SqlConnection cn = new SqlConnection("Data Source=mahmad\\sqlexpress;Initial Catalog=emp;user id=sa;password=sql;");
cn.Open();
SqlCommand cmd = new SqlCommand("Select City_Id,City_Name From Cities");
cmd.Connection = cn;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
ds.Tables[0].DefaultView.Sort = "City_Name";
DataTable dtblCities = ds.Tables[0].DefaultView.ToTable();
Thursday, October 15, 2009
Get Base Url Of WebSite
string urlString;
urlString = "http://" + System.Web.HttpContext.Current.Request.Url.Host;
urlString = "http://" + System.Web.HttpContext.Current.Request.Url.Host;
Tuesday, October 13, 2009
Out Vs Ref Parameters
For Ref parameter you must have to assign the variable to some value;
public void Add(out int a, ref int b)
{
a = 1 + 2;
b = 3 + 4;
}
int a;
int b=0; //Ref Must Be Assigned
Add(out a, ref b);
public void Add(out int a, ref int b)
{
a = 1 + 2;
b = 3 + 4;
}
int a;
int b=0; //Ref Must Be Assigned
Add(out a, ref b);
Generic Method
public static T GMethod(T g)
{
return g;
}
Response.Write(GMethod(10));
Response.Write("
");
Response.Write(GMethod("Hi From Gineric Method !"));
=====================OutPut=============================
10
Hi From Gineric Method !
{
return g;
}
Response.Write(GMethod
Response.Write("
");
Response.Write(GMethod
=====================OutPut=============================
10
Hi From Gineric Method !
Generic Method
public static T GMethod(T g)
{
return g;
}
Response.Write(GMethod(10));
Response.Write("
");
Response.Write(GMethod("Hi From Gineric Method !"));
=====================OutPut=============================
10
Hi From Gineric Method !
{
return g;
}
Response.Write(GMethod
Response.Write("
");
Response.Write(GMethod
=====================OutPut=============================
10
Hi From Gineric Method !
Saturday, October 3, 2009
Find object is of which class
public class Super
{
}
public class a : Super
{
}
public class b : Super
{
}
public class c : Super
{
}
Super objSuper;
a objA = new a();
b objB = new b();
c objC = new c();
objSuper = objB;
if (objSuper is a)
{
Response.Write("Of A");
}
else if (objSuper is b)
{
Response.Write("Of B");
}
else
{
Response.Write("Of C");
}
================OutPut===================
Of B
{
}
public class a : Super
{
}
public class b : Super
{
}
public class c : Super
{
}
Super objSuper;
a objA = new a();
b objB = new b();
c objC = new c();
objSuper = objB;
if (objSuper is a)
{
Response.Write("Of A");
}
else if (objSuper is b)
{
Response.Write("Of B");
}
else
{
Response.Write("Of C");
}
================OutPut===================
Of B
Friday, October 2, 2009
Use Of PageMethods In Javascript To Call Server Side Method
1. .aspx page
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
< html xmlns="http://www.w3.org/1999/xhtml" >
< head runat="server">
< title >Untitled Page< /title >
< script language="javascript" type="text/javascript" >
function GetServerString()
{
PageMethods.getString(OnGetProductsComplete);
}
function OnGetProductsComplete(result)
{
alert(result);
}
function GetCity()
{
var txtCityId = document.getElementById('txtCityId');
var id = txtCityId.value;
PageMethods.getCityById(id,OnGetProductsComplete);
}
< /script >
< /head >
< body >
< form id="form1" runat="server" >
< /form >
< /body >
< /html >
2. .aspx.cs file
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static string getString()
{
return ("Hi Mahmad !");
}
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static string getCityById(int CityId)
{
SqlConnection cn = new SqlConnection("Database=Emp;Server=mahmad\\sqlexpress;User Id=sa;password=sql;");
SqlCommand cmd = new SqlCommand("select City_Name from cities Where City_ID=" + CityId);
cmd.Connection = cn;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
cn.Close();
cmd.Dispose();
return ds.Tables[0].Rows[0]["City_Name"].ToString();
}
cn.Close();
cmd.Dispose();
return "Sorry City Not Found !";
}
}
Visit Below Link To Download Full Example
http://mahmad-khoja.googlegroups.com/web/WebMethodExample.rar
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
< html xmlns="http://www.w3.org/1999/xhtml" >
< head runat="server">
< title >Untitled Page< /title >
< script language="javascript" type="text/javascript" >
function GetServerString()
{
PageMethods.getString(OnGetProductsComplete);
}
function OnGetProductsComplete(result)
{
alert(result);
}
function GetCity()
{
var txtCityId = document.getElementById('txtCityId');
var id = txtCityId.value;
PageMethods.getCityById(id,OnGetProductsComplete);
}
< /script >
< /head >
< body >
< form id="form1" runat="server" >
< /form >
< /body >
< /html >
2. .aspx.cs file
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static string getString()
{
return ("Hi Mahmad !");
}
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static string getCityById(int CityId)
{
SqlConnection cn = new SqlConnection("Database=Emp;Server=mahmad\\sqlexpress;User Id=sa;password=sql;");
SqlCommand cmd = new SqlCommand("select City_Name from cities Where City_ID=" + CityId);
cmd.Connection = cn;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
cn.Close();
cmd.Dispose();
return ds.Tables[0].Rows[0]["City_Name"].ToString();
}
cn.Close();
cmd.Dispose();
return "Sorry City Not Found !";
}
}
Visit Below Link To Download Full Example
http://mahmad-khoja.googlegroups.com/web/WebMethodExample.rar
Tuesday, September 15, 2009
Find Nth Highest Salary
Select *
From Employee_Salary
OUTPUT
Emp_Id Emp_Name Salary
1 Mahmad 13500
2 Bharat 9000
3 Tausif 8000
4 Amol 8500
5 Rajkumar 24500
6 Pankaj 28200
7 Sameer 18000
8 Sunil 16800
Below query will give third highest salary employee
Select *
From (
select Emp_Id,Emp_Name,Salary,
Dense_Rank() Over (Order By Salary Desc) as Dense_Rank
from Employee_Salary
) as A
Where A.Dense_Rank = 3
OUTPUT
Emp_Id Emp_Name Salary Dense_Rank
7 Sameer 18000 3
From Employee_Salary
OUTPUT
Emp_Id Emp_Name Salary
1 Mahmad 13500
2 Bharat 9000
3 Tausif 8000
4 Amol 8500
5 Rajkumar 24500
6 Pankaj 28200
7 Sameer 18000
8 Sunil 16800
Below query will give third highest salary employee
Select *
From (
select Emp_Id,Emp_Name,Salary,
Dense_Rank() Over (Order By Salary Desc) as Dense_Rank
from Employee_Salary
) as A
Where A.Dense_Rank = 3
OUTPUT
Emp_Id Emp_Name Salary Dense_Rank
7 Sameer 18000 3
Wednesday, September 9, 2009
Fill Dropdown using web service and javascript
Fill Dropdown using web service and javascript
1 .aspx page
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="WebServiceCallApp.Default" EnableEventValidation="false" %>
transitional.dtd">
< html xmlns="http://www.w3.org/1999/xhtml">
< head runat="server">
< title >Web Service call from client-side JavaScript
< script language="javascript" type="text/javascript">
function Button1_onclick() {
var StateList = document.getElementById("ddl_States");
var selectedStateId = StateList.options[StateList.selectedIndex].value;
MySampleService.GetCities(selectedStateId, OnComplete, OnError, OnTimeOut);
}
function OnComplete(arg)
{
var xmlDoc = new ActiveXObject("MSXML2.DomDocument");
xmlDoc.loadXML(arg.xml);
var items = xmlDoc.getElementsByTagName('City_Name');
var CityList = document.getElementById("ddl_Cities");
for (var count = CityList.options.length-1; count >-1; count--)
{
CityList.options[count] = null;
}
var textValue;
var optionItem;
for (var count = 0; count < items.length; count++)
{
optionItem = new Option(xmlDoc.getElementsByTagName('City_Name')(count).text,
xmlDoc.getElementsByTagName('City_Id')(count).text, false, false);
CityList.options[count] = optionItem;
}
}
function OnTimeOut(arg)
{
alert("timeOut has occured");
}
function OnError(arg)
{
alert("error has occured: " + arg._message);
}
< /script >
< /head >
< body >
< form id="form1" runat="server">
< table style="width: 100%">
< tr>
< td style="width: 19%" align="right">
States
< td style="width: 1%">
:
< td style="width: 100px">
< /tr >
< tr >
< td style="width: 19%" align="right">
Cities
< td style="width: 1%">
:
< td style="width: 100px">
< /tr >
< tr >
< td colspan="3">
/>
< /tr >
< /table>
2. .aspx.cs file
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data;
using System.Data.SqlClient;
namespace WebServiceCallApp
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection cn = new SqlConnection("Data Source=MAHMAD\\SQLEXPRESS;Initial Catalog=
Emp;UId=sa;Password=sql;");
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "select State_Id,State_Name from dbo.States Order By State_Name";
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
ddl_States.DataTextField = "State_Name";
ddl_States.DataValueField = "State_Id";
ddl_States.DataSource = ds;
ddl_States.DataBind();
SqlCommand cmd1 = new SqlCommand();
cmd1.Connection = cn;
cmd1.CommandText = "select City_Id,City_Name from dbo.Cities where state_id=" +
Convert.ToInt32(ddl_States.SelectedValue) + " Order By City_Name";
SqlDataAdapter adp1 = new SqlDataAdapter(cmd1);
DataSet ds1 = new DataSet();
adp1.Fill(ds1);
ddl_Cities.DataTextField = "City_Name";
ddl_Cities.DataValueField = "City_Id";
ddl_Cities.DataSource = ds1;
ddl_Cities.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string selectedVal = Request[ddl_Cities.UniqueID];
Response.Write(selectedVal);
}
}
}
3. .asmx.cs page
using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data.SqlClient;
using System.Data;
///
///
/// Project: AJAX enabled Web Service
/// Company: semenoff, http://www.semenoff.dk
/// Author: Rostislav Semenov, http://www.semenoff.dk
/// Created: August 2007
///
[WebService(Namespace = "http://semenoff.dk/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]
public class MySampleService : System.Web.Services.WebService
{
public MySampleService()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string GetServerResponse(string callerName)
{
if(callerName== string.Empty)
throw new Exception("Web Service Exception: invalid argument");
return string.Format("Service responded to {0} at {1}", callerName,
DateTime.Now.ToString());
}
[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat =
System.Web.Script.Services.ResponseFormat.Xml)]
public DataSet GetCities(int StateId)
{
SqlConnection cn = new SqlConnection("Data Source=MAHMAD\\SQLEXPRESS;Initial Catalog=
Emp;UId=sa;Password=sql;");
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "select City_Id,City_Name from dbo.Cities where state_id=" + StateId + " Order
By City_Name";
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
return ds;
}
}
1 .aspx page
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="WebServiceCallApp.Default" EnableEventValidation="false" %>
transitional.dtd">
< html xmlns="http://www.w3.org/1999/xhtml">
< head runat="server">
< title >Web Service call from client-side JavaScript
< script language="javascript" type="text/javascript">
function Button1_onclick() {
var StateList = document.getElementById("ddl_States");
var selectedStateId = StateList.options[StateList.selectedIndex].value;
MySampleService.GetCities(selectedStateId, OnComplete, OnError, OnTimeOut);
}
function OnComplete(arg)
{
var xmlDoc = new ActiveXObject("MSXML2.DomDocument");
xmlDoc.loadXML(arg.xml);
var items = xmlDoc.getElementsByTagName('City_Name');
var CityList = document.getElementById("ddl_Cities");
for (var count = CityList.options.length-1; count >-1; count--)
{
CityList.options[count] = null;
}
var textValue;
var optionItem;
for (var count = 0; count < items.length; count++)
{
optionItem = new Option(xmlDoc.getElementsByTagName('City_Name')(count).text,
xmlDoc.getElementsByTagName('City_Id')(count).text, false, false);
CityList.options[count] = optionItem;
}
}
function OnTimeOut(arg)
{
alert("timeOut has occured");
}
function OnError(arg)
{
alert("error has occured: " + arg._message);
}
< /script >
< /head >
< body >
< form id="form1" runat="server">
< table style="width: 100%">
< tr>
< td style="width: 19%" align="right">
States
< td style="width: 1%">
:
< td style="width: 100px">
< /tr >
< tr >
< td style="width: 19%" align="right">
Cities
< td style="width: 1%">
:
< td style="width: 100px">
< /tr >
< tr >
< td colspan="3">
/>
< /tr >
< /table>
2. .aspx.cs file
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data;
using System.Data.SqlClient;
namespace WebServiceCallApp
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection cn = new SqlConnection("Data Source=MAHMAD\\SQLEXPRESS;Initial Catalog=
Emp;UId=sa;Password=sql;");
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "select State_Id,State_Name from dbo.States Order By State_Name";
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
ddl_States.DataTextField = "State_Name";
ddl_States.DataValueField = "State_Id";
ddl_States.DataSource = ds;
ddl_States.DataBind();
SqlCommand cmd1 = new SqlCommand();
cmd1.Connection = cn;
cmd1.CommandText = "select City_Id,City_Name from dbo.Cities where state_id=" +
Convert.ToInt32(ddl_States.SelectedValue) + " Order By City_Name";
SqlDataAdapter adp1 = new SqlDataAdapter(cmd1);
DataSet ds1 = new DataSet();
adp1.Fill(ds1);
ddl_Cities.DataTextField = "City_Name";
ddl_Cities.DataValueField = "City_Id";
ddl_Cities.DataSource = ds1;
ddl_Cities.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string selectedVal = Request[ddl_Cities.UniqueID];
Response.Write(selectedVal);
}
}
}
3. .asmx.cs page
using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data.SqlClient;
using System.Data;
///
///
/// Project: AJAX enabled Web Service
/// Company: semenoff, http://www.semenoff.dk
/// Author: Rostislav Semenov, http://www.semenoff.dk
/// Created: August 2007
///
[WebService(Namespace = "http://semenoff.dk/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]
public class MySampleService : System.Web.Services.WebService
{
public MySampleService()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string GetServerResponse(string callerName)
{
if(callerName== string.Empty)
throw new Exception("Web Service Exception: invalid argument");
return string.Format("Service responded to {0} at {1}", callerName,
DateTime.Now.ToString());
}
[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat =
System.Web.Script.Services.ResponseFormat.Xml)]
public DataSet GetCities(int StateId)
{
SqlConnection cn = new SqlConnection("Data Source=MAHMAD\\SQLEXPRESS;Initial Catalog=
Emp;UId=sa;Password=sql;");
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "select City_Id,City_Name from dbo.Cities where state_id=" + StateId + " Order
By City_Name";
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
return ds;
}
}
Monday, August 31, 2009
What is Asp.Net ?
ASP.NET is a web application framework by Microsoft to allow programmers to build dynamic web sites, web applications and web services.
Saturday, August 1, 2009
Ranking Functions
Use Of Ranking Functions
Like Row_Number() , Rank() , Dense_Rank()
Select
Row_Number() Over ( Order By Percentage Desc) as Sr_No,
Rank() Over (Order By Percentage Desc) as Rank,
Dense_Rank() Over (Order By Percentage Desc) as Dense_Rank,
Student_Name,
Percentage
From Students
Sr_No Rank Dense_Rank Student_Name Percentage
1 1 1 Ankur 80.00
2 2 2 Vinod 78.00
3 2 2 Mahmad 78.00
4 4 3 Amol 70.00
5 4 3 Varun 70.00
6 6 4 Rajesh 69.00
7 6 4 Bharat 69.00
8 8 5 Parixit 35.00
Like Row_Number() , Rank() , Dense_Rank()
Select
Row_Number() Over ( Order By Percentage Desc) as Sr_No,
Rank() Over (Order By Percentage Desc) as Rank,
Dense_Rank() Over (Order By Percentage Desc) as Dense_Rank,
Student_Name,
Percentage
From Students
Sr_No Rank Dense_Rank Student_Name Percentage
1 1 1 Ankur 80.00
2 2 2 Vinod 78.00
3 2 2 Mahmad 78.00
4 4 3 Amol 70.00
5 4 3 Varun 70.00
6 6 4 Rajesh 69.00
7 6 4 Bharat 69.00
8 8 5 Parixit 35.00
Tuesday, July 28, 2009
Recursive Stored Procedure
Create PROCEDURE Factorial
@Number as int,
@Factorial as int OUTPUT
AS
Begin
DECLARE @Input int
DECLARE @Output int
IF @Number != 1
BEGIN
set @Input = @Number - 1
EXEC Factorial @Input, @Output OUTPUT
SELECT @Factorial = @Number * @Output
END
ELSE
BEGIN
SELECT @Factorial = 1
END
RETURN
End
@Number as int,
@Factorial as int OUTPUT
AS
Begin
DECLARE @Input int
DECLARE @Output int
IF @Number != 1
BEGIN
set @Input = @Number - 1
EXEC Factorial @Input, @Output OUTPUT
SELECT @Factorial = @Number * @Output
END
ELSE
BEGIN
SELECT @Factorial = 1
END
RETURN
End
Monday, July 27, 2009
Generate Serial Number In SQL Server 2005
select Row_Number() over (order by Emp_Id) as SrNo ,Emp_Id,Emp_Name
from mstEmployee
from mstEmployee
Thursday, May 7, 2009
Candidate Key
A Candidate Key is a column or group of columns that uniquely describe every row in a table.
Wednesday, April 22, 2009
Disabling Validation On Cancel Buttons Click In Asp.Net
Disabling Client-Side Validation on cancel button's click
< asp: Button id="CancelButton" runat="server" Text="Cancel" EnableClientScript="False" / >
Disabling Client-Side and Server-Side Validation on cancel button's click
< asp :Button id="CancelButton" runat="server" Text="Cancel" CausesValidation="False" / >
< asp: Button id="CancelButton" runat="server" Text="Cancel" EnableClientScript="False" / >
Disabling Client-Side and Server-Side Validation on cancel button's click
< asp :Button id="CancelButton" runat="server" Text="Cancel" CausesValidation="False" / >
Saturday, April 11, 2009
Open Model Popup Window In JavaScript
function OpenModelPopupWindow(Path,Height,Width)
{
var ParmA = '';
var MyArgs = new Array(ParmA);
var w = screen.availWidth;
var h = screen.availHeight;
var Wdth = (w-Width);
var Hgt = (h-Height);
var WinSettings = "help:no;center:yes;resizable:no;dialogHeight:" + Hgt +"px;dialogWidth:" + Wdth + "px;status=no;"
window.showModalDialog(Path,MyArgs, WinSettings );
}
{
var ParmA = '';
var MyArgs = new Array(ParmA);
var w = screen.availWidth;
var h = screen.availHeight;
var Wdth = (w-Width);
var Hgt = (h-Height);
var WinSettings = "help:no;center:yes;resizable:no;dialogHeight:" + Hgt +"px;dialogWidth:" + Wdth + "px;status=no;"
window.showModalDialog(Path,MyArgs, WinSettings );
}
Friday, April 10, 2009
Magic table in sql server
When we are inserting or deleting any data from table in transaction a temporary table
(inserted , deleted) is created and will be deleted when we call commit tran or rollback tran, the
table is called magic table.
(inserted , deleted) is created and will be deleted when we call commit tran or rollback tran, the
table is called magic table.
Saturday, April 4, 2009
Get Property In Javascript
< script language=" javascript " type=" text/ javascript ">
var StudentName=' < % = StudentName % > ';
< / script>
var StudentName=' < % = StudentName % > ';
< / script>
Thursday, April 2, 2009
Tuesday, March 31, 2009
Bind Link Button In DataGrid With Java Script
< asp:TemplateColumn HeaderText="ShowStudent" >
< ItemTemplate >
< a href='javascript: NewWindowForStudent( < % # DataBinder . Eval ( Container . DataItem, "Roll")%>,<%#DataBinder.Eval(Container.DataItem, "Name")%>)'>Show Student< /a >
< / ItemTemplate >
< / asp:TemplateColumn >
< ItemTemplate >
< a href='javascript: NewWindowForStudent( < % # DataBinder . Eval ( Container . DataItem, "Roll")%>,<%#DataBinder.Eval(Container.DataItem, "Name")%>)'>Show Student< /a >
< / ItemTemplate >
< / asp:TemplateColumn >
Saturday, March 28, 2009
Which methods are fired during the page load?
Init() - when the page is instantiated
Load() - when the page is loaded into server memory
PreRender() - the brief moment before the page is displayed to the user as HTML
Unload() - when page finishes loading.
Load() - when the page is loaded into server memory
PreRender() - the brief moment before the page is displayed to the user as HTML
Unload() - when page finishes loading.
Thursday, March 26, 2009
Tuesday, March 24, 2009
Naming Conventions
Pascal Casing convention :
capitalizes the first character of each word.
Camel Casing convention :
capitalizes the first character of each word except the first word.
• Pascal Casing
o Class Name e.g. StudentClass
o Method Name (Sub or Function) e.g. FindStudent()
o Interface Name e.g. Istudent
• Camel Casing
o Private Variables e.g. studName
o Local Variables e.g. studCount
o Parameters Name e.g. studRoll
• Upper Casing
o Namespace should include Company Name followed by Module or System Name. e.g. COMP_SALES
o Constants e.g. COMPANY_NAME
• Other Useful Note:
o Parameters Name should followed by small ‘p’ to differentiate with the local variable
o Do not prefix data type in local variable, since this is not helpful in modern
o development environment. E.g.: strLocalvariable, intLocalVariable.
Interface name should be Prefixed with capital ‘I’
capitalizes the first character of each word.
Camel Casing convention :
capitalizes the first character of each word except the first word.
• Pascal Casing
o Class Name e.g. StudentClass
o Method Name (Sub or Function) e.g. FindStudent()
o Interface Name e.g. Istudent
• Camel Casing
o Private Variables e.g. studName
o Local Variables e.g. studCount
o Parameters Name e.g. studRoll
• Upper Casing
o Namespace should include Company Name followed by Module or System Name. e.g. COMP_SALES
o Constants e.g. COMPANY_NAME
• Other Useful Note:
o Parameters Name should followed by small ‘p’ to differentiate with the local variable
o Do not prefix data type in local variable, since this is not helpful in modern
o development environment. E.g.: strLocalvariable, intLocalVariable.
Interface name should be Prefixed with capital ‘I’
Monday, March 23, 2009
Error ! there is no editor is available for .cs make sure the application for the file type(.cs) is installed
when you cannot see the form or form controls in visual studio.
go to Visual Studio Command Prompt and run the following commands.
Please close all the VS windows before running these commands.
devenv.exe /setup
devenv /resetskippkgs
go to Visual Studio Command Prompt and run the following commands.
Please close all the VS windows before running these commands.
devenv.exe /setup
devenv /resetskippkgs
Saturday, March 21, 2009
What is the difference between an interface and abstract class?
(1)
In an interface , all methods are abstract and there is no any implementation.
In an abstract class some methods can be concrete.
(2)
In an interface class, no accessibility modifiers are allowed like public,private they are all public by default.
An abstract class may have accessibility modifiers.
In an interface , all methods are abstract and there is no any implementation.
In an abstract class some methods can be concrete.
(2)
In an interface class, no accessibility modifiers are allowed like public,private they are all public by default.
An abstract class may have accessibility modifiers.
Thursday, March 19, 2009
What is property ?
A property is a thing that describes the features / characteristics of an object (i.e class). Suppose a "Chair" is a class , design name,color,brand will be its property.
Wednesday, March 18, 2009
What is an abstract class?
An abstract class is a class that must be inherited and it's method be overriden. In other word abstract class is a blueprint of a class without any implementation.
Tuesday, March 17, 2009
How to find if variable exist or null in javascript ?
When you want to know if the variable is null then you can use :
if ( null == var ) // with type casting
if ( null === var ) // without type casting
When you want to check existance of variable you can use :
if ( typeof var != ‘undefined’ ) // Any scope
if ( null == var ) // with type casting
if ( null === var ) // without type casting
When you want to check existance of variable you can use :
if ( typeof var != ‘undefined’ ) // Any scope
Friday, March 13, 2009
Concatenate Rows Into A String Variable
DECLARE @Course varchar(Max)
SELECT @Course = COALESCE(@Course + ' , ', '') + Course_Name
FROM Course
where Course_Name like 'B%'
print @Course
SELECT @Course = COALESCE(@Course + ' , ', '') + Course_Name
FROM Course
where Course_Name like 'B%'
print @Course
Thursday, March 12, 2009
Run Stored Procedure In Asp.net With Parameters
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "server=server;initial catalog=abc;uid=abc;pwd=abc;";
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "[dbo].[sp_Fetch_Context_Sensitive_Help]";
SqlParameter para1 = new SqlParameter("@Para1",SqlDbType.VarChar,500);
para1.Direction = ParameterDirection.Input;
para1.Value="1000";
SqlParameter para2 = new SqlParameter("@Para2",SqlDbType.VarChar ,-1 ); // for varchar(max)
para2.Direction = ParameterDirection.Output;
cmd.Parameters.Add(para1);
cmd.Parameters.Add(para2);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
cn.ConnectionString = "server=server;initial catalog=abc;uid=abc;pwd=abc;";
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "[dbo].[sp_Fetch_Context_Sensitive_Help]";
SqlParameter para1 = new SqlParameter("@Para1",SqlDbType.VarChar,500);
para1.Direction = ParameterDirection.Input;
para1.Value="1000";
SqlParameter para2 = new SqlParameter("@Para2",SqlDbType.VarChar ,-1 ); // for varchar(max)
para2.Direction = ParameterDirection.Output;
cmd.Parameters.Add(para1);
cmd.Parameters.Add(para2);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
Monday, March 9, 2009
Restrict length of multiline textbox in asp.net
function checkMaxLength( txt,e, length )
{
var mLen = txt[ " MaxLength " ];
if(null == mLen)
mLen = length;
var maxLength = parseInt ( mLen );
if(!isSpecialCharacters( e ))
{
if(txt.value.length > maxLength-1)
{
if(window.event)//for Internet Explorer
e.returnValue = false;
else// For Firefox
e.preventDefault();
}
}
}
function isSpecialCharacters(e)
{
if(e.keyCode !=8 && e.keyCode!=46 && e.keyCode!=37 && e.keyCode!=38 && e.keyCode!=39 && e.keyCode!=40)
return false;
else
return true;
}
add this in code behind file of the control
onkeyDown="checkMaxLength( this ,event ,'100' );"
{
var mLen = txt[ " MaxLength " ];
if(null == mLen)
mLen = length;
var maxLength = parseInt ( mLen );
if(!isSpecialCharacters( e ))
{
if(txt.value.length > maxLength-1)
{
if(window.event)//for Internet Explorer
e.returnValue = false;
else// For Firefox
e.preventDefault();
}
}
}
function isSpecialCharacters(e)
{
if(e.keyCode !=8 && e.keyCode!=46 && e.keyCode!=37 && e.keyCode!=38 && e.keyCode!=39 && e.keyCode!=40)
return false;
else
return true;
}
add this in code behind file of the control
onkeyDown="checkMaxLength( this ,event ,'100' );"
Tuesday, March 3, 2009
Use Of TabStrip In Asp.Net
First Of All you have to install component art.
<%-- Register Component Art --%>
<% @ Register Assembly = "ComponentArt.Web.UI" TagPrefix = "ComponentArt" Namespace = "ComponentArt.Web.UI" % >
< %-- Register Your Page Or Control Here --% >
< % @ Register Src="~/wuc_MyUserControlOne.ascx" TagName="wuc_MyUserControlOne" TagPrefix="uc1" % >
< % @ Register Src="~/wuc_MyUserControlTwo.ascx" TagName="wuc_MyUserControlTwo" TagPrefix="uc1" % >
< componentart:tabstrip id="tbs_Name"
runat="server"
SiteMapXmlFile="~/file.xml"
EnableViewState="False"
MultiPageId="MP_Name">
< / componentart:tabstrip >
< ComponentArt:MultiPage ID = "MP_Name" runat = "server" CssClass="MULTIPAGE" >
< ComponentArt:PageView runat = "server" >
< uc1:wuc_MyUserControlOne ID="wuc_MyUserControlOne1" runat="server" />
< / ComponentArt:PageView >
< ComponentArt:PageView runat = "server" >
< uc1:wuc_MyUserControlTwo ID="wuc_MyUserControlTwo1" runat="server" / >
< / ComponentArt:PageView >
< / ComponentArt:MultiPage >
=============================================><=======================================
Your SiteMapXmlFile Will be as shown below
< ? xml version="1.0" encoding="utf-8" ? >
< tabs >
< tab id="zero" text="Zero"> < / tab >
< tab id="one" text="One"> < / tab >
< / tabs >
<%-- Register Component Art --%>
<% @ Register Assembly = "ComponentArt.Web.UI" TagPrefix = "ComponentArt" Namespace = "ComponentArt.Web.UI" % >
< %-- Register Your Page Or Control Here --% >
< % @ Register Src="~/wuc_MyUserControlOne.ascx" TagName="wuc_MyUserControlOne" TagPrefix="uc1" % >
< % @ Register Src="~/wuc_MyUserControlTwo.ascx" TagName="wuc_MyUserControlTwo" TagPrefix="uc1" % >
< componentart:tabstrip id="tbs_Name"
runat="server"
SiteMapXmlFile="~/file.xml"
EnableViewState="False"
MultiPageId="MP_Name">
< / componentart:tabstrip >
< ComponentArt:MultiPage ID = "MP_Name" runat = "server" CssClass="MULTIPAGE" >
< ComponentArt:PageView runat = "server" >
< uc1:wuc_MyUserControlOne ID="wuc_MyUserControlOne1" runat="server" />
< / ComponentArt:PageView >
< ComponentArt:PageView runat = "server" >
< uc1:wuc_MyUserControlTwo ID="wuc_MyUserControlTwo1" runat="server" / >
< / ComponentArt:PageView >
< / ComponentArt:MultiPage >
=============================================><=======================================
Your SiteMapXmlFile Will be as shown below
< ? xml version="1.0" encoding="utf-8" ? >
< tabs >
< tab id="zero" text="Zero"> < / tab >
< tab id="one" text="One"> < / tab >
< / tabs >
Monday, March 2, 2009
How to get ASP.NET Page Name at Runtime
System.IO.FileInfo fInfo = new System.IO.FileInfo(Request.PhysicalPath);
Response.Write( fInfo.Name);
Response.Write( fInfo.Name);
Wednesday, February 25, 2009
Unique Key Vs Primary Key
One difference is that a unique key constraint can be created over columns with null values, while a primary key constraint does not allow null values. The other difference is that there can only be one primary key constraint defined on a table, but there can be multiple unique key constraints defined on a table.
Monday, February 23, 2009
Sync Foreign Keys In Sql Server 2005
List all foreigh keys in sql 2005
SELECT f.name AS ForeignKey,
OBJECT_NAME(f.parent_object_id) AS TableName,
COL_NAME(fc.parent_object_id,
fc.parent_column_id) AS ColumnName,
OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName,
COL_NAME(fc.referenced_object_id,
fc.referenced_column_id) AS ReferenceColumnName
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc
ON f.OBJECT_ID = fc.constraint_object_id
Order By f.name , OBJECT_NAME(f.parent_object_id),fc.constraint_column_id
Sync foreigh key in sql 2005
BEGIN TRAN
BEGIN TRY
set nocount on
Declare @idoc int
set @Error_Code=0
set @Error_Desc=''
Declare @ConstraintTable Table
(
Sr_No Int Identity(1,1),
ForeignKey Varchar(Max),
TableName Varchar(Max),
ColumnName Varchar(Max),
ReferenceTableName Varchar(Max),
ReferenceColumnName Varchar(Max)
)
exec sp_xml_preparedocument @idoc output , @ConstraintsXML
Insert Into @ConstraintTable
Select ForeignKey,
TableName,
ColumnName,
ReferenceTableName,
ReferenceColumnName
From OpenXML(@idoc,'/NewDataSet/Table',2)
With (
ForeignKey Varchar(Max),
TableName Varchar(Max),
ColumnName Varchar(Max),
ReferenceTableName Varchar(Max),
ReferenceColumnName Varchar(Max)
)
Order By ForeignKey,TableName
exec sp_xml_removedocument @idoc
Declare @ForeignKey Varchar(Max)
Declare @TableName Varchar(Max)
Declare @ColumnName Varchar(Max)
Declare @ReferenceTableName Varchar(Max)
Declare @ReferenceColumnName Varchar(Max)
Declare @CTableName Varchar(Max)
Declare @CColumnName Varchar(Max)
Declare @CReferenceTableName Varchar(Max)
Declare @CReferenceColumnName Varchar(Max)
Declare @SrNo Int
Declare @ForeignKeyString Varchar(Max)
Declare @Rows Int
Declare @CommandStr Varchar(Max)
Set @SrNo = 1
Set @ForeignKeyString = ''
Select @Rows = Count(*) From @ConstraintTable
--Select * From @ConstraintTable
Set @CTableName = ''
Set @CColumnName = ''
Set @CReferenceTableName = ''
Set @CReferenceColumnName = ''
Select * From @ConstraintTable
While @SrNo < = @Rows + 1
Begin
Select @ForeignKey = ForeignKey,
@TableName = TableName,
@ColumnName = ColumnName,
@ReferenceTableName = ReferenceTableName,
@ReferenceColumnName = ReferenceColumnName
From @ConstraintTable
Where Sr_No = @SrNo
--print @ForeignKey
--print @SrNo
IF (@ForeignKeyString = @ForeignKey) And @SrNo <= @Rows
Begin --Same Key Append Column Names
set @CColumnName = @CColumnName + ',' + @ColumnName
set @CReferenceColumnName = @CReferenceColumnName + ',' + @ReferenceColumnName
End --Same Key Append Column Names
Else
Begin --Another Foreigh Key Make new command
If Len(@ForeignKeyString)>0
Begin
Set @CommandStr = 'If Exists( select * FROM sys.foreign_keys Where Name=' + CHAR(39) + @ForeignKeyString + Char(39) +') ALTER TABLE '
Set @CommandStr = @CommandStr + @CTableName + ' DROP CONSTRAINT [' + @ForeignKeyString +']'
--print @CommandStr
exec (@CommandStr)
Set @CommandStr = ' ALTER TABLE ' + @CTableName
Set @CommandStr = @CommandStr + ' WITH NOCHECK ADD CONSTRAINT [' + @ForeignKeyString + ']'
Set @CommandStr = @CommandStr + ' FOREIGN KEY (' + @CColumnName + ') '
Set @CommandStr = @CommandStr + ' REFERENCES ' + @CReferenceTableName + '(' + @CReferenceColumnName + ')'
--print @CommandStr
exec (@CommandStr)
End
Set @ForeignKeyString = @ForeignKey
Set @CTableName = @TableName
Set @CColumnName = @ColumnName
Set @CReferenceTableName = @ReferenceTableName
Set @CReferenceColumnName = @ReferenceColumnName
End --Another Foreigh Key Make new command
Set @SrNo = @SrNo + 1
End
COMMIT TRAN
print 'Sync Successfull !'
END TRY
BEGIN CATCH
ROLLBACK TRAN
Select @Error_Code = cast(ERROR_NUMBER() as varchar(5))
Select @Error_Desc = @CommandStr + char(13) + CAST(ERROR_LINE() AS VARCHAR(4000)) + 'Ö' + CAST(ERROR_MESSAGE() as VARCHAR(4000)) /*+ 'll'+ @query*/
print @Error_Code
print @Error_Desc
END CATCH
SELECT f.name AS ForeignKey,
OBJECT_NAME(f.parent_object_id) AS TableName,
COL_NAME(fc.parent_object_id,
fc.parent_column_id) AS ColumnName,
OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName,
COL_NAME(fc.referenced_object_id,
fc.referenced_column_id) AS ReferenceColumnName
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc
ON f.OBJECT_ID = fc.constraint_object_id
Order By f.name , OBJECT_NAME(f.parent_object_id),fc.constraint_column_id
Sync foreigh key in sql 2005
BEGIN TRAN
BEGIN TRY
set nocount on
Declare @idoc int
set @Error_Code=0
set @Error_Desc=''
Declare @ConstraintTable Table
(
Sr_No Int Identity(1,1),
ForeignKey Varchar(Max),
TableName Varchar(Max),
ColumnName Varchar(Max),
ReferenceTableName Varchar(Max),
ReferenceColumnName Varchar(Max)
)
exec sp_xml_preparedocument @idoc output , @ConstraintsXML
Insert Into @ConstraintTable
Select ForeignKey,
TableName,
ColumnName,
ReferenceTableName,
ReferenceColumnName
From OpenXML(@idoc,'/NewDataSet/Table',2)
With (
ForeignKey Varchar(Max),
TableName Varchar(Max),
ColumnName Varchar(Max),
ReferenceTableName Varchar(Max),
ReferenceColumnName Varchar(Max)
)
Order By ForeignKey,TableName
exec sp_xml_removedocument @idoc
Declare @ForeignKey Varchar(Max)
Declare @TableName Varchar(Max)
Declare @ColumnName Varchar(Max)
Declare @ReferenceTableName Varchar(Max)
Declare @ReferenceColumnName Varchar(Max)
Declare @CTableName Varchar(Max)
Declare @CColumnName Varchar(Max)
Declare @CReferenceTableName Varchar(Max)
Declare @CReferenceColumnName Varchar(Max)
Declare @SrNo Int
Declare @ForeignKeyString Varchar(Max)
Declare @Rows Int
Declare @CommandStr Varchar(Max)
Set @SrNo = 1
Set @ForeignKeyString = ''
Select @Rows = Count(*) From @ConstraintTable
--Select * From @ConstraintTable
Set @CTableName = ''
Set @CColumnName = ''
Set @CReferenceTableName = ''
Set @CReferenceColumnName = ''
Select * From @ConstraintTable
While @SrNo < = @Rows + 1
Begin
Select @ForeignKey = ForeignKey,
@TableName = TableName,
@ColumnName = ColumnName,
@ReferenceTableName = ReferenceTableName,
@ReferenceColumnName = ReferenceColumnName
From @ConstraintTable
Where Sr_No = @SrNo
--print @ForeignKey
--print @SrNo
IF (@ForeignKeyString = @ForeignKey) And @SrNo <= @Rows
Begin --Same Key Append Column Names
set @CColumnName = @CColumnName + ',' + @ColumnName
set @CReferenceColumnName = @CReferenceColumnName + ',' + @ReferenceColumnName
End --Same Key Append Column Names
Else
Begin --Another Foreigh Key Make new command
If Len(@ForeignKeyString)>0
Begin
Set @CommandStr = 'If Exists( select * FROM sys.foreign_keys Where Name=' + CHAR(39) + @ForeignKeyString + Char(39) +') ALTER TABLE '
Set @CommandStr = @CommandStr + @CTableName + ' DROP CONSTRAINT [' + @ForeignKeyString +']'
--print @CommandStr
exec (@CommandStr)
Set @CommandStr = ' ALTER TABLE ' + @CTableName
Set @CommandStr = @CommandStr + ' WITH NOCHECK ADD CONSTRAINT [' + @ForeignKeyString + ']'
Set @CommandStr = @CommandStr + ' FOREIGN KEY (' + @CColumnName + ') '
Set @CommandStr = @CommandStr + ' REFERENCES ' + @CReferenceTableName + '(' + @CReferenceColumnName + ')'
--print @CommandStr
exec (@CommandStr)
End
Set @ForeignKeyString = @ForeignKey
Set @CTableName = @TableName
Set @CColumnName = @ColumnName
Set @CReferenceTableName = @ReferenceTableName
Set @CReferenceColumnName = @ReferenceColumnName
End --Another Foreigh Key Make new command
Set @SrNo = @SrNo + 1
End
COMMIT TRAN
print 'Sync Successfull !'
END TRY
BEGIN CATCH
ROLLBACK TRAN
Select @Error_Code = cast(ERROR_NUMBER() as varchar(5))
Select @Error_Desc = @CommandStr + char(13) + CAST(ERROR_LINE() AS VARCHAR(4000)) + 'Ö' + CAST(ERROR_MESSAGE() as VARCHAR(4000)) /*+ 'll'+ @query*/
print @Error_Code
print @Error_Desc
END CATCH
Saturday, February 21, 2009
ADO.NET Functions for Running Query and Procedures
public DataSet RunQuery(string Query)
{
OpenDB();
SqlCommand sqlCmd = new SqlCommand(Query, sqlConn);
sqlCmd.CommandType = CommandType.Text;
SqlDataAdapter dtAdapter = new SqlDataAdapter(sqlCmd);
DataSet dtSetObject = new DataSet();
dtAdapter.Fill(dtSetObject);
sqlCmd.Dispose();
this.Dispose();
return dtSetObject;
}
public int RunProc(string procName)
{
SqlCommand sqlCmd = CreateCommand(procName, null);
sqlCmd.ExecuteNonQuery();
sqlCmd.Dispose();
this.Dispose();
return (int)sqlCmd.Parameters["ReturnValue"].Value;
}
public int RunProc(string procName, SqlParameter[] @params)
{
SqlCommand sqlCmd = CreateCommand(procName, @params);
sqlCmd.ExecuteNonQuery();
sqlCmd.Dispose();
this.Dispose();
return (int)sqlCmd.Parameters["ReturnValue"].Value;
}
private void RunProc(string procName, ref SqlDataReader dataReader)
{
SqlCommand sqlCmd = CreateCommand(procName, null);
dataReader = sqlCmd.ExecuteReader(CommandBehavior.CloseConnection);
}
public void RunProc(string procName, ref DataSet dataSetObject)
{
SqlCommand sqlCmd = CreateCommand(procName, null);
SqlDataAdapter dtAdapter = new SqlDataAdapter(sqlCmd);
DataSet dtSetObject = new DataSet();
dtAdapter.Fill(dtSetObject);
dataSetObject = dtSetObject;
sqlCmd.Dispose();
this.Dispose();
}
public void RunProc(string procName, SqlParameter[] @params, ref DataSet dataSetObject)
{
SqlCommand sqlCmd = CreateCommand(procName, @params);
SqlDataAdapter dtAdapter = new SqlDataAdapter(sqlCmd);
DataSet dtSetObject = new DataSet();
dtAdapter.Fill(dtSetObject);
dataSetObject = dtSetObject;
sqlCmd.Dispose();
this.Dispose();
}
private void RunProc(string procName, SqlParameter[] @params, ref SqlDataReader dataReader)
{
SqlCommand sqlCmd = CreateCommand(procName, @params);
dataReader = sqlCmd.ExecuteReader(CommandBehavior.CloseConnection);
}
private SqlCommand CreateCommand( string procName,SqlParameter[] @params )
{
OpenDB();
SqlCommand sqlCmd = null;
sqlCmd = new SqlCommand(procName, sqlConn);
sqlCmd.CommandType = CommandType.StoredProcedure;
if (@params != null)
{
foreach (SqlParameter parameter in @params)
{
sqlCmd.Parameters.Add(parameter);
}
}
sqlCmd.Parameters.Add(new SqlParameter("ReturnValue", SqlDbType.Int, 4, ParameterDirection.ReturnValue, false, 0, 0, string.Empty, DataRowVersion.Default, null));
return sqlCmd;
}
public SqlParameter MakeInParams(string paramName, SqlDbType paramType, int size, object obj)
{
return MakeParameter(paramName, paramType, size, ParameterDirection.Input, obj);
}
public SqlParameter MakeOutParams(string paramName, SqlDbType paramType, int size)
{
return MakeParameter(paramName, paramType, size, ParameterDirection.Output, null);
}
private SqlParameter MakeParameter(string paramName, SqlDbType paramType, int size, ParameterDirection paramDirection, object obj)
{
SqlParameter sqlParam = null;
if (size > 0)
{
sqlParam = new SqlParameter(paramName, paramType, size);
}
else
{
sqlParam = new SqlParameter(paramName, paramType);
}
sqlParam.Direction = paramDirection;
if (!(sqlParam.Direction == paramDirection & obj == null))
{
sqlParam.Value = obj;
}
return sqlParam;
}
private string getPoolConSting()
{
if (DBConnection.DBPoolConString == null)
{
string DBServer = ConfigurationManager.AppSettings.Get("DBServer");
string DBCredential = ConfigurationManager.AppSettings.Get("DBCredential");
DBCredential = Util.DecryptToString(DBCredential);
string PoolOn = ConfigurationManager.AppSettings.Get("PoolOn");
DBConnection.DBPoolConString = DBServer + DBCredential + PoolOn;
}
return DBConnection.DBPoolConString;
}
private string getnonPoolConString()
{
if (DBConnection.DBNonPoolConString == null)
{
string DBServer = ConfigurationManager.AppSettings.Get("DBServer");
string DBCredential = ConfigurationManager.AppSettings.Get("DBCredential");
DBCredential = Util.DecryptToString(DBCredential);
string PoolOff = ConfigurationManager.AppSettings.Get("PoolOff");
DBConnection.DBNonPoolConString = DBServer + DBCredential + PoolOff;
}
return DBConnection.DBNonPoolConString;
}
private void OpenDB()
{
if (sqlConn == null)
{
try
{
sqlConn = new SqlConnection(getPoolConSting());
sqlConn.Open();
}
catch (System.Data.SqlClient.SqlException)
{
if (sqlConn.State != ConnectionState.Closed)
{
sqlConn.Close();
sqlConn = new SqlConnection(getnonPoolConString());
sqlConn.Open();
}
}
}
}
public void Dispose()
{
if (!(System.Convert.IsDBNull(sqlConn)))
{
sqlConn.Dispose();
sqlConn = null;
}
}
public void Close()
{
if (!(System.Convert.IsDBNull(sqlConn)))
{
sqlConn.Close();
}
}
{
OpenDB();
SqlCommand sqlCmd = new SqlCommand(Query, sqlConn);
sqlCmd.CommandType = CommandType.Text;
SqlDataAdapter dtAdapter = new SqlDataAdapter(sqlCmd);
DataSet dtSetObject = new DataSet();
dtAdapter.Fill(dtSetObject);
sqlCmd.Dispose();
this.Dispose();
return dtSetObject;
}
public int RunProc(string procName)
{
SqlCommand sqlCmd = CreateCommand(procName, null);
sqlCmd.ExecuteNonQuery();
sqlCmd.Dispose();
this.Dispose();
return (int)sqlCmd.Parameters["ReturnValue"].Value;
}
public int RunProc(string procName, SqlParameter[] @params)
{
SqlCommand sqlCmd = CreateCommand(procName, @params);
sqlCmd.ExecuteNonQuery();
sqlCmd.Dispose();
this.Dispose();
return (int)sqlCmd.Parameters["ReturnValue"].Value;
}
private void RunProc(string procName, ref SqlDataReader dataReader)
{
SqlCommand sqlCmd = CreateCommand(procName, null);
dataReader = sqlCmd.ExecuteReader(CommandBehavior.CloseConnection);
}
public void RunProc(string procName, ref DataSet dataSetObject)
{
SqlCommand sqlCmd = CreateCommand(procName, null);
SqlDataAdapter dtAdapter = new SqlDataAdapter(sqlCmd);
DataSet dtSetObject = new DataSet();
dtAdapter.Fill(dtSetObject);
dataSetObject = dtSetObject;
sqlCmd.Dispose();
this.Dispose();
}
public void RunProc(string procName, SqlParameter[] @params, ref DataSet dataSetObject)
{
SqlCommand sqlCmd = CreateCommand(procName, @params);
SqlDataAdapter dtAdapter = new SqlDataAdapter(sqlCmd);
DataSet dtSetObject = new DataSet();
dtAdapter.Fill(dtSetObject);
dataSetObject = dtSetObject;
sqlCmd.Dispose();
this.Dispose();
}
private void RunProc(string procName, SqlParameter[] @params, ref SqlDataReader dataReader)
{
SqlCommand sqlCmd = CreateCommand(procName, @params);
dataReader = sqlCmd.ExecuteReader(CommandBehavior.CloseConnection);
}
private SqlCommand CreateCommand( string procName,SqlParameter[] @params )
{
OpenDB();
SqlCommand sqlCmd = null;
sqlCmd = new SqlCommand(procName, sqlConn);
sqlCmd.CommandType = CommandType.StoredProcedure;
if (@params != null)
{
foreach (SqlParameter parameter in @params)
{
sqlCmd.Parameters.Add(parameter);
}
}
sqlCmd.Parameters.Add(new SqlParameter("ReturnValue", SqlDbType.Int, 4, ParameterDirection.ReturnValue, false, 0, 0, string.Empty, DataRowVersion.Default, null));
return sqlCmd;
}
public SqlParameter MakeInParams(string paramName, SqlDbType paramType, int size, object obj)
{
return MakeParameter(paramName, paramType, size, ParameterDirection.Input, obj);
}
public SqlParameter MakeOutParams(string paramName, SqlDbType paramType, int size)
{
return MakeParameter(paramName, paramType, size, ParameterDirection.Output, null);
}
private SqlParameter MakeParameter(string paramName, SqlDbType paramType, int size, ParameterDirection paramDirection, object obj)
{
SqlParameter sqlParam = null;
if (size > 0)
{
sqlParam = new SqlParameter(paramName, paramType, size);
}
else
{
sqlParam = new SqlParameter(paramName, paramType);
}
sqlParam.Direction = paramDirection;
if (!(sqlParam.Direction == paramDirection & obj == null))
{
sqlParam.Value = obj;
}
return sqlParam;
}
private string getPoolConSting()
{
if (DBConnection.DBPoolConString == null)
{
string DBServer = ConfigurationManager.AppSettings.Get("DBServer");
string DBCredential = ConfigurationManager.AppSettings.Get("DBCredential");
DBCredential = Util.DecryptToString(DBCredential);
string PoolOn = ConfigurationManager.AppSettings.Get("PoolOn");
DBConnection.DBPoolConString = DBServer + DBCredential + PoolOn;
}
return DBConnection.DBPoolConString;
}
private string getnonPoolConString()
{
if (DBConnection.DBNonPoolConString == null)
{
string DBServer = ConfigurationManager.AppSettings.Get("DBServer");
string DBCredential = ConfigurationManager.AppSettings.Get("DBCredential");
DBCredential = Util.DecryptToString(DBCredential);
string PoolOff = ConfigurationManager.AppSettings.Get("PoolOff");
DBConnection.DBNonPoolConString = DBServer + DBCredential + PoolOff;
}
return DBConnection.DBNonPoolConString;
}
private void OpenDB()
{
if (sqlConn == null)
{
try
{
sqlConn = new SqlConnection(getPoolConSting());
sqlConn.Open();
}
catch (System.Data.SqlClient.SqlException)
{
if (sqlConn.State != ConnectionState.Closed)
{
sqlConn.Close();
sqlConn = new SqlConnection(getnonPoolConString());
sqlConn.Open();
}
}
}
}
public void Dispose()
{
if (!(System.Convert.IsDBNull(sqlConn)))
{
sqlConn.Dispose();
sqlConn = null;
}
}
public void Close()
{
if (!(System.Convert.IsDBNull(sqlConn)))
{
sqlConn.Close();
}
}
Thursday, February 19, 2009
Get Query String In JavaScript With Split
< script type= "text/javascript" >
function querySt(qsFind)
{
qs = window.location.search.substring(1);
str = qs.split("&"); //Split Query String
for (i=0 ; i < str.length ; i++)
{
cs = str[i].split("="); /Split Individual Query String with =
if (cs[0] == qsFind) //Check for particular query string and if found return value
{
return cs[1];
}
}
}
< / script >
var Ledger_Id = querySt("Ledger_Id");
function querySt(qsFind)
{
qs = window.location.search.substring(1);
str = qs.split("&"); //Split Query String
for (i=0 ; i < str.length ; i++)
{
cs = str[i].split("="); /Split Individual Query String with =
if (cs[0] == qsFind) //Check for particular query string and if found return value
{
return cs[1];
}
}
}
< / script >
var Ledger_Id = querySt("Ledger_Id");
Wednesday, January 28, 2009
Subscribe to:
Posts (Atom)