6.8.08

State management in ASP.NET

  • Define state management in ASP.NET

Answer - State management is implemented in order to retain information about the user requests. Web pages are stateless. Each request creates new page without retaining any previous information about the user requests. ASP.NET supports several State management techniques to maintain state information.

State management in ASP.NET can be classified into

Client-side state management & Server-side state management

  • Define each mechanism of Client-side state management and Server-side state management.

Client-side state management

This maintains information on the client's machine using Cookies, View State, and Query Strings.

Cookies.

A cookie is a small text file on the client machine either in the client's file system or memory of client browser session. Cookies are not good for sensitive data. Moreover, Cookies can be disabled on the browser. Thus, you can't rely on cookies for state management.

View State

Each page and each control on the page has View State property. This property allows automatic retention of page and controls state between each trip to server. This means control value is maintained between page postbacks. Viewstate is implemented using _VIEWSTATE, a hidden form field which gets created automatically on each page. You can't transmit data to other page using view state.

View State can be used to store state information for a single user. View State is a built in feature in web controls to persist data between page post backs. You can set View State on/off for each control using EnableViewState property. By default, EnableViewState property will be set to true. View state mechanism poses performance overhead. View state information of all the controls on the page will be submitted to server on each post back. To reduce performance penalty, disable View State for all the controls for which you don't need state. (Data grid usually doesn't need to maintain state). You can also disable View State for the entire page by adding EnableViewState=false to @page directive.

View state data is encoded as binary Base64 - encoded which add approximately 30% overhead. Care must be taken to ensure view state for a page is smaller in size. View State can be used using following syntax in an ASP.NET web page.// Add item to ViewStateViewState["myviewstate"] = myValue;//Reading items from ViewStateResponse.Write(ViewState["myviewstate"]);

Advantages:

Simple for page level data

Encrypted

Can be set at the control level

Disadvantages:

Overhead in encoding View State values.

Makes a page heavy

Querystring

Querystring can maintain limited state information. Data can be passed from one page to another with the URL but you can send limited size of data with the URL. Most browsers allow a limit of 255 characters on URL length.

Query strings are usually used to send information from one page to another page. They are passed along with URL in clear text. Now that cross page posting feature is back in asp.net 2.0, Query strings seem to be redundant. Most browsers impose a limit of 255 characters on URL length. We can only pass smaller amounts of data using query strings. Since Query strings are sent in clear text, we can also encrypt query values. Also, keep in mind that characters that are not valid in a URL must be encoded using Server.UrlEncode.

Let's assume that we have a Data Grid with a list of products, and a hyperlink in the grid that goes to a product detail page, it would be an ideal use of the Query String to include the product ID in the Query String of the link to the product details page (for example, productdetails.aspx?productid=4).

When product details page is being requested, the product information can be obtained by using the following codes:string productid;productid=Request.Params["productid"];

Advantages:

Simple to Implement

Disadvantages:

Human Readable

Client browser limit on URL length

Cross paging functionality makes it redundant

Easily modified by end user

Control State:

Control State is new mechanism in ASP.NET 2.0 which addresses some of the shortcomings of View State. Control state can be used to store critical, private information across post backs. Control state is another type of state container reserved for controls to maintain their core behavioral functionality whereas View State only contains state to maintain control's contents (UI). Control State shares same memory data structures with View State. Control State can be propagated even though the View State for the control is disabled.

For example, new control Grid View in ASP.NET 2.0 makes effective use of control state to maintain the state needed for its core behavior across post backs. Grid View is in no way affected when we disable View State for the Grid View or entire page

Server-side state management

As name implies, state information will be maintained on the server. Application, Session, Cache and Database are different mechanisms for storing state on the server.Care must be taken to conserve server resources. For a high traffic web site with large number of concurrent users, usage of sessions object for state management can create load on server causing performance degradation

Application State

The data stored in an application object can be shared by all the sessions of the application. The application object stores data in the key value pair.

Application object is used to store data which is visible across entire application and shared across multiple user sessions. Data which needs to be persisted for entire life of application should be stored in application object.

In classic ASP, application object is used to store connection strings. It's a great place to store data which changes infrequently. We should write to application variable only in application_Onstart event (global.asax) or application.lock event to avoid data conflicts. Below code sample gives idea

Application.Lock();

Application["mydata"]="mydata";

Application.UnLock();

Session State

Session state stores session-specific information and the information is visible within the session only. ASP.NET creates unique sessionId for each session of the application. SessionIDs are maintained either by an HTTP cookie or a modified URL, as set in the application's configuration settings. By default, SessionID values are stored in a cookie.

Session object is used to store state specific information per client basis. It is specific to particular user. Session data persists for the duration of user session you can store session's data on web server in different ways. Session state can be configured using the section in the application's web.config file.

Configuration information: cookieless = <"true" "false"> timeout = sqlconnectionstring= server = port =

Mode:This setting supports three options. They are InProc, SQLServer, and State Server

Cookie less:This setting takes a Boolean value of either true or false to indicate whether the Session is a cookie less one.

Timeout:This indicates the Session timeout vale in minutes. This is the duration for which a user's session is active. Note that the session timeout is a sliding value; Default session timeout value is 20 minutes

SqlConnectionString:This identifies the database connection string that names the database used for mode SQLServer.

Server:In the out-of-process mode State Server, it names the server that is running the required Windows NT service: aspnet_state.

Port:This identifies the port number that corresponds to the server setting for mode State Server. Note that a port is an unsigned integer that uniquely identifies a process running over a network.

You can disable session for a page using EnableSessionState attribute. You can set off session for entire application by setting mode=off in web.config file to reduce overhead for the entire application.Session state in ASP.NET can be configured in different ways based on various parameters including scalability, maintainability and availability

In process mode:

In process mode (in-memory)- State information is stored in memory of web server.This mode is useful for small applications which can be hosted on a single server. This model is most common and default method to store session specific information. Session data is stored in memory of local web server

Advantages:

Fastest mode

Simple configuration

Disadvantages:

Session data will be lost if the worker process or application domain recycles

Not ideal for web gardens and web farms

Out-of-process Session mode (state server mode):

session state is held in a process called aspnet_state.exe that runs as a windows service which listens on TCP port 42424 by default. You can invoke state service using services MMC snap-in or by running following net command from command line. This mode is ideal for scalable and highly available applications.

Advantages:

Supports web farm and web garden configuration

Session data is persisted across application domain recycles. This is achieved by using separate worker process for maintaining state

Disadvantages:

Out-of-process mode provides slower access compared to In processRequires serializing data

Database

Database can be used to store large state information. Database support is used in combination with cookies or session state.

ASP.NET sessions can also be stored in a SQL Server database. Storing sessions in SQL Server offers resilience that can serve sessions to a large web farm that persists across IIS restarts.SQL based Session state is configured with aspnet_regsql.exe. This utility is located in .NET Framework's installed directory C:\\microsoft.net\framework\. Running this utility will create a database which will manage the session state.

No comments: