Pages

Monday 16 December 2013

State Management In Asp.Net

In this article I'm going to discuss about various state management techniques used in Asp.Net.

Introduction

A new instance of the Web page class is created each time the page is posted to the server. In traditional Web programming, this would typically mean that all information associated with the page and the controls on the page would be lost with each round trip. For example, if a user enters information into a text box, that information would be lost in the round trip from the browser or client device to the server.

To overcome this inherent limitation of traditional Web programming, ASP.NET includes several options that help us to preserve data on both a per-page basis and an application-wide basis.


Types of State Management

We can categorize the state management techniques in following 2 types:

1. Client Side State management
2. Server Side State Management


Client Side State Management

Client side state management can be of following types:

1. Hidden Field: Hidden field is a control provided by ASP.NET which is used to store small amounts of data on the client. It store one value for the variable and it is a preferable way when a variable's value is changed frequently. Hidden field control is not rendered to the client (browser) and it is invisible on the browser. A hidden field travels with every request like a standard control’s value.


To declare a hidden field on aspx page we need to put the following asp.net control:
     <asp:HiddenField ID="HiddenField1" runat="server">

To Set the value of a hidden field from the code behind we need to put the following code:

 HiddenField1.Value="123";

2. ViewState: The ViewState property provides a dictionary object for retaining values between multiple requests for the same page. This is the default method that the page uses to preserve page and control property values between round trips.

When the page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field, or multiple hidden fields if the amount of data stored in the ViewState property exceeds the specified value in the MaxPageStateFieldLength property. When the page is posted back to the server, the page parses the view-state string at page initialization and restores property information in the page.

We can use ViewState in the following manner:

protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
 }   {
       if (ViewState["count"] != null)
        {
            int ViewstateVal = Convert.ToInt32(ViewState["count"]) + 1;
            Label1.Text = ViewstateVal.ToString();
            ViewState["count"]=ViewstateVal.ToString();
        }
        else
        {
            ViewState["count"] = "1";
        }
    }
}
protected void Button1_Click(object sender, EventArgs e)
{
       Label1.Text=ViewState["count"].ToString();
}

3. Control State: Control state is an object comprised of critical view state data that Web server controls need to function, and is contained in a separate object from normal view state information. Control state data is not affected when view state is disabled at the Page level, but requires extra implementation steps to use.
We can use control state in the following manner:
// Load ViewState and ControlState. 
// 
public override void Load()
{
    Stream stateStream = GetSecureStream();

    // Read the state string, using the StateFormatter.
    StreamReader reader = new StreamReader(stateStream);

    IStateFormatter formatter = this.StateFormatter;
    string fileContents = reader.ReadToEnd();

    // Deserilize returns the Pair object that is serialized in 
    // the Save method.
    Pair statePair = (Pair)formatter.Deserialize(fileContents);

    ViewState = statePair.First;
    ControlState = statePair.Second;
    reader.Close();
    stateStream.Close();
}
3. CookiesA cookie is a small amount of data that is stored either in a text file on the client file system or in-memory in the client browser session. It contains site-specific information that the server sends to the client along with page output. Cookies can be temporary (with specific expiration times and dates) or persistent.
We can use cookies to store information about a particular client, session, or application. The cookies are saved on the client device, and when the browser requests a page, the client sends the information in the cookie along with the request information. The server can read the cookie and extract its value. A typical use is to store a token (perhaps encrypted) indicating that the user has already been authenticated in your application.
Limitation of cookies: The number of cookies allowed is limited and varies according to the browser. Most browsers allow 20 cookies per server in a client's hard disk folder and the size of a cookie is not more than 4096 bytes or 4 KB of data that also includes name and value data.
Cookie can be of 2 types:
 a. Persistent Cookies: Cookies which you can set an expiry date time are called persistence cookies. Persistence cookies are permanently stored till the time you set.
Example:
            Response.Cookies["nameWithPCookies"].Value = "This is A Persistance Cookie";
       Response.Cookies["nameWithPCookies"].Expires = DateTime.Now.AddSeconds(10);
 b. Non-Persistent Cookies: Non persistence cookies are not permanently stored on the user client hard disk folder. It maintains user information as long as the user accesses the same browser. When user closes the browser the cookie will be discarded. Non Persistence cookies are useful for public computers.
Example: Response.Cookies["nameWithPCookies"].Value = "This is A Non Persistance Cookie";
3. QueryStringQuery String is information that is appended to the end of a page URL. A typical query string might look like the following examples:
  http://www.contoso.com/listwidgets.aspx?category=basic&price=100
to get the query string values from code behind we can use the following code:
  String Category=Request.QueryString["category"].ToString();
 Int Price=Convert.ToInt32(Request.QueryString["category"]
.ToString());
Server Side State Management

Server side state management can be of following types:
1. Application StateASP.NET allows you to save values using application state — which is an instance of the HttpApplicationState class — for each active Web application. Application state is a global storage mechanism that is accessible from all pages in the Web application. Thus, application state is useful for storing information that needs to be maintained between server round trips and between requests for pages.
Application state is stored in a key/value dictionary that is created during each request to a specific URL. You can add your application-specific information to this structure to store it between page requests.
Example:
Application["Count"] = Convert.ToInt32(Application["Count"]) + 1; //Set Value to The Application Object
Label1.Text = Application["Count"].ToString(); //Get Value from the Application Object     

Application events in ASP.NET

There are three types of events in ASP.NET. Application event is written in a special file called Global.asax. This file is not created by default, it is created explicitly by the developer in the root directory. An application can create more than one Global.asax file but only the root one is read by ASP.NET.
Application_start: The Application_Start event is raised when an app domain starts. When the first request is raised to an application then the Application_Start event is raised. Let's see the Global.asax file. 
Application_Error: It is raised when an unhandled exception occurs, and we can manage the exception in this event.
Application_End: The Application_End event is raised just before an application domain ends because of any reason, may IIS server restarting or making some changes in an application cycle. 
3. Session StateASP.NET allows you to save values by using session state — which is an instance of the HttpSessionState class — for each active Web-application session.
Session state is similar to application state, except that it is scoped to the current browser session. If different users are using your application, each user session will have a different session state. In addition, if a user leaves your application and then returns later, the second user session will have a different session state from the first.
Session state is structured as a key/value dictionary for storing session-specific information that needs to be maintained between server round trips and between requests for pages.
Example:
Session["Count"] = Convert.ToInt32(Session["Count"]) + 1;//Set Value to The Session
Label2.Text = Session["Count"].ToString(); //Get Value from the Sesion 

Session Events in ASP.NET  

To manage a session, ASP.NET provides two events: session_start and session_end that is written in a special file called Global.aspx in the root directory of the project. 
Session_Start: The Session_start event is raised every time a new user makes a request without a session ID, i.e., new browser accesses the application, then a session_start event raised. Let's see the Global.asax file.  
Session_End: The Session_End event is raised when session ends either because of a time out expiry or explicitly by using Session.Abandon(). The Session_End event is raised only in the case of In proc mode not in the state server and SQL Server modes. 
There are four session storage mechanisms provided by ASP.NET:
  • In Proc mode 
  • State Server mode  
  • SQL Server mode 
  • Custom mode 
In Process mode: In proc mode is the default mode provided by ASP.NET. In this mode, session values are stored in the web server's memory (in IIS). If there are more than one IIS servers then session values are stored in each server separately on which request has been made. Since the session values are stored in server, whenever server is restarted the session values will be lost. 
<configuration>
 <sessionstate mode="InProc" cookieless="false" timeout="10" 
    stateConnectionString="tcpip=127.0.0.1:80808" 

    sqlConnectionString="Data Source=.\SqlDataSource;User ID=userid;Password=password"/>
</configuration>
In State Server mode: This mode could store session in the web server but out of the application pool. But usually if this mode is used there will be a separate server for storing sessions, i.e., stateServer. The benefit is that when IIS restarts the session is available. It stores session in a separate Windows service. For State server session mode, we have to configure it explicitly in the web config file and start the aspnet_state service.
<configuration>
<sessionstate mode="stateserver" cookieless="false" 
   timeout="10"  stateConnectionString="tcpip=127.0.0.1:42424"  
   sqlConnectionString="Data Source=.\SqlDataSource;User ID=userid;Password=password"/> </configuration>
In SQL Server mode: Session is stored in a SQL Server database. This kind of session mode is also separate from IIS, i.e., session is available even after restarting the IIS server. This mode is highly secure and reliable but also has a disadvantage that there is overhead from serialization and deserialization of session data. This mode should be used when reliability is more important than performance.
<configuration>
    <sessionstate mode="sqlserver" cookieless="false" timeout="10" 
       stateConnectionString="tcpip=127.0.0.1:4  2424" 
       sqlConnectionString="Data Source=.\SqlDataSource;User ID=userid;Password=password"/>
</configuration>
Custom Session mode: Generally we should prefer in proc state server mode or SQL Server mode but if you need to store session data using other than these techniques then ASP.NET provides a custom session mode. This way we have to maintain everything customized even generating session ID, data store, and also security.
Following are the important attributes of session states:
Attributes  Description 
Cookieless true/false  Indicates that the session is used with or without cookie. cookieless set to true indicates sessions without cookies is used and cookieless set to false indicates sessions with cookies is used. cookieless set to false is the default set. 
timeout Indicates the session will abound if it is idle before session is abounded explicitly (the default time is 20 min).
StateConnectionStringIndicates the session state is stored on the remote computer (server). This attribute is required when session mode is StateServer
SqlConnectionStringIndicates the session state is stored in the database. This attribute is required when session mode is SqlServer
By,
Akash Roy,
CEO, JPR Infoserve,
http://jprinfoserve.com

No comments:

Post a Comment