using statement example in asp.net uses of using statement

Introduction:

In this article I will explain uses of using statement and how to declare and use using statement in asp.net.


Description:

Generally in our applications we will write code like create connection object to handle connectionstring after that open a connection and create command object etc. to interact with database to get data that would be like this 

SqlConnection con = new SqlConnection(connectionString);
con.Open();
SqlCommand cmd = new SqlCommand (commandString, con);
cmd.ExecuteNonQuery();
con.Close();
It’s very easy way to write above code but problem is SqlConnection and SqlCommand objects will create IDISPOSABLE interface that means it could create unmanaged resources in our application to cleanup those objects we need to call Dispose() method at the end of our process otherwise those objects will remain in our application.
Suppose we use using statement in our applications it will automatically create try / finally blocks for the objects and automatically runs Dispose() method for us no need to create any try/finally block and no need to run any Dispose() method.
If we use using statement we need to write code will be like this 
C# Code

using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand (commandString, con))
{
con.Open();
cmd.ExecuteNonQuery();
}
}
VB.NET Code

Using con As New SqlConnection(connectionString)
Using cmd As New SqlCommand(commandString, con)
con.Open()
cmd.ExecuteNonQuery()
End Using
End Using
In above code using statement no need to worry about close connection because using statement automatically close the connection once process is complete and automatically it will run Dispose() method to dispose objects. 
The above using statement code will equal to below code 
SqlConnection con = null;
SqlCommand cmd = null;
try
{
con = new SqlConnection(connectionString);
cmd = new SqlCommand(commandString, con);
con.Open();
cmd.EndExecuteNonQuery();
}
finally
{
if (con != null)
con.Dispose();
if (cmd != null)
cmd.Dispose();
}
Sample Code to display data in gridview by using statement 
First open Default.aspx page and write the following code
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvDetails" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>
After that open code behind page and add the following namespace references
using System;
using System.Configuration;
using System.Web.Configuration;
After add namespaces write the following code in code behind
C# code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridviewData();
}
}
//Bind Data to Repeater Control
protected void BindGridviewData()
{
string connectionString = "Data Source=ARYAN-PC\SQLEXPRESS;Initial Catalog=SalmanTempDB;Integrated Security=true";
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd=new SqlCommand("select * from Repeater_Table Order By PostedDate desc",con))
{
con.Open();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
gvDetails.DataSource = dt;
gvDetails.DataBind();
}
}
}
VB.NET Code
Imports System.Data
Imports System.Data.SqlClient
Partial Class Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGridviewData()
End If
End Sub
'Bind Data to Repeater Control
Protected Sub BindGridviewData()
Dim connectionString As String = "Data Source=ARYAN-PC\SQLEXPRESS;Initial Catalog=SalmanTempDB;Integrated Security=true"
Using con As New SqlConnection(connectionString)
Using cmd As New SqlCommand("select * from Repeater_Table Order By PostedDate desc", con)
con.Open()
Dim dt As New DataTable()
Dim da As New SqlDataAdapter(cmd)
da.Fill(dt)
gvDetails.DataSource = dt
gvDetails.DataBind()
End Using
End Using
End Sub
End Class

A Closer Look Inside RAISERROR - SQLServer 2005

This article describes how to use RAISERROR in SQL Server 2005

Table of Contents 

  • Introduction
  • Overview of RAISERROR
  • General Syntax for using RAISERROR
  • Parameters of RAISERROR
    • Message ID
    • Message Text
    • Severity
    • States
  • WITH Options
    • LOG
    • NOWAIT
    • SETERROR
  • Looking Inside Sp_addmessage  
    • @msgnum
    • @severity
    • @msgtext
    • @lang
    • @with_log
    • @replace
  • ALL In One Example
    • Add a User-defined Message
    • Check the Details Inside
    • Call RAISERROR
    • Store Error Inside Event Log
    • Replace the Existing Message
    • Use Try-Catch with RAISE ERROR

Introduction

This is a pre-extension article of one of my recently published articles, Error Handling in SQL Server 2005. There were a few gaps that I didn't mention about raise error. So, I linked it to that article, so that readers can have a better view on Error handling. Here I have explained only those things which we use generally while working in SQL Server. If you want to know details, please have a look into Further Study and Reference Section. Please give your valuable suggestions and feedback.

Overview of RAISERROR 

SQL Server has its own error handling mechanism, where @@Error is used to trap the errors and we can get the Error Message for that error. RAISERROR allows developers to produce our own error message. Using RAISERROR, we can throw our own error message while running our Query or Stored procedure. RAISERROR is used to return messages back to applications using the same format as a system error or warning message generated by the SQL Server Database Engine. We can also set our own severity for each and every individual message.
To conclude the summary:
  • It allows developers to generate their own messages
  • It returns the same message format that is generated by SQL Server Database Engine
  • We can set our own level of Severity for messages
  • It can be associated with Query and stored procedure

General Syntax for using RAISERROR

Below is the general syntax for RAISERROR:

RAISERROR ( { Message ID | Message Text}
    { ,severity ,state }
    [ ,argument [ ,...n ] ] )
    [ WITH option [ ,...n ] ]
Let's divide the block for better understanding.

Parameters of RAISERROR

RAISERROR ( { Message ID | Message Text}
Generally we can use a specific message id (msg_id) or provide an error message string.

Message ID

Is a user-defined error message number stored in the sys.messages catalog view. Error numbers for user-defined error messages should be greater than 50000. By default, RAISERROR raises an error message with an error number of 50000.
We can add error number using sp_addmessge in the following way:

exec sp_addmessage @msgnum=50009,@severity=1,@msgtext='Custom Error Message'
Now, if you want to check what the original location that messages are stored in, you need to run the following query:

select * from sys.messages 
Have a look at the below images, where I have explained the step by step procedures. Right now, forget about @Severity parameter and other optional parameter. I have explained them later.
This is how the data is stored inside SQL Server and returned by the SQL Server Database Engine when we call like this...

RAISERROR ( 50009,1,1)
... which will show us the below output:

Custom Error Message
Msg 50009, Level 1, State 1
Now, I guess you can co-relate things. Let's move to message text parameter.

Message Text

This is the message description, that I have already explained in the last example and you are now also aware where it is stored physically. Error message has certain limitations:
  • The error message can have a maximum of 2,047 characters
  • If the message has more than 2,047 characters, then will show only 2,044 characters with an ellipsis to indicate that the message has been truncated
As I have already mentioned, if we did not specify any message number, RAISERROR will use 50000 ID by default. This is the only reason we need to specify the error message ID more than 50000. If we add any message with ID 50000, it will throw the following error:

User-defined error messages must have an ID greater than 50000.
There are certain parameters used with message text. For that, I will recommend you read the article that I have mentioned in the Further Study section.
Now, just have a look at the other two parameters of RAISERROR:

 RAISERROR ( { Message ID| Message Text}
    { ,severity ,state }
These stand for set Severity and state for the message. These two are numeric types and relate to how severe the message is.

Severity

We have to mention severity, while adding the message using sp_addmessage. Range of Severity level is 0-25. But for user defined message, we have to set it up to 0-19. 20-25 can only be set by the administrator. Severity levels from 20 through 25 are considered fatal.

States

For any message related to RAISERROR, we have to specify the state also. The default State value is 1. The range of state is from 1 to 127. But for most implementations, we use 1. We can use it to indicate which error was thrown by providing a different state for each RAISERROR function in our stored procedure. This is a required parameter.

WITH Options

Finally, there are options that we can set, these are the WITH options.

LOG

It will place the error in windows Error log. We have to mention this parameter while adding the message using sp_addmessage.

exec sp_addmessage @msgnum=50002,@severity=1,_
 @msgtext='This Error Message Will Store into EVENT VIEWER',@with_log='true'
Now, if we want to test the result, just execute this command RAISERROR ( 50002,1,1) , we can get an entry in EventViewer.

NOWAIT

Send the error directly to client.

SETERROR

It will replace the error ID with 5000.

Looking Inside Sp_addmessage

I have already explained it previously. Here I am going to give you a brief overall syntax and the arguments it needs.

    sp_addmessage [ @msgnum= ] msg_id, [ @severity= ] severity , 
    [ @msgtext = ' ] 'message'
    [, [ @lang = ] 'Language' ]
    [, [ @with_log = ] 'log' ]
    [, [ @replace = ] 'replace' ] 
Here is the general overview of those parameters.

@msgnum

Indicates the number of the message. It should be greater than 50000.

@severity

We used 1 in most cases. General range is 1 to 25. I have already covered the details.

@msgtext

Message text, maximum characters limit is 2,047. More than that will be truncated.

@lang

Used if you want to specify any language.

@with_log

As I have already shown in example, Set 'TRUE' to log the error in EventViewer.

@replace

If the same message number already exists, but you want to replace the string for that ID, you have to use this parameter.

ALL In One Example

Now have a look into a simple example where we can check each and every point that has been discussed above.

Add a User-defined Message

To add an error message, we have to use sp_addmessgae stored procedure. This message will store inside sys.messages. The error number should be greater than 5000.

exec sp_addmessage @msgnum=50010,@severity=1,_
 @msgtext='User-Defined Message with ID 50010'

Check The Details Inside

This is not mandatory, you can check the original location and how it is stored by just running the following query:

select * from sys.messages 
 
This will give you the following output:
message_id  language_id severity is_event_logged text
----------- ----------- -------- --------------- ----------------------------
50010       1033        1        1               User-Defined Message with ID 50010

Call RAISERROR

Now we can retrieve the message using RAISERROR:

RAISERROR ( 50010,1,1)
 
This will give the following output:
User-Defined Message with ID 50010
Msg 50010, Level 1, State 1

Store Error Inside Event Log

If we need to store the message inside Event Viewer, we have to use @with_log parameter:

sp_addmessage @msgnum=50002,@severity=1,_
 @msgtext='This Error Message Will Store into EVENT VIEWER',@with_log='true'
I have already covered that part how it is stored inside Event Viewer.

Replace the Existing Message

If we have already set the message for some error id and we want to replace the message, it will throw an error as follows:
You must specify 'REPLACE' to overwrite an existing message.
   So, for replacing message we have to use 
 @replace parameter with sp_addmessge Stored procedure.
 
Here is the syntax:
exec sp_addmessage @msgnum=50010,@severity=1,_
 @msgtext='User-Defined Message with ID 50010-Replaced Message',_
 @with_log='true', @replace='replace'

This will replace the message for the id 50010. 
You can try it using run RAISERROR again.  

Use Try-Catch with RAISE ERROR

The below code is a simple example where I have shown how we can use RAISERROR inside TRY-CATCH Block:
 
BEGIN TRY
DECLARE @Intval int;
SET @Intval = 1/0; -- Divide by Zero Error
END TRY
BEGIN CATCH
RAISERROR (50009, 11, 1);  -- 50009 is our pre-defined error 
   -- that are stored using sp_addmessage
END CATCH;

Reference and Further Study

 

Maintaining temporary table in ASP.NET


What -- To create a variable with table-like structure and to store the information within it. And to retains the records with page postbacks.
Why --  The need of temporary table may be necessary if you don't want to interact with the database as and when you need it. Rather you prefer storing all information in some intermediate variable and on certain conditions to synchronize these data with the database. It will increase your execution speed causing faster application loading which will give the end user more comfort and satisfaction.
How --  
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
{

    // To add Autoincremented column to the table.
    DataColumn dcSlno = new DataColumn("PK_ID");
    dcSlno.AutoIncrement = true;
    dcSlno.AutoIncrementSeed = 0;
    dcSlno.AutoIncrementStep = 1;
    dcSlno.DataType = typeof(Int32);
    dtTemp.Columns.Add(dcSlno);


    // To add column with the default value.
    DataColumn points = new DataColumn();
    points.ColumnName = "POINTS";
    points.DataType = typeof(Int32);
    points.DefaultValue = 1;
    dtTemp.Columns.Add(points);


    // If you want to add data from the database
    DataTable dtDatabase = null; // Fetch Data from database
    dtTemp = dtDatabase.Clone();
    dtTemp.Merge(dtDatabase);


    // TO insert SPecific rows to temp table.
    // ! note -- The structure of row must be matched with the structure of temporary rable.
    dtTemp.ImportRow(dtDatabase.Rows[0]);


    //Updation ::
    dtTemp.Rows[0].SetField<int>("POINTS", 20);


    // Deleation of record.
    dtTemp.Rows[1].Delete();


    //Filteration of records.
    string Expression = "POINT > 20";
    string sort = "SLNO ASC";
    DataRow[] drFiltered = dtTemp.Select(Expression, sort);


    foreach (DataRow dr in drFiltered)
    {
        dtTemp.ImportRow(dr);
    }
 
    //Another approach for filtering the contents , But execution time is more , so only acceptable for smaller amount of datarows.
    DataView dv = new DataView(dtTemp);
    dv.Sort = ("SLNO");
    dtTemp = dv.ToTable();


    // Storing of records during page postback..
    //One idea can be to store this table in viestate and retrive values from the viewstate each time.
 
    ViewState["TempTable"] = dtTemp;
    //Bind to the databinding control
    ListView1.DataSource = dtTemp;
    ListView1.DataBind();


}
if (Page.IsPostBack)
{

    // On each postback retrive the datatable from the view state
    if (ViewState["TempTable"] != null)
    {
        dtTemp = (DataTable)ViewState["TempTable"];
    }

    //Bind to the databinding control
    ListView1.DataSource = dtTemp;
    ListView1.DataBind();
} 
 

Note: The above approach should not be taken when working with large number of records as it may adversely affect performance 


// Create a temporary datatable.
DataTable dtTemp = new DataTable();

An easy way to bind 'DELETE confirmation message' to .NET controls



 You always come accross a confirmation message "Are you sure you want to delete this item ? " while deleting an item. In web application basically  we attach a javascript function with the OnClientClick event of the server control to ask user confirmation before delete the item.

     So this is not a big problem if we have a single server control like Button control to call the javascript function through the OnClientClick event like:

 function ConfirmDelete()
 {
          if(confirm("Are you sure you want to delete this item ?"))
         {
              return true;
         }
         else
         {
              return false;
          }       
 }

    But in case of GridView control if we need a confirmation message before deleting any row items from the grid then we have to bind the javascript function for each row's OnClientClick event of the grid control. This is a bit complex process. So we can have the other way to do this and can be done without binding the javascript function to each row's OnClientClick event of the grid.
Solutions:
 
1. Here we have a function The 'ConfirmDelete()' which is executed each time a click event occurs on the page.
2. Then we use a logic that to find which element was clicked on i.s we append a word 'DELETE' to the ID of the control.
3.And finally check if the clicked element having ID is 'DELETED' , then the javascript function will be execute to ask the user about his/her confirmation.
 
JavaScript code:
 
 function ConfirmDelete(e)
 {   
         var targ;
       
         if (!e)
        {  
            var e = window.event;
         }
         targ = (e.target) ? e.target : e.srcElement;
       
         if (targ.nodeType == 3)
         {
              targ = targ.parentNode;
         }
       
        if (targ.id.toLowerCase().indexOf("delete") >= 0)
        {       
              return confirm("Do you want to delete this item?");
         }
         routeEvent(e);
     } 
 document.onclick = ConfirmDelete;
 
aspx  code:

 <asp:GridView RunAt="server" ID="gvTest" DataSourceID="SqlDataSource1">
            <Columns>      
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:LinkButton runat="server"
                               ID="DeleteMe" Text="Delete" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

How to Add the Reference of a User Control in the web.config file in ASP.NET



Most of the time developers register the User Controls to individual asp.net pages where, controls are in use. If the control is in use in most of the pages of the site, the reference can be added at one place only, that is in the web.config.
 
 
Code to add in web.config file to register the user control
<configuration>
  <system.web>
    <pages>
      <controls>
        <add tagPrefix="uc1" src="~/usercontrols/Note.ascx" tagName="Note"/>
        <add tagPrefix="uc2" src="~/usercontrols/Diary.ascx" tagName="Diary"/>
      </controls>
    </pages>
  </system.web>
</configuration>
 
Code to use the user control in the page
<uc1:Note ID="ucNote" runat="server"/>
<uc2:Diary ID="ucDiary" runat="server"/>

A Scrollable GridView with a Fixed Header in .NET



One workaround is to have  a separate table control to show the header elements and hide the actual header of the grid.Now put the grid inside a div or panel with scrollbar property.But that takes extra effort to have a proper alignment.Each cell of the header table should be aligned with each cell of the grid.The other work around is to fix the header of the grid in such a way that scrolling down shouldnt hide the header of  the grid.Using stylesheet we can achieve that.
Add the following style in your code and assign the grid view or datagrid header style css.
.fixedHeader {
font-weight:bold;
position:absolute;
background-color: #006699;
color: #ffffff;
height: 25px;
top: expression(Sys.UI.DomElement.getBounds(document.getElementById("panelContainer")).y-25);
}
 "panelContainer" is the id of the panel . "Sys.UI.DomElement.getBounds(document.getElementById("panelContainer")).y " gives the exact  Y location of the panel where we need to fix the header.25 pixel is the usual height of the header .That much of space we had to leave for the header so that its not going to eat up any space of the grid content.With the Panel control, we can control the width, height, and scrollable option. For our code example, we set the height as 300px, the width as 100%, and set the Panel to scroll while showing only the vertical scrollbars. Put your grid inside the panel.Now we have to assign the CSS class defined above  to the GridView's HeaderStyle
<asp:Panel ID="panelContainer" runat="server" Height="300px" Width="100%"  ScrollBars="Vertical">
<asp:GridView ID="gvScrollableExample" runat="server">
<HeaderStyle CssClass="fixedHeader " />
</asp:GridView></asp:Panel>


This way we can fix the header at the top of the grid and scrolling down is not going to scroll the grid with the header.

How to publish content from another URL in a ContentPlaceHolder control



Follow the process below to publish content from another URL in a ContentPlaceHolder Control..
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
 
<asp:Literal runat=server ID="ltlContent" />
 
</asp:Content>
 
protected void Page_Load(object sender, EventArgs e)
      {
 
            try
            {
 
         WebRequest wReq = WebRequest.Create("http://yahoo.com");
         WebResponse mRes = wReq.GetResponse();
         StreamReader sr = new StreamReader(mRes.GetResponseStream());
         string sHTML = sr.ReadToEnd();
         sr.Close();
         mRes.Close();
 
             if (sHTML != string.Empty && sHTML != null)
              {
                ltlContent.Text = sHTML;
              }
 
            }
 
            catch (Exception eX)
        {
          Response.Write(eX.Message);
         }
       }

Using HttpForbiddenHandler to help securing resources

HttpForbiddenHandler can be used to restrict access to resources and files from being downloaded through HTTP.
Using <httpHandlers> in Machine.config
HTTP handlers are responsible for processing Web requests for specific file extensions. We can modify the <httpHandlers> section of Machine.Config file (default path of Mahine.Config file is %windir%\Microsoft.NET\Framework\{version}\CONFIG) to forbid access to any specific file extension.
Ex. Access to Web Services for a particular web server can be restricted by setting .asmx file types to HttpForbiddenHandler in machine.config file
go to the <httpHandlers> section and add the following line :
<add verb="*" path="*.asmx" type="System.Web.HttpForbiddenHandler" />

How to set the properties of ASP.NET Server controls for compatibility with different browsers


This is a small but useful trick that I recently came across.
We can set the properties of a server control according to the browser without writing a single line of javascript.
 
Let's check out some code samples:
 
Label control:
 
<asp:Label ID="lblTest" runat="server" ie:CssClass="IEStyle" mozilla:CssClass="FFStyle" CssClass="DefaultStyle" ie:Text="You are in Internet explorer." mozilla:Text="You are in Firefox." Text="You are in other browser." />
 
If we will define css classes like:
.IEStyle{color:Red;}
.FFStyle{color:Blue;}
.DefaultStyle{color:Black;}
 
Output:
IE  : You are in Internet explorer.
FF : You are in Firefox.
Others : You are in other browser.
 
TextBox Control:

<asp:TextBox ID="txtBoxTest" runat="server" ie:Text="You are in Internet explorer." mozilla:Text="You are in Firefox." Text="You are in other browser." ie:CssClass="IEStyle" mozilla:CssClass="FFStyle" CssClass="DefaultStyle" />
  
Output:
Same behaviour as of above label.
 
Button Control:

<asp:Button ID="btnTest" runat="server" ie:Text="Submit [IE]" mozilla:Text="Submit [FF]" Text="Submit [Others]" ie:OnClientClick="javascript:alert('You are in Internet explorer.');" mozilla:OnClientClick="javascript:alert('You are in Firefox!');" OnClientClick="javascript:alert('You are in other browser.');" ie:CssClass="IEStyle" mozilla:CssClass="FFStyle" CssClass="DefaultStyle" />
 
If we will define css classes like:
.IEStyle{color:Red;}
.FFStyle{color:Blue;}
.DefaultStyle{color:Black;}
 
Output :
IE  : Button with text " Submit [IE] ". By clicking that button one alert will appear which will say : "You are in Internet explorer."
FF : Button with text " Submit [FF] ". By clicking that button one alert will appear which will say : "You are in Firefox."
Others : Button with text " Submit [Others] ". By clicking that button one alert will appear which will say : "You are in other browser."
 
NOTE : There is no intellisense available for above in Visual Studio.

Paging and Sorting a GridView without Refreshing a Page



 We generally use a GridView Control to Display Data and also Perform Paging, Sorting, Editing, Deleting records. In each of these we have postback on the page.
To avoid Postback during sorting and Paging, the following code can be used inside the GridView Control.
 If you have created a GridView and Bind the GridView using data source control, you can avoid postback during sorting and paging by setting EnableSortingAndPagingCallbacks' property of the GridView to True.
N:B: when you use the 'EnableSortingAndPagingCallbacks' property to true for avoid Postback, you cannot use Template Fields in the GridView.
Ex:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowSorting = "true"
 DataSourceID="SqlDataSource1" EnableSortingAndPagingCallbacks = "true">
 <Columns>
  <asp:BoundField DataField="FIRST_NAME" HeaderText="First Name"
                    SortExpression="FIRST_NAME" />
  <asp:BoundField DataField="LAST_NAME" HeaderText="Last Name"
                    SortExpression="LAST_NAME" />
  <asp:BoundField DataField="ADDRESS" HeaderText="Address"
                    SortExpression="ADDRESS" />
 </Columns>                 
</asp:GridView>