State Management in ASP.Net

Web applications are based on stateless HTTP protocol which does not retain any information about user requests. In typical client and server communication using HTTP protocol, page is created each time the page is requested.

We can classify state management techniques as client side state management and server side state management, each of which has its own pros and cons.

Client Side State Management:


Various client side state management options in ASP.NET are Cookies, QueryStrings (URL), Hidden fields, View State and Control state (ASP.NET 2.0). 

Cookie: 

A cookie is a small piece of text stored on user's computer. Usually, information is stored as name-value pairs. Cookies are used by websites to keep track of visitors. Every time a user visits a website, cookies are retrieved from user machine and help identify the user.

Example: This example makes use of cookies to customize web page.

if (Request.Cookies["UId"] != null)
    lbMessage.text = "Mr/Mrs" + Request.Cookies["UId"].Value + ", Welcome!";
else
    lbMessage.text = "Hi, welcome!";


Client's information can be stored as given below:

Response.Cookies["UId"].Value=username;

Advantages:
  • Simplicity
Disadvantages:
  • Cookies can be disabled on user browsers
  • Cookies are transmitted for each HTTP request/response causing overhead on bandwidth
  • Inappropriate for sensitive data

Hidden fields:

Hidden fields are not rendered by the browser and used to store data at the page level. Whenever a page is submitted to server, hidden fields values are also posted to server along with other controls on the page. We can use hidden fields in ASP.NET pages using following syntax:

protected System.Web.UI.HtmlControls.HtmlInputHidden HiddenField;
 
//to assign a value to Hidden field
HiddenField.Value="This is a hidden field";
//to retrieve a value
string str=HiddenField.Value;

Advantages:
  • Simple to implement for a page specific data
  • Can store small amount of data so they take less size.
Disadvantages:
  • Inappropriate for sensitive data
  • Hidden field values can be intercepted(clearly visible) when passed over a network

View State:

View State is a built in feature in web controls to persist data between page post backs. It can be used to store state information for a single user. 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. Disable View State for all the controls for which you don't need state, to reduce performance penalty (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 ViewState
ViewState["viewstate"]  = viewstateValue;
 
//Reading items from ViewState
Response.Write(ViewState["viewstate"]);

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

Query strings:

Query strings are usually used to send information from one page to another page along with URL in clear text. We can only pass smaller amounts of data using query strings. Most browsers impose a limit of 255 characters on URL length. 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.UrlEncodeQuery strings can be used using the following syntax:

string prodId;
prodId=Request.QueryString["prodId"];
          
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 behaviour 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:


Server Side State Management maintains state information on the server. Application, Session, Cache and Database are different mechanisms for storing state on the server.

Application State:

Application State 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 does not changes frequently. 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["testData"]="testData";
Application.UnLock();

Session State:

Session State is used to store state specific information per client basis. Session data persists for the duration of user session. Session state can be configured using the <sessionState> section in the application's web.config file. 

Configuration information:

<sessionState mode = <"inproc" | "sqlserver" | "stateserver">
 cookieless = <"true" | "false">
 timeout = <positive integer indicating the session timeout in minutes>
 sqlconnectionstring = <SQL connection string that is only used in the SQLServer mode>
 server = <The server name that is only required when the mode is State Server>
 port = <The
port number that is only required when the mode is State Server>

      
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 value 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-memory) - State information is stored in memory of web server.
  • Out-of-process mode - Session state is held in a process called aspnet_state.exe that runs as a windows service.
  • Database mode - session state is maintained on a SQL Server database.
In process mode:
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.

Configuration information:
<sessionState mode="Inproc"
 sqlConnectionString="data source=server;user id=freelance;password=freelance"
 cookieless="false" timeout="20" />

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):
This mode is ideal for scalable and highly available applications. 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. We can invoke state service using services MMC snap-in or by running following net command from command line.

Net start aspnet_state

Configuration information:

<sessionState mode="StateServer"
 StateConnectionString="tcpip=127.0.0.1:42424"
 sqlConnectionString="data source=127.0.0.1;user id=freelance; password=freelance"
 cookieless="false" timeout="20"/>  

                                                         
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 process.
  • Requires serializing data.  
SQL-Backed 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:\<windows>\microsoft.net\framework\<version>. Running this utility will create a database which will manage the session state.


Configuration Information:
<sessionState mode="SQLServer"
  sqlConnectionString="data source=server;user id=freelance;password=freelance"
  cookieless="false" timeout="20" />

Advantages:
  • Supports web farm and web garden configuration
  • Session state is persisted across application domain recycles and even IIS restarts when session is maintained on different server.
Disadvantages:
  • Requires serialization of objects

Advantages of Client – Side State Management:

1. Better Scalability: With server-side state management, each client that connects to the Web server consumes memory on the Web server. If a Web site has hundreds or thousands of simultaneous users, the memory consumed by storing state management information can become a limiting factor. Pushing this burden to the clients removes that potential bottleneck.

2. Supports multiple Web servers: With client-side state management, you can distribute incoming requests across multiple Web servers with no changes to your application because the client provides all the information the Web server needs to process the request. With server-side state management, if a client switches servers in the middle of the session, the new server does not necessarily have access to the client’s state information. You can use multiple servers with server-side state management, but you need either intelligent load-balancing (to always forward requests from a client to the same server) or centralized state management (where state is stored in a central database that all Web servers access).

Advantages of Server – Side State Management:

1. Better security: Client-side state management information can be captured (either in transit or while it is stored on the client) or maliciously modified. Therefore, you should never use client-side state management to store confidential information, such as a password, authorization level, or authentication status.

2. Reduced bandwidth: If you store large amounts of state management information, sending that information back and forth to the client can increase bandwidth utilization and page load times, potentially increasing your costs and reducing scalability. The increased bandwidth usage affects mobile clients most of all, because they often have very slow connections. Instead, you should store large amounts of state management data (say, more than 1 KB) on the server.

1 comment:

  1. Nice Blog,Net Grid is the best performing grid on the market adapted for real-time applications and displaying huge data volumes. Thread protection makes it safe to use with MVVM model. Learn more on how to build high-performance applications.visit http://www.dapfor.com/en

    ReplyDelete