Sunday, November 14, 2010

ASP.net - State Management in ASP.net

Web Pages developed in ASP.Net are HTTP based and HTTP protocol is a stateless protocol. It means that web server does not have any idea about the requests from where they coming i.e from same client or new clients. On each request web pages are created and destroyed.

ASP.Net technology offers following state management techniques.

Client side State Management
  • Cookies
  • Hidden Fields
  • View State
  • Query String
Server side State Management
  • Session State
  • Application State
These state management techniques can be understood and by following simple examples and illustrations of the each techniques.


Client Side State Management


Cookie

A cookie is a small amount of data which is either stored at client side in text file or in memory of the client browser session. Cookies are always sent with the request to the web server and information can be retrieved from the cookies at the web server. In ASP.Net, HttpRequest object contains cookies collection which is nothing but list of HttpCookie objects. Cookies are generally used for tracking the user/request in ASP.Net for example, ASP.Net internally uses cookie to store session identifier to know whether request is coming from same client or not. We can also store some information like user identifier (UserName/Nick Name etc) in the cookies and retrieve them when any request is made to the web server as described in following example. It should be noted that cookies are generally used for storing only small amount of data(i.e 1-10 KB).

Code Sample


 //Storing value in cookie
            HttpCookie CookieObj = new HttpCookie("Programmer", "KishoR NaiK"); // Create a new Cookie and give the cookie value
            Request.Cookies.Add(CookieObj); // Add a cookie to the cookie collection

            //Retrieving value in cookie 
            if (Request.Cookies.Count > 0 && Request.Cookies["Programmer"].Value != String.Empty)
            {
                Response.Write("Welcome " + Request.Cookies["Programmer"].Value);
            }
            else
            {
                Response.Write("Welcome Guest");  
            }

Cookies can be permanent in nature or temporary. ASP.Net internally stores temporary cookie at the client side for storing session identifier. By default cookies are temporary and permanent cookie can be placed by setting "Expires" property of the cookie object.

Advantage
State is stored at client side. It can be shared across multiple sessions in case of permanent cookie.

Disadvantage
Depends on client browser setting.It can not be used for large amount of data as it is sent back and forth in each page request.

Recommended Use
When small amount of data less than 4 KB needs to stored at client side. Generally used for authentication in ASP.Net. It can be used in case site retains user preferences.



Hidden Fields

A Hidden control is the control which does not render anything on the web page at client browser but can be used to store some information on the web page which can be used on the page.

HTML input control offers hidden type of control by specifying type as "hidden". Hidden control behaves like a normal control except that it is not rendered on the page. Its properties can be specified in a similar manner as you specify properties for other controls. This control will be posted to server in HttpControl collection whenever web form/page is posted to server. Any page specific information can be stored in the hidden field by specifying value property of the control.
ASP.Net provides HtmlInputControl that offers hidden field functionality.

Code Sample

 //Declaring a hidden variable
            System.Web.UI.HtmlControls.HtmlInputHidden HiddenValue =new HtmlInputHidden();

            //Populating hidden variable
            HiddenValue.Value = "I am a .Net Programmer"; 

           // Retrieving value stored in hidden field.
            Response.Write(HiddenValue.Value);     

Note:Do not store critical information in hidden fields because HACKER can retrive a value from hidden value.

Advantage
It can be very useful when additional information needs to sent to client side for validations.

Disadvantage
All the information is stored at client side and anyone can view it using source of the web page.

Recommended Use
It can be used very carefully as all the information is at client side. Generally it is used to pass data which can be used to validate user entries on the page. Or it can b used to contain values specific to user.


View State

ASP.Net technology provides View State feature to the web forms. View State is used to remember controls state when page is posted back to server. ASP.Net stores view state on client site in hidden field __ViewState in encrypted form. When page is created on web sever this hidden control is populate with state of the controls and when page is posted back to server this information is retrieved and assigned to controls. You can look at this field by looking at the source of the page (i.e by right clicking on page and selecting view source option.)
You do not need to worry about this as this is automatically handled by ASP.Net. You can enable and disable view state behaviour of page and its control by specifying 'enableViewState' property to true and false. You can also store custom information in the view state as described in following code sample. This information can be used in round trips to the web server.

Code Sample

// To store Information in View State 
            ViewState.Add("Programmer", "Kishor Naik");

            //Retrieving View state value
            Response.Write(ViewState["Programmer"].ToString());  

Advantage
ASP.Net in built state management technique. Can be used to store small amount of information in encrypted form at client side.

Disadvantage
It is sent back and forth in each page request and post back so their may be performance hit if large amount of data is stored in that. State is retained only when post request is made to page.

Recommended Use
When small amount of data needs to be stored on the page which is needed when post request is made to a page.


Query String

Query string is the limited way to pass information to the web server while navigating from one page to another page. This information is passed in url of the request.

Code Sample

           Default.aspx

// Pass a value from one page to another page
            String ProgrammerName="Kishor Naik";
            Response.Redirect("Default2.aspx?Programmer=" + ProgrammerName, false);

           
NOTE - Value should be encrypted form.

           Default2.aspx
Response.Write(Request.QueryString["Programmer"].ToString());  

But remember that many browsers impose a limit of 255 characters in query strings. You need to use HTTP-Get method to post a page to server otherwise query string values will not be available.

Advantage
It can be used to pass small amount of data b/w pages.

Disadvantage
Data passed in the url so security may be issue and it should not be used to pass any sensitive data.

Recommended Use
It can be used to pass any general information b/ pages of application.



Server Side State Management

Session State

Session state is used to store and retrieve information about the user as user navigates from one page to another page in ASP.Net web application. Session state is maintained per user basis in ASP.Net runtime. It can be of two types in-memory and out of memory. In most of the cases small web applications in-memory session state is used. Out of process session state management technique is used for the high traffic web applications or large applications. It can be configured  with some configuration settings in web.conig file to store state information.

Code Sample

//Storing informaton in session state 
            Session["Programmer"] = "Kishor Naik";

            //Retrieving information from session state
            Response.Write(Session["Programmer"].ToString());

Session state is being maintained automatically by ASP.Net. A new session is started when a new user sents  first request to the server. At that time session state is created and user can use it to store information and retrieve it while navigating to different web pages in ASP.Net web application.

ASP.Net maintains session information using the session identifier which is being transacted b/w user machine and web server on each and every request either using cookies or querystring (if cookieless session is used in web application).


Advantage
It can be shared with different machine and different processors. It can use persistent medium like SQL server or different processes.

Disadvantage
Storing state in persistent medium can be hard to maintain. Uses Cookies or URL to manage state.

Recommended Use
Generally used in ASP.Net application to store state specific information this can be shared across page for a single client.


Application State

Application State is used to store information which is shared among users of the ASP.Net web application. Application state is stored in the memory of the windows process which is processing user requests on the web server. Application state is useful in storing small amount of often-used data. If application state is used for such data instead of frequent trips to database, then it increases the response time/performance of the web application.

In ASP.Net, application state is an instance of HttpApplicationState class and it exposes key-value pairs to store information. Its instance is automatically created when a first request is made to web application by any user and same state object is being shared across all subsequent users.

Application state can be used in similar manner as session state but it should be noted that many user might be accessing application state simultaneously so any call to application state object needs to be thread safe. This can be easily achieved in ASP.Net by using lock keyword on the statements which are accessing application state object.

This lock keyword places a mutually exclusive lock on the statements and only allows a single thread to access the application state at a time.

Code Sample


 //Stroing information in application state
            lock (this)
            {
                Application["Programmer"] = "Kishor Naik"; 
            }

            //Retrieving value from application state
            lock (this)
            {
                Response.Write(Application["Programmer"].ToString());  
            }

Advantage
It can be shared across all the clients.

Disadvantage
It can not be shared b/w machines and processors. Its use should be limited as it can reduce scalability of the application.

Recommended Use
When information needs to shared with all clients. I.e. number of active users to application.


Download
Download Source Code

No comments:

Post a Comment