Mock tests, Interview questions, Tutorials and Tech news
 
 
Home > Programming / tutorials > State Management in ASP.NET

State Management in ASP.NET

Introduction

For any HTTP based protocol it is true that Web Forms are stateless and for each new request to the web server web pages are destroyed and recreated. As a result we do not get page information beyond the life cycle of a single page. State is the ability of a web application to retain user information and therefore state management becomes an important issue in developing web application.

Objectives

The main objective of this tutorial is to show how the state is managed in ASP.NET Web application. Through this tutorial we have tried to cover:
• State Management and different types of available options in ASP.NET
• Use of Session, Application and Cache variables to manage server state
• Use of Cookies, QueryString, Hidden Field and ViewState to manage client state

State management and its different options

ASP.NET provides state management which saves information within the round trip of page between the server and user’s machine and as a result the information entered by the user can be reused. Please have a look on Figure-1 which clearly shows the difference between state management and without state management.

.Net Tutorial

Figure-1: Difference between ‘Without State Management’ and ‘With State Management’

If state is maintained between pages the information entered originally by an user can be reused in other pages. As shown in Figure-1, user enters his name in Login.aspx page and then the information is sent to the web server so that in the Welcome.aspx page the system can show the same piece of information. But without state management it is not possible.

ASP.NET provides two types of state management, so that information can be maintained between server roundtrips. The types are:

• Server-Side
• Client-Side

User can store state information by using server resources in Server-side management. These options provide higher security than Client-side.

Client-Side state management is simple and has minimal security and does not use server resources to store state information.

Different options are available for both Server -side and Client-side state management. First we discuss on the available options for Server-side state management.

1.Application State:

Application state is a key value dictionary structure that is created during each request to the web pages in a web server. ASP.NET provide instance of HttpApplicationState class for each web application to store the application state.
User can use the Application object to share information among all users of a particular Web application. The Application object is not global to the machine. It is global to HttpApplicaton.

User should prevent the other users or applications to update the Application variables when he/she is modifying it. ASP.NET provides two methods Application.Lock() and Application.UnLock() which can be used to prevent concurrent multiple access of the application variable.

Here we provide a small example about the use of application variables:

Application.Lock(); //Locking the Application variables
Application[“TotalMember”]=int.parse(Application[“TotalMember”].ToString())+1; //Modifying it
Application.UnLock(); //Unlocking the variables

//Retrieving Application variable’s value
LabelCount.Text=”You are member number:“ +Application[“TotalMember “].ToString();

2.Session State with asp.net

In Session state, information is available only to a user of a particular session of a web application. HTTPSessionState class in ASP.NET provides session state. Session state is limited to the current browser session. For example if many users are using a web application then every user will get different session state. This session state is available until the user leaves the application.

Like application state session state is also structured as a key value dictionary structure and it is used to store session specific information which is useful between request for pages and round trip to the web server.ASP.NET provides the session variables that are needed to maintain session state. Generally short lived, sensitive data important for a specific session is stored in session state.

We can identify each active web application session by using a 120 bit Session ID which is formed of ASCII characters and allowed in the URLs.

If a user has not requested a page for more than 20 minutes by default session time out occurs. So if the same user returns back after 20 minutes , he/she will be considered as new user by the web application. But we can modify the session duration in the Web Configuration file. The following is the code in Web.Config file that sets the session duration 30 minutes:

In below we have just written two lines to add and retrieve values from session variables:

Session[“PersonName”]=”Scott”; //Storing name in session variable

Label1.Text=”Welcome Mr.”+ Session[“PersonName”].ToString(); //Retrieving the data

3. The Cache object in asp.net

The Cache object can be used to store information that we can also be stored in application variables. But for each Web Application ASP.NET creates a single Cache object and the items stored in the Cache object cannot be used by other web applications running on the same web server. Thus rather than recreating the value each time, a single cached value can be accessed by any page in the web application.

The Cache object uses key-value pairs to store and retrieve objects. Like dictionary we can add item in a cache object. Here a simple example is shown:

Cache[“PersonName”]=”Scott” ; // Add item in Cache object

Label1.Text=”Welcome Mr.”+ Cache[“PersonName”].ToString(); // Retrieve information from Cache

Like application object Cache object provides automatic lock management on items that are stored in Cache object. As a result users can not modify Cache objects concurrently.

Cache object is made to ensure that the web application does not use server memory much. As a result the Cache object automatically removes the least used items when there is a shortage of server’s memory. Users can set priority on Cache items. So items with higher priority are less likely to be removed from the Cache. The detail on Cache object is out of scope of this tutorial.

Client side state management

Client side state management also has different options to store sate or information. The options are discussed below:

1.Cookies

A cookie is a text file that store small amount of information. The text file is stored on the file system of the client computer or in the memory of client browser session. Generally a cookie contains page specific information and also the information of the domain that issued the cookie.

We can classify cookies in two types:
a.Temporary
b.Persistent

Temporary cookies (non-persistent) exist only in the memory of a browser and as a result information added in temporary cookies are lost when the browser is shut down.

Persistent cookies have a defined expiration period and these type of cookies are stored in user’s hard disk. Users can delete the cookies before the cookie expires. So there is no assurance on the life span of persistent cookies created in user’s machine.

Users should take care of the following things to store information in cookies:

• Cookies can be stolen and faked. So find out different option before storing secured information in cookies.
• Users can not store information more than 4KB in a cookie. So cookie has size restriction.
• Cookies cannot be trusted and users need to cross validate the data retrieved from a cookie.

2. Query Strings

Through query string navigation specific data can be passed and this information is appended to the end of a URL. A typical example might look like the following:

http://abc.com/ItemList.aspx?category=watch&type=ladies

Above in the URL path, the query string starts with the question mark (?) and contains two attribute-value pairs: category and type. Information can be retried from the query string like the following:

Label1.Text=”Items of category ”+Request.QueryString[“category”].ToString()+” are displayed”;

But please remember that query string is the most hackable element on a web site. Users can play with it by changing values and may enter in the restricted pages. A good idea is to return Response.StatusCode=404 when someone changes a URL to an unreasonable value.

3.Hidden Fields

Hidden input fields are sent back as name-value pairs in a Form POST exactly like any other control , except they are not rendered. They are like hidden text boxes. Figure-2 shows a Hidden Field control with the available properties in Visual Studio:

.Net Tutorial

Figure-2: Hidden Field and its Properties

When this control is drag and dropped in the test page the following line is also added in the source section.

<asp:HiddenField ID=”HiddenField1″ runat=”server” />

Now add a string value in this hidden field as shown in Figure-3:

.Net Tutorial

Figure-3: Add a string value in the Hidden Field

When we run the page we will find the value is added in the HTML code like Figure-4:

.Net Tutorial

Figure-4: HTML code changed for the Hidden Field

4. View State

Web forms provide the ViewState property as a built-in structure for automatically retaining values between multiple requests for same page. ViewState exposes itself as a collection of key/value pairs but renders itself as a hidden field with the name “__VIEWSTATE “ (Shown in Figure-5)

Figure-5:  ViewState and its value

Figure-5: ViewState and its value

View state can store both simple and complex type objects. We can simply add values in ViewState like the following:

ViewState["Name"] = “Scott”;

Note that ViewState value uses only valid ASCII characters to represent all its contents. It is big and appears to be opaque. Viewstate is not acceptable for any kind of sensitive data.

Conclusion

ASP.NET provides lots of functions and utilities (which we discussed in our tutorial above) to store page state in an efficient and effective manner. Choosing among the options will depend on the web application but we should think about the following points before making the choice:
• Amount of information we need to store
• Sensitivity of the information
• Performance expectation from the pages

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Mixx
  • Google Bookmarks
  • IndianPad
  • Reddit
Categories: Programming / tutorials Tags: ,
  1. meena
    February 22nd, 2011 at 13:31 | #1

    this is too good to get knowledge in brief

  1. January 4th, 2010 at 16:03 | #1
  2. January 11th, 2010 at 12:59 | #2
Get Adobe Flash playerPlugin by wpburn.com wordpress themes