State Management in ASP.Net

By Luke Alderton at 29 Jul 2010, 19:26 PM
  • State management is the process of maintaining state and web page information over multiple page requests.

    There are two types of state management.

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

    Client Side State Management

    In ASP.Net there are five ways to manage the client side state. By using these methods the information is stored on the client’s computer. For these five methods no server resources are required. The five methods are,

    • Cookies
    • Query String
    • Hidden Fields
    • View State
    • Control State

    Cookies

    A Cookie is a mechanism that allows the server to store its own information about a user on the user’s own computer. It’s a user log. The cookie contains information that the web application can read whenever the user visits the website.

    Types of Cookies

    Session Cookies

    A cookie that is erased when the user closes the web browser.

    Persistent Cookies

    A cookie that is stored on a user’s hard drive until it expires or until the user deletes the cookie.

    Example

    Creating Cookies

    A cookie with a single key / value pair,

    1. Response.Cookies["TestCookie"].Value = " TestCookie Value";
    2. Response.Cookies["TestCookie "].Expires = DateTime.Now.AddDays(1);

    A cookie with a multiple key / value pair,

    1. Response.Cookies["User"]["UserID"] = "Admin";
    2. Response.Cookies["User"]["UserName"] = "XXX";
    3. Response.Cookies["User"]["Status"] = "New";

    Reading a Cookie

    Before reading the cookie, make sure that it exists

    1. string TestCookie;
    2. if (Request.Cookies["TestCookie "] != null)
    3. TestCookie = Request.Cookies["TestCookie "].Value;

    Deleting a Cookie

    For deleting a cookie the expiration time is set in the past.

    1. if (Request.Cookies["MyCookieName"] != null)
    2. Response.Cookies["MyCookieName"].Expires = DateTime.Now.AddDays(-1);

    Query String

    A Query String stores values at the end of the URL. This information is visible to the user. We can also encrypt and decrypt the query string information for security. This is an easy way to pass the information form one page to another page. The query string starts with the question mark (?) character. We can pass multiple values, each value can be separated by an ampersand (&).

    Example

    http://www.test.com?ID=12&Mode=Update

    In this example there are two items available in the query string, one is Id and the other is Mode.

    Hidden Fields

    We can add HTML-standard hidden fields in the web page. Asp.Net allows storing information in the hidden fields. The “HiddenField” control, stores the single value in the controls “Value” property. The HiddenField control must be explicitly added to the web page. The users can view and modify the HiddenField data through code behind. The HiddenField control will not be visible in the browser, but if we look at the page source, we can see the HiddenField control in the plain HTML.

    Example

    Control in design page,

    We can access value like this

    string Val; Val= HField1.Value; 

    View State

    The view state provides a dictionary object for retaining the values between multiple requests of the same web page. The view state can support the structured data, this is an advantage compared to other client side state management methods. View state cannot keep data for other pages. View state is the default method used by the page to preserve page and control properties between each round trip.

    Example

    Use the key/value pair to save an object in to view state.

    ViewState["User"] = "XXX"; 

    Retrieving the view state value:

    string User; User= (string) ViewState["User"]; 

    Control State

    The ASP.NET page framework provides the ControlState property as way to store custom control data between server trips. Control state cannot be turned off, but we can turn off the view state. By using this, control state provides a more reliable way to store control-state data. This is an advantage compared to view state, because the view state can be turned off at the page level.

    Server Side State Management

    ASP.Net provides the following options to support the server side state management:

    • Application State
    • Session State
    • Profile properties
    • Database support

    Application State

    In ASP.Net we can save values using the application state. This is a global storage mechanism, so it is accessible from all pages of the web application. It is stored in a key / value dictionary that is created during each request to a specific URL. We can initialize application variables using three events in ASP.Net,

    Application_Start:

    This event is raised when the application starts. We can initialize application variables in this event.

    Application_End

    This event is raised when the application shuts down. We can free up the application resources and also perform the logging here.

    Application_Error:

    This event is raised when an unhandled exception occurs. We can log the exception details here.

    Session State

    Session State is another storage mechanism of ASP.Net to preserve values, which are accessible from all pages requested over a span of single web browser session. Session state can be managed using three different storage options,

    • InProc
    • StateServer
    • SQLServer

    InProc

    InProc creates session state objects in the memory of the web server. This is the default storage option, and it offers better performance compared to the other two storage options. This is suitable only for simple applications, so complex applications should use the other two storage options.

    StateServer

    State Server stores session state objects in a service called the ASP.NET State Service. This storage option ensures that the session state is preserved when the Web application is restarted. It also makes the session state available on multiple Web servers in a Web farm.

    SQLServer

    This method uses a SQL Server database to manage session state objects. This storage option ensures the session state is preserved when the web application is restarted. It also makes the session state available on multiple web servers in a web farm. SQL Server offers more robust data integrity and reporting capabilities.

    Profile Properties

    ASP.NET provides a feature called profile properties, which allows you to store user-specific data. This is similar to session state, but the profile data is not lost when a user's session expires. Using profiles we can easily manage user information. We don't need to maintain our own database for that. Profiles use a strongly typed API to avail the user information so that we can access the information from anywhere in the application. To use profile properties, we must configure a profile provider.

    Database Support

    Database support helps to maintain the long term state of the website or preserves the state of the website even if the server is restarted.

    The database support approach enables the user to

    • Uniquely identify the requests.
    • Maintain the state of the website using unique IDs and the information is accessed and updated using the unique ID.

    Advantages of using a database include

    Security

    User authenticates to the site using a username and password. The site queries the database to verify the credentials of the user. If the username and password are valid then the website creates a valid cookie, which contains the unique id for the user logged in and then the site grants access permissions to the user.

    Storage Capacity

    We can store large amounts of information in the database.

    Data Persistence

    The information stored in the database is not subject to the availability of the web browser.

    Robustness and Data Integrity

    A database includes more facilities for maintaining data; the facilities are referential integrity, triggers and so on.

    Personalization

    With security information in place, the site is able to differentiate each user in the web site by reading the cookie on the client computer.

    Accessibility

    The data in the database is accessible to a wide variety of information-processing tools.


    Comments

     

    Post a comment

    Please correct the following: