Monday, 19 October 2015

Decrypt Text

   private string Decrypt(string cipherText)  //For Decrypt
    {
        string EncryptionKey = "MAKV2SPBNI99212";
        byte[] cipherBytes = Convert.FromBase64String(cipherText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(cipherBytes, 0, cipherBytes.Length);
                    cs.Close();
                }
                cipherText = Encoding.Unicode.GetString(ms.ToArray());
            }
        }
        return cipherText;
    }


    private void passcheck()
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from ustable where uid='" + Encrypt(TextBox1.Text) + "'", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable(); da.Fill(dt);
        con.Close();
        if (TextBox1.Text == Decrypt(dt.Rows[0]["uid"].ToString()))
        {
            Response.Write("password checked");
        }
        else
        {
            Response.Write("Not Valid");
        }
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        passcheck();
    }

EncryptText

Encrypt Text


  private string Encrypt(string clearText)         // Functon for plane text to encrypt text
    {
        string EncryptionKey = "MAKV2SPBNI99212";
        byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                }
                clearText = Convert.ToBase64String(ms.ToArray());
            }
        }
        return clearText;
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string uid=Encrypt(TextBox1.Text);
        string pwd=Encrypt(TextBox2.Text);
        con.Open();
        SqlCommand cmd = new SqlCommand("insert into ustable (uid,pass) values ('" + uid + "','" + pwd + "')",con);
       
        int i = cmd.ExecuteNonQuery();
        con.Close();
        if (i > 0)
        {
            Response.Write("Saved");
        }
        else
        {
            Response.Write("Eroor....");
        }
    }

Wednesday, 7 October 2015

sp_executesql in procedure with separate query,parameter

sp_executesql in procedure with separate query,parameter

CREATE PROCEDURE Myproc-- 'pabitra','@parm1OUT',''
    @parm varchar(10),
    @parm1OUT varchar(30) OUTPUT,
    @parm2OUT varchar(30) OUTPUT
    AS
      SELECT @parm1OUT='parm 1' + @parm
     SELECT @parm2OUT='parm 2' + @parm
GO
DECLARE @SQLString NVARCHAR(500)
DECLARE @ParmDefinition NVARCHAR(500)
DECLARE @parmIN VARCHAR(10)
DECLARE @parmRET1 VARCHAR(30)
DECLARE @parmRET2 VARCHAR(30)
SET @parmIN=' returned'
SET @SQLString=N'EXEC Myproc @parm,
                             @parm1OUT OUTPUT, @parm2OUT OUTPUT'
SET @ParmDefinition=N'@parm varchar(10),
                      @parm1OUT varchar(30) OUTPUT,
                      @parm2OUT varchar(30) OUTPUT'

EXECUTE sp_executesql
    @SQLString,
    @ParmDefinition,
    @parm=@parmIN,
    @parm1OUT=@parmRET1 OUTPUT,@parm2OUT=@parmRET2 OUTPUT

SELECT @parmRET1 AS "parameter 1", @parmRET2 AS "parameter 2"
go
drop procedure Myproc

Data Annotations in entity framework

SQL Setting Default value of Date and time in Table

SQL Setting Default value of Date and time in Table

create table Mst_Category
(
Cat_Auto bigint not null primary key identity(1,1),
Cat_Id varchar(20) not null,
Cat_Name varchar(100),
userId varchar(20),
dflag int,
Sys_Date datetime default getdate(),
sys_Time  time default CONVERT(time, GETDATE())
)


create table Mst_Category
(
Cat_Auto bigint not null primary key identity(1,1),
Cat_Id varchar(20) not null,
Cat_Name varchar(100),
userId varchar(20),
dflag int,
Sys_Date datetime default getdate(),
sys_Time  varchar(20) default RIGHT(CONVERT(CHAR(20), GETDATE(), 22), 11)--For AM and PM
)

Sql Trigger Insert,Update,Delete

Sql Trigger Insert,Update,Delete

create table tblMain
  (
   Id int not null Primary Key identity(1,1) ,
   Name varchar(100),
   dflag int,
   userId varchar(20)
    )


create table tblMain_Image
  (
  AutoId bigint not null Primary key identity(1,1),
    Id int  not null,
    Name varchar(100),
    userId varchar(20),
    dflag int,
Sys_Date datetime default getdate(),
sys_Time  varchar(20) default RIGHT(CONVERT(CHAR(20), GETDATE(), 22), 11)--For AM and PM
    )
----------------------------------INSERT----------------------------  
create trigger [dbo].[Triger_Insert_tblMain] ON  [dbo].[tblMain] FOR INSERT
AS
BEGIN
     set nocount on
    insert into [dbo].[tblMain_Image]
           (Id,Name,userId,dflag)
    SELECT Id,Name,userId,0
    FROM inserted;
 
END
----------------------------------INSERT-----------------------------------


----------------------------------UPDATE---------------------------------
create trigger [dbo].[Triger_Update_tblMain] ON  [dbo].[tblMain] FOR UPDATE
AS
BEGIN
    set nocount on
    insert into [dbo].[tblMain_Image]
           (Id,Name,userId,dflag)
    SELECT Id,Name,userId,1
    FROM inserted;
 
END
---------------------------------UPDATE---------------------------------


---------------------------DELETE------------------------------------
create  trigger Triger_Delete_tblMain on  [dbo].[tblMain]
FOR DELETE
AS
begin
 set nocount on
     insert into [dbo].[tblMain_Image]
           (Id,Name,userId,dflag)
    SELECT Id,Name,userId,2
    FROM deleted;
end
---------------------------DELETE------------------------------------

c# Page.ClientScript.RegisterStartupScript

c# Page.ClientScript.RegisterStartupScript

 Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('Hello Mr Pabitra Now your eligible for join in microsoft');window.location.href=('Thanku.aspx');</script>");

custom message in asp.nt

custom message in asp.nt

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="btnClick" runat="server" Text="Click Me" OnClick="btnClick_Click" />
    </div>
    </form>
</body>
</html>
---------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnClick_Click(object sender, EventArgs e)
    {
        CustomPopup.Show(this.Page, "Hello Pabitra Microsoft");
    }
 
 
}
public static class CustomPopup
{
    public static void Show(this Page Page, String Message)
    {
        Page.ClientScript.RegisterStartupScript(Page.GetType(),"MessageBox","<script language='javascript'>alert('" + Message + "');</script>");
    }
}

C#- different type of alert message in code behind

C#- different type of alert message in code behind

 string Message = "Pabitra you as Microsoft Employee !";
         ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Pabitra you as Microsoft Employee !');", true);
         ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + Message + "');", true);

         ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Pabitra you as Microsoft Employee !');", true);
         ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + Message + "');", true);

         Response.Write(@"<script language='javascript'>alert('Pabitra you as Microsoft Employee ! ')</script>");
         Response.Write(@"<script language='javascript'>alert('"+Message+"')</script>");

         Page.ClientScript.RegisterStartupScript(Page.GetType(), "MessageBox", "<script language='javascript'>alert('Pabitra you as Microsoft Employee !');</script>");
         Page.ClientScript.RegisterStartupScript(Page.GetType(),"MessageBox","<script language='javascript'>alert('" + Message + "');</script>");

         ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "ClientScript", "alert('Pabitra you as Microsoft Employee !')", true);
         ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "ClientScript", "alert('" + Message + "')", true);
        ////////////////
         ClientScript.RegisterClientScriptBlock(GetType(), "Email", "GetEmail();", true);
        //In Html Page
        <head>
        <script type="text/javascript" language="javascript">
         function GetEmail() {
             alert('hi');
         }
        </script>
    </head>
    ///////////////////////////

c# google plus integration in website

c# google plus integration in website

Follw the sample
https://developers.google.com/+/web/samples/csharp

Or Follow

http://www.c-sharpcorner.com/UploadFile/vdtrip/google-plus-authentication-in-Asp-Net-and-C-Sharp/

get ip address in c#

 //using System.Net;
        string hostName = Dns.GetHostName(); // Retrive the Name of HOST  
        string myIP = Dns.GetHostByName(hostName).AddressList[0].ToString();
        Response.Write("My IP Address is :" + myIP); 

Switch Case In ASp.net With Examples By Pabitra

Switch Case In ASp.net With Examples By Pabitra

 Switch Case In ASp.net For Clear Method
 ------------------------------------------------------------------
 private void DesableEnableClear(string Status)
    {
  TextBox[] arr = { txtHeltID, txtHelthType };
   switch (Status)
   {
    case "D":
           foreach (TextBox txt in arr)
           {
            txt.Enabled = false;
           }
           txtHeltID.Text = "";
           break;        
    case "E":
            foreach (TextBox txt in arr)
            {
                txt.Enabled = true;
            }
            txtHeltID.Text = LoadMaxID();
            break;
    case "C":
           foreach (TextBox txt in arr)
            { txt.Text = ""; }
            btnSave.Enabled = true;
            txtHeltID.Text = LoadMaxID();
            break;
    case "GL":
            btnSave.Enabled = true;          
            btnDelete.Enabled = false;
            btnUpdate.Enabled = false;
            panelg.Visible = true;
            break;
    case "GR":
            btnSave.Enabled = false;
            btnDelete.Enabled = true;
            btnUpdate.Enabled = true;
            panelg.Visible = false;
            break;
       case "U":
           btnSave.Enabled = true;         
            btnDelete.Enabled = false;
            btnUpdate.Enabled = false;
            panelg.Visible = false;
            break;
      case "SD":
            lblSearch.Visible = false;
            txtSearch.Visible = false;
            break;
      case "SE":
            lblSearch.Visible = true;
             txtSearch.Visible = true;
            break;
      default :
           // Response.Write("Hello");
            break;
        } ////

how to change server side div background images

how to change server side div background images

how to change server side div background images
any one can help me....
my code is ..
 <div id="divID" runat="server" > </div>

 divID.Style["background-image"] = Page.ResolveUrl("~/body/backShadow.png");

Create a Full Database Backup In SQL Server

Create a Full Database Backup In SQL Server



BACKUP DATABASE DataBaseName TO DISK = 'D:\BackupName.bak'
Example
DataBase name:DbPabitra
BACKUP DATABASE DbPabitra TO DISK = 'D:\DataBaseBacup.bak'
For More Informatation
http://pabitramicrosoftresearch.blogspot.in/

DDL TRIGGER FOR ALL DATABASE CREATE,ALTER,DELETE TABLE IN SQLSERVER

---For All Server(DataBase)
ALTER trigger NoTable
on all server
for CREATE_TABLE,ALTER_TABLE,DROP_TABLE
AS BEGIN
PRINT 'NO NEW TABLE PLEASE'
ROLLBACK
END

inserted trigger in sql server

inserted trigger in sql server


CREATE TABLE [dbo].[tblTRIGGERMAST1](
[ID] [varchar](10) NOT NULL PRIMARY KEY,
[NAME] [varchar](20) NULL,
[PHONE] [int] NULL
)

CREATE TABLE [dbo].[tblTRIGGER2](
[ID] [int] IDENTITY(1001,1) PRIMARY KEY NOT NULL,
[IDMAST] [varchar](10) NULL,
[PHONE] [int] NULL,
[DATE] [datetime] NULL
)
CREATE  TRIGGER Triger_On_tblTRIGGERMAST1
ON  tblTRIGGERMAST1
AFTER INSERT
AS
BEGIN

SET NOCOUNT ON;
declare @ID int
declare @Phone int
declare @Result varchar(100)
select @ID=ID from inserted
select @Phone =PHONE from inserted
INSERT INTO tblTRIGGER2(IDMAST,PHONE)VALUES(@ID,@Phone)
set @Result=convert(varchar,'The Inserted Values Are Inserted in Table tblTRIGGER2:ID IS:  ')
+convert(varchar,@ID)+convert(varchar,' pHONE nO  Is: ')+convert(varchar,@Phone)
Print @Result

END
insert into tblTRIGGERMAST1(ID,NAME,PHONE)values(1004,'PABITRA BEHERA',828989)

-------------
---THE RESULT WILL BE
The Inserted Values Are Insert1004 pHONE nO  Is: 828989

(1 row(s) affected)

sql server restore database query

sql server restore database query

RESTORE DATABASE PabitraDemoDb

FROM DISK='d:\PabitraDemoDb.bak'

Disable Right Click of Page in c#

Disable Right Click of Page in c#

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Sample to Disable Right Click of Page</title>
<script language="JavaScript" type="text/javascript">
    //Message to display whenever right click on website
    var message = "Sorry, Right Click have been disabled.";
    function click(e) {
        if (document.all) {
            if (event.button == 2 || event.button == 3) {
                alert(message);
                return false;
            }
        }
        else {
            if (e.button == 2 || e.button == 3) {
                e.preventDefault();
                e.stopPropagation();
                alert(message);
                return false;
            }
        }
    }
    if (document.all) {
        document.onmousedown = click;
    }
    else {
        document.onclick = click;
    }
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
from Suresh
-----

sql alter drop rename column in the table

sql alter drop rename column in the table

To add a column in a table, use the following syntax:
------------------------------
ALTER TABLE table_name
ADD column_name datatype

-----------------------------
To delete a column in a table, use the following syntax (notice that some database systems don't
allow deleting a column):
--------------------------------------
ALTER TABLE table_name
DROP COLUMN column_name
-----------------------------


To change the data type of a column in a table, use the following syntax:
--------------------------------------------
ALTER TABLE table_name
ALTER COLUMN column_name datatype


----------------------------------
To rename Column Name
-------------------------
EXEC sp_RENAME 'table_name.old_name', 'new_name', 'COLUMN'

Key Down Events and Key press Events

Key Down Events and Key press Events

Key Down Events
-----------------


<script type="text/javascript">
        $(document).ready(function () {
            $("#<%= txtcontactno.ClientID%>").keydown(function (e) {
                if (e.shiftKey)
                    e.preventDefault();
                else {
                    var nKeyCode = e.keyCode;
                    //Ignore Backspace and Tab keys      
                    if (nKeyCode == 8 || nKeyCode == 9)
                        return;
                    if (nKeyCode < 95) {
                        if (nKeyCode < 48 || nKeyCode > 57)
                            e.preventDefault();
                    }
                    else {
                        if (nKeyCode < 96 || nKeyCode > 105)
                            e.preventDefault();
                    }
                }
            });
        });
    </script>
Key press Events
-----------------
 <script type="text/javascript">

        $(document).ready(function () {
            //called when key is pressed in textbox
            $('#<%=txtcontactno.ClientID%>').keypress(function (e) {
                alert('hello');
                //if the letter is not digit then display error and don't type anything
                if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                    //display error message
                    //  alert('Please Enter ');
                    //  $("#errmsg").html("Digits Only").show().fadeOut("slow");
                    return false;
                }
            });
        });

    </script>

For Clear Session

For Clear Session

 Session.Abandon();
        Session.RemoveAll(); Session.Clear();

Concate Sql Query in c#

Concate Sql Query in c#

  The  Below query is concate in c#
When a long query we write we impliments this
Solution
-----------
 protected void Button1_Click(object sender, EventArgs e)
    {

        string Name = "Pabitra";
        // string Query = "insert into tblEmployee ( id, name ) values( " + 4 + ",'" + Name + "' )";
        string Query = "insert into tblEmployee " +
            " (        " +
            " id,      " +
            " name     " +
            " )        " +

            " values(  " +
            "" + 4 + "," +
            "'" + Name + "' " +
            " )";
        Response.Write(Query);
    }

Date Time Picker in Jquery

Date Time Picker in Jquery

  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#<%=txtFromdate.ClientID%>').datepicker({ dateFormat: "dd/mm/yy" }).val()
            $('#<%=txtTodate.ClientID%>').datepicker({ dateFormat: "dd/mm/yy" }).val()
        });
      
   </script>


<div>

<asp:TextBox ID="txtFromdate" Width="35%" runat="server" placeholder="Select Date" ToolTip="From Date" AutoCompleteType="Disabled" TabIndex="1"></asp:TextBox>

<br/>
<asp:TextBox ID="txtTodate" Width="35%" runat="server" placeholder="Select Date" ToolTip="From Date" AutoCompleteType="Disabled" TabIndex="1"></asp:TextBox>



</div>

Get USD to INR exchange rate dynamically in C#

Get USD to INR exchange rate dynamically in C# 

using System.IO;
using System.Net;
using System.Xml;
----------------------

 private void button2_Click(object sender, EventArgs e)
        {
            WebRequest webrequest = WebRequest.Create("http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate?FromCurrency=USD&ToCurrency=INR");
            HttpWebResponse response = (HttpWebResponse)webrequest.GetResponse();
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(responseFromServer);
            string value = doc.InnerText;

            MessageBox.Show(value);
            reader.Close();
            dataStream.Close();
            response.Close();


        }

Repeater Control In Asp.net

Repeater Control In Asp.net

USE [DBPABITRA]
GO

/****** Object:  Table [dbo].[tbexecutive]    Script Date: 01/06/2015 17:47:58 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[tbexecutive](
[id] [varchar](10) NULL,
[workername] [varchar](50) NULL,
[currentadd] [varchar](50) NULL
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO


-------------------------using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
public partial class RepeatearControl : System.Web.UI.Page
{  
    SqlConnection con = new SqlConnection("server=.;uid=sa;pwd=mypass;database=MyDB");
    protected void Page_Load(object sender, EventArgs e)
    {

        if (con.State == ConnectionState.Closed)
        {

            con.Open();

        }

        if (Page.IsPostBack == false)
        {

            Show_Data();

        }

    }

    protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
    {

        if (e.CommandName == "edit")
        {

            ((Label)e.Item.FindControl("Label1")).Visible = false;

            ((Label)e.Item.FindControl("Label2")).Visible = false;

            ((TextBox)e.Item.FindControl("Textbox1")).Visible = true;

            ((TextBox)e.Item.FindControl("Textbox2")).Visible = true;

            ((LinkButton)e.Item.FindControl("LinkEdit")).Visible = false;

            ((LinkButton)e.Item.FindControl("LinkDelete")).Visible = false;

            ((LinkButton)e.Item.FindControl("LinkUpdate")).Visible = true;

            ((LinkButton)e.Item.FindControl("Linkcancel")).Visible = true;

        } if (e.CommandName == "delete")
        {

            SqlCommand cmd = new SqlCommand("delete from tbexecutive where id=@id", con);

            cmd.Parameters.AddWithValue("@id", e.CommandArgument);

            cmd.ExecuteNonQuery();

            cmd.Dispose();

            Page.ClientScript.RegisterStartupScript(this.GetType(), "ch", "");

            Show_Data();

        }

        if (e.CommandName == "update")
        {

            string str1 = ((TextBox)e.Item.FindControl("TextBox1")).Text;

            string str2 = ((TextBox)e.Item.FindControl("TextBox2")).Text;

            SqlDataAdapter adp = new SqlDataAdapter("update tbexecutive set workername=@workername, currentadd=@add where id=@id", con);

            adp.SelectCommand.Parameters.AddWithValue("@workername", str1);

            adp.SelectCommand.Parameters.AddWithValue("@add", str2);

            adp.SelectCommand.Parameters.AddWithValue("@id", e.CommandArgument);

            DataSet ds = new DataSet();

            adp.Fill(ds);

            Show_Data();

            Page.ClientScript.RegisterStartupScript(this.GetType(), "ch", "");

        } if (e.CommandName == "cancel")
        {

            ((Label)e.Item.FindControl("Label1")).Visible = true;

            ((Label)e.Item.FindControl("Label2")).Visible = true;

            ((TextBox)e.Item.FindControl("TextBox1")).Visible = false;

            ((TextBox)e.Item.FindControl("TextBox2")).Visible = false;

            ((LinkButton)e.Item.FindControl("LinkEdit")).Visible = true;

            ((LinkButton)e.Item.FindControl("LinkDelete")).Visible = true;

            ((LinkButton)e.Item.FindControl("LinkUpdate")).Visible = false;

            ((LinkButton)e.Item.FindControl("Linkcancel")).Visible = false;

        }



    }

    public void Show_Data()
    {

        SqlDataAdapter adp = new SqlDataAdapter("select * from tbexecutive ORDER BY workername ASC", con);

        DataSet ds = new DataSet();

        adp.Fill(ds);

        Repeater1.DataSource = ds;

        Repeater1.DataBind();

    }

}

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RepeatearControl.aspx.cs" Inherits="RepeatearControl" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
<head id = "Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form2" runat="server">
    <div>
 
        <asp:Repeater ID="Repeater1" runat="server"
            onitemcommand="Repeater1_ItemCommand">
            <HeaderTemplate>
         

          <table width="350"><tr
bgcolor="#FF6600"><td>Name</td><td>Address</td><td>Action</td></tr></HeaderTemplate>

           <ItemTemplate><tr><td> <asp:Label
ID="Label1" runat="server" Text='<%#Eval("workername")
%>'></asp:Label>

      <asp:TextBox ID="TextBox1" runat="server"
Text='<%#Eval("workername") %>'
Visible="false"></asp:TextBox>
        </td>
        <td>
        <asp:Label ID="Label2" runat="server" Text='<%#Eval("currentadd") %>'></asp:Label>

      <asp:TextBox ID="TextBox2" runat="server"
Text='<%#Eval("currentadd") %>'
Visible="false"></asp:TextBox>
        </td>
         <td>

      <asp:LinkButton ID="LinkEdit" runat="server"
CommandArgument='<%#Eval("id") %>'
CommandName="edit">Edit</asp:LinkButton>

          <asp:LinkButton ID="LinkDelete" runat="server"
CommandArgument='<%#Eval("id") %>'
CommandName="delete">Delete</asp:LinkButton>

          <asp:LinkButton ID="LinkUpdate" runat="server"
CommandArgument='<%#Eval("id") %>' CommandName="update"
Visible="false">Update</asp:LinkButton>

          <asp:LinkButton ID="Linkcancel" runat="server"
CommandArgument='<%#Eval("id") %>' CommandName="cancel"
Visible="false">Cancel</asp:LinkButton>
            </td>
        </tr>
         
     
     
        </ItemTemplate>
        </asp:Repeater>
 
    </div>
    </form>
</body>
</html>
---------------------------

Send Mail in c# through gmail

using System.Configuration;
using System.Net;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
----------------
 protected void btnSendMail1_Click(object sender, EventArgs e)
      {
          string ToWhomYouMail = "pabitrakiims@gmail.com";//Send to mail
          string Subject = "Test Mail";
          string mailbody = "<html><body><div>Dear Sir ,Good Morning</div></body></html>";
          bool m = send_mail(ToWhomYouMail, Subject, mailbody);
          if (m)
          {
              ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('Mail Send Sucessfully !');", true);
          }
          else
          {
              ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('An Error Occurs !');", true);
          }
      }



 public bool send_mail(string ToMail,string subject,string body)
       {
           bool k = false;
           try
           {
               MailMessage msg = new MailMessage("pabitra.best28@gmail.com", ToMail);
               msg.To.Add(ToMail);
            msg.Subject = subject;
            msg.Body = body;
            msg.IsBodyHtml = true;
            AlternateView view;
            SmtpClient client;
            msg.IsBodyHtml = true;
            client = new SmtpClient();
            client.Host = "smtp.gmail.com";
            client.Port = 587;
            client.Credentials = new System.Net.NetworkCredential("pabitra.best28@gmail.com", "password@123");
            client.EnableSsl = true; //Gmail works on Server Secured Layer
            client.Send(msg);
            k = true;
            //return k;
        }catch(Exception ex)
        {
            k = false;
        }
        return k;
     
    }

Google Map Current Loacatation

Copy the Code And Past in Aspx Page and Run You Find the Current Locatation
------------------------------------------------------------------


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!DOCTYPE html>
<html>
    <head>
        <script src="http://maps.google.com/maps/api/js?sensor=false">
        </script>
        <script>
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(showCurrentLocation);
            }
            else {
                alert("Geolocation API not supported.");
            }

            function showCurrentLocation(position) {
                var latitude = position.coords.latitude;
                var longitude = position.coords.longitude;
                var coords = new google.maps.LatLng(latitude, longitude);

                var mapOptions = {
                    zoom: 15,
                    center: coords,
                    mapTypeControl: true,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };

                //create the map, and place it in the HTML map div
                map = new google.maps.Map(
                document.getElementById("mapPlaceholder"), mapOptions
                );

                //place the initial marker
                var marker = new google.maps.Marker({
                    position: coords,
                    map: map,
                    title: "Current location!"
                });
            }
        </script>
    </head>
    <style>
    #mapPlaceholder {
        height: 400px;
        width: 700px;
    </style>
    <body>
        <div>
        <h2>HTML5 Show Location on GoogleMap Sample</h2>
        <div id="mapPlaceholder"></div>
        </div>
    </body>
</html>

Saturday, 19 September 2015

Java script validation

Java script validation

<script type="text/javascript">

        function validate()
        {
            if (document.getElementById("<%=txtid.ClientID%>").value=="")
            {
                alert("Name Feild can not be blank");
                document.getElementById("<%=txtid.ClientID%>").focus();
                return false;
               
               
            }
            else
            {
              
                    if (confirm("Are you sure you want to Save this user?"))
                        return true;
                    else
                        return false;
               
            }
          
           
        }
    </script>

Tuesday, 8 September 2015

CSS for button

css for button


    <style type="text/css">
        .gbqfba {
    -moz-user-select: none;
    background-color: #f2f2f2;
    background-image: -moz-linear-gradient(center top , #f5f5f5, #f1f1f1);
    border: 1px solid #f2f2f2;
    border-radius: 2px;
    color: #757575;
    cursor: default;
    font-family: arial,sans-serif;
    font-size: 13px;
    font-weight: bold;
    margin: 11px 4px;
    min-width: 54px;
    padding: 0 16px;
    text-align: center;
    height:48px;
}
         .gbqfba:hover {
    background-color: #f8f8f8;
    background-image: -moz-linear-gradient(center top , #f8f8f8, #f1f1f1);
    border: 1px solid #c6c6c6;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
    color: #222;
}
         .mGrid td {
    border: 1px solid #c1c1c1;
    color: #717171;
    font-family: Tahoma,Geneva,sans-serif;
    font-size: 12px;
    padding: 2px;
}
    </style>

Wednesday, 26 August 2015

popup modal

    for close form

<script>
    function CloseAndRefresh()
{
   
    self.close();
}
    </script>

gridview

<asp:GridView ID="grdselct" runat="server" AutoGenerateColumns="False" Height="89px" OnRowCommand="grdselct_RowCommand" Width="338px">
            <Columns>
                <asp:TemplateField HeaderText="ID">
                    <ItemTemplate>
                        <asp:LinkButton ID="LinkButton1" runat="server" Text='<%# Eval("ID") %>' OnClientClick="  CloseAndRefresh();">

                        </asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>

        </asp:GridView>

for open pop up


  <script>
        function popUp(URL) {
            day = new Date();
            id = day.getTime();
            eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=580,height=340,left = 490,top = 184');");
        }
 



</script>

<asp:Button ID="Button2" runat="server" OnClick="Button2_Click"  OnClientClick="return popUp('PurchaseDetails.aspx')" Text="Button" />



Tuesday, 25 August 2015

pop up on link button click

pop up on link button click



<script>
  function popUp(URL) {
            day = new Date();
            id = day.getTime();
            eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=580,height=340,left = 490,top = 184');");
        }
</script>






<asp:TemplateField HeaderText="Item List">
                                    <ItemTemplate>
                                        <a href="javascript:popUp('PurchaseDetails.aspx?PurchaseId=<%#Eval("PurchaseId")%>')">
                                            View Items</a>
                                    </ItemTemplate>
                                    <HeaderStyle HorizontalAlign="Center" Width="80px" />
                                    <ItemStyle HorizontalAlign="Center" />
                                </asp:TemplateField>

On Check Grid view Rows color change

On Check Grid view Rows color change
..................................................................................................
protected void chkStatus_CheckedChanged(object sender, EventArgs e)
{
        private const string colorPresent = "#BDF8B9";

private const string colorAbsent = "#FFB5B2";


        //to enable/disable Isgranted checkbox.
        CheckBox chk = (CheckBox)sender;
        CheckBox chkGr = (CheckBox)((CheckBox)sender).Parent.Parent.FindControl("chkGranted");
        if (chk.Checked)
        {

            chkGr.Checked = false;
            chkGr.Enabled = false;
            chkGr.Text = "---";
        }
        else
        {
            chkGr.Enabled = true;

            chkGr.Text = "IsGranted";
        }

CheckBox checkBox = (CheckBox)sender;
GridViewRow parent = (GridViewRow)checkBox.Parent.Parent;
TextBox empty = (TextBox)parent.FindControl("txtRemarks");
empty.Text = string.Empty;
if (checkBox.Checked)
{
empty.Enabled = false;
parent.BackColor = ColorTranslator.FromHtml("#BDF8B9");
return;
}
empty.Enabled = true;
parent.BackColor = ColorTranslator.FromHtml("#FFB5B2");
     
}

Monday, 24 August 2015

Triggers for Update Panel

Triggers for Update Panel
 
</ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="btnSaveAddNew" EventName="Click" />
            <asp:AsyncPostBackTrigger ControlID="btnShow" EventName="Click" />
        </Triggers>
    </asp:UpdatePanel>

Export Data into Excel


Export Data into Excel


 public static string ExportToExcelFromDataTable(DataTable dtOrig, int[] delColIndx, string[] colNames, string filename)
    {
        try
        {
            if (!validateDelColIndx(dtOrig, delColIndx))
            {
                return "Verify the list of indices to be deleted !";
            }
            if (colNames.Length > (dtOrig.Columns.Count - delColIndx.Length))
            {
                return "No of column names didn't match the no of columns that will be available in the final result !";
            }
            DataTable dtExcel = dtOrig.Copy();
            //remove the unwanted columns
            int decr = 0;
            foreach (int looInt in delColIndx)
            {
                dtExcel.Columns.RemoveAt(looInt - decr);
                decr++;
            }

            dtExcel.AcceptChanges();
            //change column header names as per requirement
            int incre = 0;
            foreach (string loopStr in colNames)
            {
                dtExcel.Columns[incre].ColumnName = loopStr;
                incre++;
            }
            dtExcel.AcceptChanges();
            string downloadFile = "attachment; filename=" + filename + ".xls";
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.AddHeader("content-disposition", downloadFile);
            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            string nextColumn = "";
            foreach (DataColumn col in dtExcel.Columns)
            {
                HttpContext.Current.Response.Write(nextColumn + col.ColumnName);
                nextColumn = "\t";
            }
            HttpContext.Current.Response.Write("\n");
            int i;
            foreach (DataRow dr in dtExcel.Rows)
            {
                nextColumn = "";
                for (i = 0; i < dtExcel.Columns.Count; i++)
                {
                    HttpContext.Current.Response.Write(nextColumn + dr[i].ToString());
                    nextColumn = "\t";
                }
                HttpContext.Current.Response.Write("\n");
            }
            HttpContext.Current.Response.End();
            return string.Empty;
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }
------------------------------------------------------------------------------------------------------------
    protected void btnExport_Click(object sender, EventArgs e)
    {
        clsDAL obj = new clsDAL();
        DataTable dt = new DataTable();
        dt = obj.GetDataTable("Ps_Sp_GetStudDataForExport");
        if (dt.Rows.Count > 0)
        {
            foreach (DataRow dr in dt.Rows)
            {
                clsDAL Stud = new clsDAL();
                Hashtable htStud = new Hashtable();
                htStud.Add("@StudId", dr["StudId"]);
                Stud.ExecuteScalar("ps_sp_InsertExpExlData", htStud);
            }
         

            ExportToExcelFromDataTable(dt, new int[] { 0 }, new string[] { "AdmnNo", "AdmnDate", "SessionYear", "ReadingClass", "Section", "RollNo", "FullName", "NickName", "DOB", "FatherName", "FatherOccupation", "MotherName", "MotherOccupation", "Gender", "Religion", "Category", "Nationality", "MotherTongue", "PresAddress", "PresAddrDist", "PresAddrPin", "PresAddrPS", "PermAddress", "PermAddrDist", "PermAddrPin", "PermAddrPS", "Phone", "Mobile", "UrbanRuralTribe", "SSVMID" }, "../Reports/Exported_Files/SSVM_StudentDetails" + DateTime.Now.ToString("dd-MM-yyyy hh-mm-ss") + ".xls");
        }
        else
        {
            lblMsg.Text = "No data exist to export !";
        }
    }

Sunday, 23 August 2015

Auto gen ID in Sql

 Auto Gen ID  in Sql
SELECT @AdmnNo=CAST(LEFT(@AdmnSessYr,4)+RIGHT(@AdmnSessYr,2)+'0001' AS BIGINT)

Saturday, 22 August 2015

Sql Helper Class

Sql Helper Class


using System;
using System.Data;
using System.Xml;
using System.Data.SqlClient;
using System.Collections;

namespace PROJECT.DAL
{
/// <summary>
/// The SqlHelper class is intended to encapsulate high performance, scalable best practices for
/// common uses of SqlClient.
/// </summary>
public sealed class SqlHelper
{
#region private utility methods & constructors

//Since this class provides only static methods, make the default constructor private to prevent
//instances from being created with "new SqlHelper()".
private SqlHelper() {}



/// <summary>
/// This method is used to attach array of SqlParameters to a SqlCommand.
///
/// This method will assign a value of DbNull to any parameter with a direction of
/// InputOutput and a value of null.
///
/// This behavior will prevent default values from being used, but
/// this will be the less common case than an intended pure output parameter (derived as InputOutput)
/// where the user provided no input value.
/// </summary>
/// <param name="command">The command to which the parameters will be added</param>
/// <param name="commandParameters">an array of SqlParameters tho be added to command</param>
private static void AttachParameters(SqlCommand command, SqlParameter[] commandParameters)
{
foreach (SqlParameter p in commandParameters)
{
//check for derived output value with no value assigned
if ((p.Direction == ParameterDirection.InputOutput) && (p.Value == null))
{
p.Value = DBNull.Value;
}

command.Parameters.Add(p);
}
}

/// <summary>
/// This method assigns an array of values to an array of SqlParameters.
/// </summary>
/// <param name="commandParameters">array of SqlParameters to be assigned values</param>
/// <param name="parameterValues">array of objects holding the values to be assigned</param>
private static void AssignParameterValues(SqlParameter[] commandParameters, object[] parameterValues)
{
if ((commandParameters == null) || (parameterValues == null))
{
//do nothing if we get no data
return;
}

// we must have the same number of values as we pave parameters to put them in
if (commandParameters.Length != parameterValues.Length)
{
throw new ArgumentException("Parameter count does not match Parameter Value count.");
}

//iterate through the SqlParameters, assigning the values from the corresponding position in the
//value array
for (int i = 0, j = commandParameters.Length; i < j; i++)
{
commandParameters[i].Value = parameterValues[i];
}
}

/// <summary>
/// This method opens (if necessary) and assigns a connection, transaction, command type and parameters
/// to the provided command.
/// </summary>
/// <param name="command">the SqlCommand to be prepared</param>
/// <param name="connection">a valid SqlConnection, on which to execute this command</param>
/// <param name="transaction">a valid SqlTransaction, or 'null'</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParameters to be associated with the command or 'null' if no parameters are required</param>
private static void PrepareCommand(SqlCommand command, SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters)
{
//if the provided connection is not open, we will open it
if (connection.State != ConnectionState.Open)
{
connection.Open();
}

//associate the connection with the command
command.Connection = connection;

//set the command text (stored procedure name or SQL statement)
command.CommandText = commandText;

//if we were provided a transaction, assign it.
if (transaction != null)
{
command.Transaction = transaction;
}

//set the command type
command.CommandType = commandType;

//attach the command parameters if they are provided
if (commandParameters != null)
{
AttachParameters(command, commandParameters);
}

return;
}


#endregion private utility methods & constructors

#region ExecuteNonQuery

/// <summary>
/// Execute a SqlCommand (that returns no resultset and takes no parameters) against the database specified in
/// the connection string.
/// </summary>
/// <remarks>
/// e.g.:
///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders");
/// </remarks>
/// <param name="connectionString">a valid connection string for a SqlConnection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <returns>an int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText)
{
//pass through the call providing null for the set of SqlParameters
return ExecuteNonQuery(connectionString, commandType, commandText, (SqlParameter[])null);
}

/// <summary>
/// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">a valid connection string for a SqlConnection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>an int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
//create & open a SqlConnection, and dispose of it after we are done.
using (SqlConnection cn = new SqlConnection(connectionString))
{
cn.Open();

//call the overload that takes a connection in place of the connection string
return ExecuteNonQuery(cn, commandType, commandText, commandParameters);
}
}

/// <summary>
/// Execute a stored procedure via a SqlCommand (that returns no resultset) against the database specified in
/// the connection string using the provided parameter values.  This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
///  int result = ExecuteNonQuery(connString, "PublishOrders", 24, 36);
/// </remarks>
/// <param name="connectionString">a valid connection string for a SqlConnection</param>
/// <param name="spName">the name of the stored prcedure</param>
/// <param name="parameterValues">an array of objects to be assigned as the input values of the stored procedure</param>
/// <returns>an int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(string connectionString, string spName, params object[] parameterValues)
{
//if we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > 0))
{
//pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);

//assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues);

//call the overload that takes an array of SqlParameters
return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
//otherwise we can just call the SP without params
else
{
return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName);
}
}

/// <summary>
/// Execute a SqlCommand (that returns no resultset and takes no parameters) against the provided SqlConnection.
/// </summary>
/// <remarks>
/// e.g.:
///  int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders");
/// </remarks>
/// <param name="connection">a valid SqlConnection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <returns>an int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText)
{
//pass through the call providing null for the set of SqlParameters
return ExecuteNonQuery(connection, commandType, commandText, (SqlParameter[])null);
}

/// <summary>
/// Execute a SqlCommand (that returns no resultset) against the specified SqlConnection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
///  int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connection">a valid SqlConnection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>an int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
//create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters);

//finally, execute the command.
int retval = cmd.ExecuteNonQuery();

// detach the SqlParameters from the command object, so they can be used again.
cmd.Parameters.Clear();
return retval;
}

/// <summary>
/// Execute a stored procedure via a SqlCommand (that returns no resultset) against the specified SqlConnection
/// using the provided parameter values.  This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
///  int result = ExecuteNonQuery(conn, "PublishOrders", 24, 36);
/// </remarks>
/// <param name="connection">a valid SqlConnection</param>
/// <param name="spName">the name of the stored procedure</param>
/// <param name="parameterValues">an array of objects to be assigned as the input values of the stored procedure</param>
/// <returns>an int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(SqlConnection connection, string spName, params object[] parameterValues)
{
//if we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > 0))
{
//pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection.ConnectionString, spName);

//assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues);

//call the overload that takes an array of SqlParameters
return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName, commandParameters);
}
//otherwise we can just call the SP without params
else
{
return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName);
}
}

/// <summary>
/// Execute a SqlCommand (that returns no resultset and takes no parameters) against the provided SqlTransaction.
/// </summary>
/// <remarks>
/// e.g.:
///  int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders");
/// </remarks>
/// <param name="transaction">a valid SqlTransaction</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <returns>an int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText)
{
//pass through the call providing null for the set of SqlParameters
return ExecuteNonQuery(transaction, commandType, commandText, (SqlParameter[])null);
}

/// <summary>
/// Execute a SqlCommand (that returns no resultset) against the specified SqlTransaction
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
///  int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="transaction">a valid SqlTransaction</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>an int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
//create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters);

//finally, execute the command.
int retval = cmd.ExecuteNonQuery();

// detach the SqlParameters from the command object, so they can be used again.
cmd.Parameters.Clear();
return retval;
}

/// <summary>
/// Execute a stored procedure via a SqlCommand (that returns no resultset) against the specified
/// SqlTransaction using the provided parameter values.  This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
///  int result = ExecuteNonQuery(conn, trans, "PublishOrders", 24, 36);
/// </remarks>
/// <param name="transaction">a valid SqlTransaction</param>
/// <param name="spName">the name of the stored procedure</param>
/// <param name="parameterValues">an array of objects to be assigned as the input values of the stored procedure</param>
/// <returns>an int representing the number of rows affected by the command</returns>
public static int ExecuteNonQuery(SqlTransaction transaction, string spName, params object[] parameterValues)
{
//if we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > 0))
{
//pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection.ConnectionString, spName);

//assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues);

//call the overload that takes an array of SqlParameters
return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
//otherwise we can just call the SP without params
else
{
return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName);
}
}


#endregion ExecuteNonQuery

#region ExecuteDataSet

/// <summary>
/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in
/// the connection string.
/// </summary>
/// <remarks>
/// e.g.:
///  DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="connectionString">a valid connection string for a SqlConnection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <returns>a dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText)
{
//pass through the call providing null for the set of SqlParameters
return ExecuteDataset(connectionString, commandType, commandText, (SqlParameter[])null);
}






        //ghanshyam for DataTable
        public static DataTable ExecuteDataTable(string connectionString, CommandType commandType, string commandText)
        {
            //pass through the call providing null for the set of SqlParameters
            return ExecuteDataTable(connectionString, commandType, commandText, (SqlParameter[])null);
        }

        //ghanshyam for DataTable
        public static DataTable ExecuteDataTable(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        {
            //create & open a SqlConnection, and dispose of it after we are done.
            using (SqlConnection cn = new SqlConnection(connectionString))
            {
                cn.Open();

                //call the overload that takes a connection in place of the connection string
                return ExecuteDataTable(cn, commandType, commandText, commandParameters);
            }
        }
        //Ghanshyam for DataTable

        public static DataTable ExecuteDataTable(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        {
            //create a command and prepare it for execution
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters);

            //create the DataAdapter & DataSet
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();

            //fill the DataSet using default values for DataTable names, etc.
            da.Fill(dt);

            // detach the SqlParameters from the command object, so they can be used again.
            cmd.Parameters.Clear();

            //return the dataset
            return dt;
        }



/// <summary>
/// Execute a SqlCommand (that returns a resultset) against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
///  DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">a valid connection string for a SqlConnection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>a dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
//create & open a SqlConnection, and dispose of it after we are done.
using (SqlConnection cn = new SqlConnection(connectionString))
{
cn.Open();

//call the overload that takes a connection in place of the connection string
return ExecuteDataset(cn, commandType, commandText, commandParameters);
}
}

/// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a resultset) against the database specified in
/// the connection string using the provided parameter values.  This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
///  DataSet ds = ExecuteDataset(connString, "GetOrders", 24, 36);
/// </remarks>
/// <param name="connectionString">a valid connection string for a SqlConnection</param>
/// <param name="spName">the name of the stored procedure</param>
/// <param name="parameterValues">an array of objects to be assigned as the input values of the stored procedure</param>
/// <returns>a dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(string connectionString, string spName, params object[] parameterValues)
{
//if we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > 0))
{
//pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);

//assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues);

//call the overload that takes an array of SqlParameters
return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
//otherwise we can just call the SP without params
else
{
return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName);
}
}

/// <summary>
/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlConnection.
/// </summary>
/// <remarks>
/// e.g.:
///  DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="connection">a valid SqlConnection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <returns>a dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText)
{
//pass through the call providing null for the set of SqlParameters
return ExecuteDataset(connection, commandType, commandText, (SqlParameter[])null);
}

/// <summary>
/// Execute a SqlCommand (that returns a resultset) against the specified SqlConnection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
///  DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connection">a valid SqlConnection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>a dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
//create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters);

//create the DataAdapter & DataSet
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();

//fill the DataSet using default values for DataTable names, etc.
da.Fill(ds);

// detach the SqlParameters from the command object, so they can be used again.
cmd.Parameters.Clear();

//return the dataset
return ds;
}

/// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection
/// using the provided parameter values.  This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
///  DataSet ds = ExecuteDataset(conn, "GetOrders", 24, 36);
/// </remarks>
/// <param name="connection">a valid SqlConnection</param>
/// <param name="spName">the name of the stored procedure</param>
/// <param name="parameterValues">an array of objects to be assigned as the input values of the stored procedure</param>
/// <returns>a dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(SqlConnection connection, string spName, params object[] parameterValues)
{
//if we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > 0))
{
//pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection.ConnectionString, spName);

//assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues);

//call the overload that takes an array of SqlParameters
return ExecuteDataset(connection, CommandType.StoredProcedure, spName, commandParameters);
}
//otherwise we can just call the SP without params
else
{
return ExecuteDataset(connection, CommandType.StoredProcedure, spName);
}
}

/// <summary>
/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction.
/// </summary>
/// <remarks>
/// e.g.:
///  DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="transaction">a valid SqlTransaction</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <returns>a dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(SqlTransaction transaction, CommandType commandType, string commandText)
{
//pass through the call providing null for the set of SqlParameters
return ExecuteDataset(transaction, commandType, commandText, (SqlParameter[])null);
}

/// <summary>
/// Execute a SqlCommand (that returns a resultset) against the specified SqlTransaction
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
///  DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="transaction">a valid SqlTransaction</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>a dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
//create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters);

//create the DataAdapter & DataSet
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();

//fill the DataSet using default values for DataTable names, etc.
da.Fill(ds);

// detach the SqlParameters from the command object, so they can be used again.
cmd.Parameters.Clear();

//return the dataset
return ds;
}

/// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified
/// SqlTransaction using the provided parameter values.  This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
///  DataSet ds = ExecuteDataset(trans, "GetOrders", 24, 36);
/// </remarks>
/// <param name="transaction">a valid SqlTransaction</param>
/// <param name="spName">the name of the stored procedure</param>
/// <param name="parameterValues">an array of objects to be assigned as the input values of the stored procedure</param>
/// <returns>a dataset containing the resultset generated by the command</returns>
public static DataSet ExecuteDataset(SqlTransaction transaction, string spName, params object[] parameterValues)
{
//if we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > 0))
{
//pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection.ConnectionString, spName);

//assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues);

//call the overload that takes an array of SqlParameters
return ExecuteDataset(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
//otherwise we can just call the SP without params
else
{
return ExecuteDataset(transaction, CommandType.StoredProcedure, spName);
}
}

#endregion ExecuteDataSet

#region ExecuteReader

/// <summary>
/// this enum is used to indicate whether the connection was provided by the caller, or created by SqlHelper, so that
/// we can set the appropriate CommandBehavior when calling ExecuteReader()
/// </summary>
private enum SqlConnectionOwnership
{
/// <summary>Connection is owned and managed by SqlHelper</summary>
Internal,
/// <summary>Connection is owned and managed by the caller</summary>
External
}

/// <summary>
/// Create and prepare a SqlCommand, and call ExecuteReader with the appropriate CommandBehavior.
/// </summary>
/// <remarks>
/// If we created and opened the connection, we want the connection to be closed when the DataReader is closed.
///
/// If the caller provided the connection, we want to leave it to them to manage.
/// </remarks>
/// <param name="connection">a valid SqlConnection, on which to execute this command</param>
/// <param name="transaction">a valid SqlTransaction, or 'null'</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParameters to be associated with the command or 'null' if no parameters are required</param>
/// <param name="connectionOwnership">indicates whether the connection parameter was provided by the caller, or created by SqlHelper</param>
/// <returns>SqlDataReader containing the results of the command</returns>
private static SqlDataReader ExecuteReader(SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters, SqlConnectionOwnership connectionOwnership)
{
//create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, transaction, commandType, commandText, commandParameters);

//create a reader
SqlDataReader dr;

// call ExecuteReader with the appropriate CommandBehavior
if (connectionOwnership == SqlConnectionOwnership.External)
{
dr = cmd.ExecuteReader();
}
else
{
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}

// detach the SqlParameters from the command object, so they can be used again.
cmd.Parameters.Clear();

return dr;
}

/// <summary>
/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the database specified in
/// the connection string.
/// </summary>
/// <remarks>
/// e.g.:
///  SqlDataReader dr = ExecuteReader(connString, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="connectionString">a valid connection string for a SqlConnection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <returns>a SqlDataReader containing the resultset generated by the command</returns>
public static SqlDataReader ExecuteReader(string connectionString, CommandType commandType, string commandText)
{
//pass through the call providing null for the set of SqlParameters
return ExecuteReader(connectionString, commandType, commandText, (SqlParameter[])null);
}

/// <summary>
/// Execute a SqlCommand (that returns a resultset) against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
///  SqlDataReader dr = ExecuteReader(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">a valid connection string for a SqlConnection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>a SqlDataReader containing the resultset generated by the command</returns>
public static SqlDataReader ExecuteReader(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
//create & open a SqlConnection
SqlConnection cn = new SqlConnection(connectionString);
cn.Open();

try
{
//call the private overload that takes an internally owned connection in place of the connection string
return ExecuteReader(cn, null, commandType, commandText, commandParameters,SqlConnectionOwnership.Internal);
}
catch
{
//if we fail to return the SqlDatReader, we need to close the connection ourselves
cn.Close();
throw;
}
}

/// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a resultset) against the database specified in
/// the connection string using the provided parameter values.  This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
///  SqlDataReader dr = ExecuteReader(connString, "GetOrders", 24, 36);
/// </remarks>
/// <param name="connectionString">a valid connection string for a SqlConnection</param>
/// <param name="spName">the name of the stored procedure</param>
/// <param name="parameterValues">an array of objects to be assigned as the input values of the stored procedure</param>
/// <returns>a SqlDataReader containing the resultset generated by the command</returns>
public static SqlDataReader ExecuteReader(string connectionString, string spName, params object[] parameterValues)
{
//if we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > 0))
{
//pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);

//assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues);

//call the overload that takes an array of SqlParameters
return ExecuteReader(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
//otherwise we can just call the SP without params
else
{
return ExecuteReader(connectionString, CommandType.StoredProcedure, spName);
}
}

/// <summary>
/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlConnection.
/// </summary>
/// <remarks>
/// e.g.:
///  SqlDataReader dr = ExecuteReader(conn, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="connection">a valid SqlConnection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <returns>a SqlDataReader containing the resultset generated by the command</returns>
public static SqlDataReader ExecuteReader(SqlConnection connection, CommandType commandType, string commandText)
{
//pass through the call providing null for the set of SqlParameters
return ExecuteReader(connection, commandType, commandText, (SqlParameter[])null);
}

/// <summary>
/// Execute a SqlCommand (that returns a resultset) against the specified SqlConnection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
///  SqlDataReader dr = ExecuteReader(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connection">a valid SqlConnection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>a SqlDataReader containing the resultset generated by the command</returns>
public static SqlDataReader ExecuteReader(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
//pass through the call to the private overload using a null transaction value and an externally owned connection
return ExecuteReader(connection, (SqlTransaction)null, commandType, commandText, commandParameters, SqlConnectionOwnership.External);
}

/// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection
/// using the provided parameter values.  This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
///  SqlDataReader dr = ExecuteReader(conn, "GetOrders", 24, 36);
/// </remarks>
/// <param name="connection">a valid SqlConnection</param>
/// <param name="spName">the name of the stored procedure</param>
/// <param name="parameterValues">an array of objects to be assigned as the input values of the stored procedure</param>
/// <returns>a SqlDataReader containing the resultset generated by the command</returns>
public static SqlDataReader ExecuteReader(SqlConnection connection, string spName, params object[] parameterValues)
{
//if we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection.ConnectionString, spName);

AssignParameterValues(commandParameters, parameterValues);

return ExecuteReader(connection, CommandType.StoredProcedure, spName, commandParameters);
}
//otherwise we can just call the SP without params
else
{
return ExecuteReader(connection, CommandType.StoredProcedure, spName);
}
}

/// <summary>
/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction.
/// </summary>
/// <remarks>
/// e.g.:
///  SqlDataReader dr = ExecuteReader(trans, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="transaction">a valid SqlTransaction</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <returns>a SqlDataReader containing the resultset generated by the command</returns>
public static SqlDataReader ExecuteReader(SqlTransaction transaction, CommandType commandType, string commandText)
{
//pass through the call providing null for the set of SqlParameters
return ExecuteReader(transaction, commandType, commandText, (SqlParameter[])null);
}

/// <summary>
/// Execute a SqlCommand (that returns a resultset) against the specified SqlTransaction
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
///   SqlDataReader dr = ExecuteReader(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="transaction">a valid SqlTransaction</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>a SqlDataReader containing the resultset generated by the command</returns>
public static SqlDataReader ExecuteReader(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
//pass through to private overload, indicating that the connection is owned by the caller
return ExecuteReader(transaction.Connection, transaction, commandType, commandText, commandParameters, SqlConnectionOwnership.External);
}

/// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified
/// SqlTransaction using the provided parameter values.  This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
///  SqlDataReader dr = ExecuteReader(trans, "GetOrders", 24, 36);
/// </remarks>
/// <param name="transaction">a valid SqlTransaction</param>
/// <param name="spName">the name of the stored procedure</param>
/// <param name="parameterValues">an array of objects to be assigned as the input values of the stored procedure</param>
/// <returns>a SqlDataReader containing the resultset generated by the command</returns>
public static SqlDataReader ExecuteReader(SqlTransaction transaction, string spName, params object[] parameterValues)
{
//if we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection.ConnectionString, spName);

AssignParameterValues(commandParameters, parameterValues);

return ExecuteReader(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
//otherwise we can just call the SP without params
else
{
return ExecuteReader(transaction, CommandType.StoredProcedure, spName);
}
}

#endregion ExecuteReader

#region ExecuteScalar

/// <summary>
/// Execute a SqlCommand (that returns a 1x1 resultset and takes no parameters) against the database specified in
/// the connection string.
/// </summary>
/// <remarks>
/// e.g.:
///  int orderCount = (int)ExecuteScalar(connString, CommandType.StoredProcedure, "GetOrderCount");
/// </remarks>
/// <param name="connectionString">a valid connection string for a SqlConnection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <returns>an object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalar(string connectionString, CommandType commandType, string commandText)
{
//pass through the call providing null for the set of SqlParameters
return ExecuteScalar(connectionString, commandType, commandText, (SqlParameter[])null);
}

/// <summary>
/// Execute a SqlCommand (that returns a 1x1 resultset) against the database specified in the connection string
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
///  int orderCount = (int)ExecuteScalar(connString, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connectionString">a valid connection string for a SqlConnection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>an object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalar(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
//create & open a SqlConnection, and dispose of it after we are done.
using (SqlConnection cn = new SqlConnection(connectionString))
{
cn.Open();

//call the overload that takes a connection in place of the connection string
return ExecuteScalar(cn, commandType, commandText, commandParameters);
}
}

/// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a 1x1 resultset) against the database specified in
/// the connection string using the provided parameter values.  This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
///  int orderCount = (int)ExecuteScalar(connString, "GetOrderCount", 24, 36);
/// </remarks>
/// <param name="connectionString">a valid connection string for a SqlConnection</param>
/// <param name="spName">the name of the stored procedure</param>
/// <param name="parameterValues">an array of objects to be assigned as the input values of the stored procedure</param>
/// <returns>an object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalar(string connectionString, string spName, params object[] parameterValues)
{
//if we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > 0))
{
//pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);

//assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues);

//call the overload that takes an array of SqlParameters
return ExecuteScalar(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
//otherwise we can just call the SP without params
else
{
return ExecuteScalar(connectionString, CommandType.StoredProcedure, spName);
}
}

/// <summary>
/// Execute a SqlCommand (that returns a 1x1 resultset and takes no parameters) against the provided SqlConnection.
/// </summary>
/// <remarks>
/// e.g.:
///  int orderCount = (int)ExecuteScalar(conn, CommandType.StoredProcedure, "GetOrderCount");
/// </remarks>
/// <param name="connection">a valid SqlConnection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <returns>an object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalar(SqlConnection connection, CommandType commandType, string commandText)
{
//pass through the call providing null for the set of SqlParameters
return ExecuteScalar(connection, commandType, commandText, (SqlParameter[])null);
}

/// <summary>
/// Execute a SqlCommand (that returns a 1x1 resultset) against the specified SqlConnection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
///  int orderCount = (int)ExecuteScalar(conn, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connection">a valid SqlConnection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>an object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalar(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
//create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters);

//execute the command & return the results
object retval = cmd.ExecuteScalar();

// detach the SqlParameters from the command object, so they can be used again.
cmd.Parameters.Clear();
return retval;

}

/// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a 1x1 resultset) against the specified SqlConnection
/// using the provided parameter values.  This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
///  int orderCount = (int)ExecuteScalar(conn, "GetOrderCount", 24, 36);
/// </remarks>
/// <param name="connection">a valid SqlConnection</param>
/// <param name="spName">the name of the stored procedure</param>
/// <param name="parameterValues">an array of objects to be assigned as the input values of the stored procedure</param>
/// <returns>an object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalar(SqlConnection connection, string spName, params object[] parameterValues)
{
//if we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > 0))
{
//pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection.ConnectionString, spName);

//assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues);

//call the overload that takes an array of SqlParameters
return ExecuteScalar(connection, CommandType.StoredProcedure, spName, commandParameters);
}
//otherwise we can just call the SP without params
else
{
return ExecuteScalar(connection, CommandType.StoredProcedure, spName);
}
}

/// <summary>
/// Execute a SqlCommand (that returns a 1x1 resultset and takes no parameters) against the provided SqlTransaction.
/// </summary>
/// <remarks>
/// e.g.:
///  int orderCount = (int)ExecuteScalar(trans, CommandType.StoredProcedure, "GetOrderCount");
/// </remarks>
/// <param name="transaction">a valid SqlTransaction</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <returns>an object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalar(SqlTransaction transaction, CommandType commandType, string commandText)
{
//pass through the call providing null for the set of SqlParameters
return ExecuteScalar(transaction, commandType, commandText, (SqlParameter[])null);
}

/// <summary>
/// Execute a SqlCommand (that returns a 1x1 resultset) against the specified SqlTransaction
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
///  int orderCount = (int)ExecuteScalar(trans, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="transaction">a valid SqlTransaction</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>an object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalar(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
//create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters);

//execute the command & return the results
object retval = cmd.ExecuteScalar();

// detach the SqlParameters from the command object, so they can be used again.
cmd.Parameters.Clear();
return retval;
}

/// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a 1x1 resultset) against the specified
/// SqlTransaction using the provided parameter values.  This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
///  int orderCount = (int)ExecuteScalar(trans, "GetOrderCount", 24, 36);
/// </remarks>
/// <param name="transaction">a valid SqlTransaction</param>
/// <param name="spName">the name of the stored procedure</param>
/// <param name="parameterValues">an array of objects to be assigned as the input values of the stored procedure</param>
/// <returns>an object containing the value in the 1x1 resultset generated by the command</returns>
public static object ExecuteScalar(SqlTransaction transaction, string spName, params object[] parameterValues)
{
//if we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > 0))
{
//pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection.ConnectionString, spName);

//assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues);

//call the overload that takes an array of SqlParameters
return ExecuteScalar(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
//otherwise we can just call the SP without params
else
{
return ExecuteScalar(transaction, CommandType.StoredProcedure, spName);
}
}

#endregion ExecuteScalar

#region ExecuteXmlReader

/// <summary>
/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlConnection.
/// </summary>
/// <remarks>
/// e.g.:
///  XmlReader r = ExecuteXmlReader(conn, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="connection">a valid SqlConnection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command using "FOR XML AUTO"</param>
/// <returns>an XmlReader containing the resultset generated by the command</returns>
public static XmlReader ExecuteXmlReader(SqlConnection connection, CommandType commandType, string commandText)
{
//pass through the call providing null for the set of SqlParameters
return ExecuteXmlReader(connection, commandType, commandText, (SqlParameter[])null);
}

/// <summary>
/// Execute a SqlCommand (that returns a resultset) against the specified SqlConnection
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
///  XmlReader r = ExecuteXmlReader(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="connection">a valid SqlConnection</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command using "FOR XML AUTO"</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>an XmlReader containing the resultset generated by the command</returns>
public static XmlReader ExecuteXmlReader(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
//create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters);

//create the DataAdapter & DataSet
XmlReader retval = cmd.ExecuteXmlReader();

// detach the SqlParameters from the command object, so they can be used again.
cmd.Parameters.Clear();
return retval;

}

/// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified SqlConnection
/// using the provided parameter values.  This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
///  XmlReader r = ExecuteXmlReader(conn, "GetOrders", 24, 36);
/// </remarks>
/// <param name="connection">a valid SqlConnection</param>
/// <param name="spName">the name of the stored procedure using "FOR XML AUTO"</param>
/// <param name="parameterValues">an array of objects to be assigned as the input values of the stored procedure</param>
/// <returns>an XmlReader containing the resultset generated by the command</returns>
public static XmlReader ExecuteXmlReader(SqlConnection connection, string spName, params object[] parameterValues)
{
//if we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > 0))
{
//pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection.ConnectionString, spName);

//assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues);

//call the overload that takes an array of SqlParameters
return ExecuteXmlReader(connection, CommandType.StoredProcedure, spName, commandParameters);
}
//otherwise we can just call the SP without params
else
{
return ExecuteXmlReader(connection, CommandType.StoredProcedure, spName);
}
}

/// <summary>
/// Execute a SqlCommand (that returns a resultset and takes no parameters) against the provided SqlTransaction.
/// </summary>
/// <remarks>
/// e.g.:
///  XmlReader r = ExecuteXmlReader(trans, CommandType.StoredProcedure, "GetOrders");
/// </remarks>
/// <param name="transaction">a valid SqlTransaction</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command using "FOR XML AUTO"</param>
/// <returns>an XmlReader containing the resultset generated by the command</returns>
public static XmlReader ExecuteXmlReader(SqlTransaction transaction, CommandType commandType, string commandText)
{
//pass through the call providing null for the set of SqlParameters
return ExecuteXmlReader(transaction, commandType, commandText, (SqlParameter[])null);
}

/// <summary>
/// Execute a SqlCommand (that returns a resultset) against the specified SqlTransaction
/// using the provided parameters.
/// </summary>
/// <remarks>
/// e.g.:
///  XmlReader r = ExecuteXmlReader(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24));
/// </remarks>
/// <param name="transaction">a valid SqlTransaction</param>
/// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
/// <param name="commandText">the stored procedure name or T-SQL command using "FOR XML AUTO"</param>
/// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
/// <returns>an XmlReader containing the resultset generated by the command</returns>
public static XmlReader ExecuteXmlReader(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
//create a command and prepare it for execution
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters);

//create the DataAdapter & DataSet
XmlReader retval = cmd.ExecuteXmlReader();

// detach the SqlParameters from the command object, so they can be used again.
cmd.Parameters.Clear();
return retval;
}

/// <summary>
/// Execute a stored procedure via a SqlCommand (that returns a resultset) against the specified
/// SqlTransaction using the provided parameter values.  This method will query the database to discover the parameters for the
/// stored procedure (the first time each stored procedure is called), and assign the values based on parameter order.
/// </summary>
/// <remarks>
/// This method provides no access to output parameters or the stored procedure's return value parameter.
///
/// e.g.:
///  XmlReader r = ExecuteXmlReader(trans, "GetOrders", 24, 36);
/// </remarks>
/// <param name="transaction">a valid SqlTransaction</param>
/// <param name="spName">the name of the stored procedure</param>
/// <param name="parameterValues">an array of objects to be assigned as the input values of the stored procedure</param>
/// <returns>a dataset containing the resultset generated by the command</returns>
public static XmlReader ExecuteXmlReader(SqlTransaction transaction, string spName, params object[] parameterValues)
{
//if we receive parameter values, we need to figure out where they go
if ((parameterValues != null) && (parameterValues.Length > 0))
{
//pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection.ConnectionString, spName);

//assign the provided values to these parameters based on parameter order
AssignParameterValues(commandParameters, parameterValues);

//call the overload that takes an array of SqlParameters
return ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
//otherwise we can just call the SP without params
else
{
return ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName);
}
}


#endregion ExecuteXmlReader
}

/// <summary>
/// SqlHelperParameterCache provides functions to leverage a static cache of procedure parameters, and the
/// ability to discover parameters for stored procedures at run-time.
/// </summary>
public sealed class SqlHelperParameterCache
{
#region private methods, variables, and constructors

//Since this class provides only static methods, make the default constructor private to prevent
//instances from being created with "new SqlHelperParameterCache()".
private SqlHelperParameterCache() {}

private static Hashtable paramCache = Hashtable.Synchronized(new Hashtable());

/// <summary>
/// resolve at run time the appropriate set of SqlParameters for a stored procedure
/// </summary>
/// <param name="connectionString">a valid connection string for a SqlConnection</param>
/// <param name="spName">the name of the stored procedure</param>
/// <param name="includeReturnValueParameter">whether or not to include their return value parameter</param>
/// <returns></returns>
private static SqlParameter[] DiscoverSpParameterSet(string connectionString, string spName, bool includeReturnValueParameter)
{
using (SqlConnection cn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(spName,cn))
{
cn.Open();
cmd.CommandType = CommandType.StoredProcedure;

SqlCommandBuilder.DeriveParameters(cmd);

if (!includeReturnValueParameter)
{
cmd.Parameters.RemoveAt(0);
}

SqlParameter[] discoveredParameters = new SqlParameter[cmd.Parameters.Count];;

cmd.Parameters.CopyTo(discoveredParameters, 0);

return discoveredParameters;
}
}

//deep copy of cached SqlParameter array
private static SqlParameter[] CloneParameters(SqlParameter[] originalParameters)
{
SqlParameter[] clonedParameters = new SqlParameter[originalParameters.Length];

for (int i = 0, j = originalParameters.Length; i < j; i++)
{
clonedParameters[i] = (SqlParameter)((ICloneable)originalParameters[i]).Clone();
}

return clonedParameters;
}

#endregion private methods, variables, and constructors

#region caching functions

/// <summary>
/// add parameter array to the cache
/// </summary>
/// <param name="connectionString">a valid connection string for a SqlConnection</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <param name="commandParameters">an array of SqlParamters to be cached</param>
public static void CacheParameterSet(string connectionString, string commandText, params SqlParameter[] commandParameters)
{
string hashKey = connectionString + ":" + commandText;

paramCache[hashKey] = commandParameters;
}

/// <summary>
/// retrieve a parameter array from the cache
/// </summary>
/// <param name="connectionString">a valid connection string for a SqlConnection</param>
/// <param name="commandText">the stored procedure name or T-SQL command</param>
/// <returns>an array of SqlParamters</returns>
public static SqlParameter[] GetCachedParameterSet(string connectionString, string commandText)
{
string hashKey = connectionString + ":" + commandText;

SqlParameter[] cachedParameters = (SqlParameter[])paramCache[hashKey];

if (cachedParameters == null)
{
return null;
}
else
{
return CloneParameters(cachedParameters);
}
}

#endregion caching functions

#region Parameter Discovery Functions

/// <summary>
/// Retrieves the set of SqlParameters appropriate for the stored procedure
/// </summary>
/// <remarks>
/// This method will query the database for this information, and then store it in a cache for future requests.
/// </remarks>
/// <param name="connectionString">a valid connection string for a SqlConnection</param>
/// <param name="spName">the name of the stored procedure</param>
/// <returns>an array of SqlParameters</returns>
public static SqlParameter[] GetSpParameterSet(string connectionString, string spName)
{
return GetSpParameterSet(connectionString, spName, false);
}

/// <summary>
/// Retrieves the set of SqlParameters appropriate for the stored procedure
/// </summary>
/// <remarks>
/// This method will query the database for this information, and then store it in a cache for future requests.
/// </remarks>
/// <param name="connectionString">a valid connection string for a SqlConnection</param>
/// <param name="spName">the name of the stored procedure</param>
/// <param name="includeReturnValueParameter">a bool value indicating whether the return value parameter should be included in the results</param>
/// <returns>an array of SqlParameters</returns>
public static SqlParameter[] GetSpParameterSet(string connectionString, string spName, bool includeReturnValueParameter)
{
string hashKey = connectionString + ":" + spName + (includeReturnValueParameter ? ":include ReturnValue Parameter":"");

SqlParameter[] cachedParameters;

cachedParameters = (SqlParameter[])paramCache[hashKey];

if (cachedParameters == null)
{
cachedParameters = (SqlParameter[])(paramCache[hashKey] = DiscoverSpParameterSet(connectionString, spName, includeReturnValueParameter));
}

return CloneParameters(cachedParameters);
}

#endregion Parameter Discovery Functions

}
}