Saturday 17 July 2010

State management in ASP.NET

Introduction


State management is the process by which you maintain state and page information over multiple requests for the same or different pages.
The web is a stateless medium – state is not maintained between client requests by default. Technologies must be utilized to provide some form of state management if this is what is required of your application, which will be the case for all but the simplest of web applications. ASP.NET provides several mechanisms to manage state in a more powerful and easier to utilize way than classic ASP. It is these mechanisms that are the subject matter for this article.

In general, Webapplications are stateless i.e. the objects wont persist its state accross request to the web application. In other words, the State or Cache Management is nothing but the way to storing the data in Client-Side and in Server-Side using pretty small memory to maintain its state.
There are two major categories of the above :


Types of State Management 

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

1. Client – Side State Management 

This stores information on the client's computer by embedding the information into a Web page, a uniform resource locator(url), or a cookie. The techniques available to store the state information at the client end are listed down below:

a. View State – Asp.Net uses View State to track the values in the Controls. You can add custom values to the view state. It is used by the Asp.net page framework to automatically save the values of the page and of each control just prior to rendering to the page. When the page is posted, one of the first tasks performed by page processing is to restore view state.

b. Control State – If you create a custom control that requires view state to work properly, you should use control state to ensure other developers don’t break your control by disabling view state.

c. Hidden fields – Like view state, hidden fields store data in an HTML form without displaying it in the user's browser. The data is available only when the form is processed.

d. Cookies – Cookies store a value in the user's browser that the browser sends with every page request to the same server. Cookies are the best way to store state data that must be available for multiple Web pages on a web site.

e. Query Strings - Query strings store values in the URL that are visible to the user. Use query strings when you want a user to be able to e-mail or instant message state data with a URL. 

2. Server – Side State Management 

a. Application State - Application State information is available to all pages, regardless of which user requests a page.

b. Session State – Session State information is available to all pages opened by a user during a single visit.

Both application state and session state information is lost when the application restarts. To persist user data between application restarts, you can store it using profile properties. 


Session State: Its nothing but defined as a period of time shared between the web application and user. Every user has individual session. Items/Objects can be placed into the Session which would only define these objects for that user. Session contains key variables which help to identify the related values. This can be thought of as a hash table. Each user would represent a different key node in the hash identifying unique values. The Session variables will be clear by the application which can clear it, as well as through the timeout property in the web config file. Usually the timeout is 20 minutes by default.
Session Variables are stored on the server, can hold any type of data including references, they are similar to global variables in a windows application and use HTTP cookies to store a key with which to locate user's session variables.
The collection of session variables is indexed by the name of the variable or by an integer index. Session variables are created by referring to the session variable by name. You do not have to declare a session variable or explicitly add it to the collection.
Lets get it cleared from following example:

Session["firstName"] = "jitendra"   //User’s first name
Session["lastName"] = "gupta"     //User’s last name
// Clear the session variable
Session["FirstName"] = null;
//Clear all Session variables
Session.Abandon(); 

InProc—Stores Session state in the same process as the ASP.NET process [aspnet_wp.exe].
StateServer—Stores Session state in a Windows NT process, which is distinct from the ASP.NET process[aspnet_state.exe].
SQLServer—Stores Session state in a SQL Server database.
Both in StateServer and SQLServer options, we need to ensure that the objects we cache are serializable as data storages are out-of-process systems. Both these options have impact on the application performance as data retrieval and saving operations take more time when compared to the InProc option. So based on our application requirement we should choose the option that best suits our requirement.

ASP.NET session state supports several different storage options for session data: 

a. InProc Stores session state in memory on the Web server. This is the default, and it offers much better performance than using the ASP.NET state service or storing state information in a database server. InProc is fine for simple applications, but robust applications that use multiple Web servers or must persist session data between application restarts should use State Server or SQLServer.

b. StateServer Stores session state in a service called the ASP.NET State Service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. ASP.NET State Service is included with any computer set up to run ASP.NET Web applications; however, the service is set up to start manually by default. Therefore, when configuring the ASP.NET State Service, you must set the startup type to Automatic.

c. SQLServer Stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. On the same hardware, the ASP.NET State Service outperforms SQLServer. However, a SQL Server database offers more robust data integrity and reporting capabilities.

d. Custom Enables you to specify a custom storage provider. You also need to implement the custom storage provider.

e. Off Disables session state. You should disable session state if you are not using it to improve performance. 



Application State: ASP.NET allows you to save values using application state, a global storage mechanism that is accessible from all pages in the Web application. Application state is stored in the Application key/value dictionary. Once you add your application-specific information to application state, the server manages it, and it is never exposed to the client. Application state is a great place to store information that is not user-specific. By storing it in the application state, all pages can access data from a single location in memory, rather than keeping separate copies of the data. Data stored in the Application object is not permanent and is lost any time the application is restarted.

ASP.NET provides three events that enable you to initialize Application variables (free resources when the application shuts down) and respond to Application errors:

a. Application_Start: Raised when the application starts. This is the perfect place to initialize Application variables.

b. Application_End: Raised when an application shuts down. Use this to free application resources and perform logging.

c. Application_Error: Raised when an unhandled error occurs. Use this to perform error logging. 


Client-Side State Management
Cookies
Cookie is a very familiar term in web development environment. Cookie is a client-side storage that is sent to the server for each request and also received as response back from the server. Because of its size limitation (4096 bytes) it should be used for storing small amount of data. Expiration policies can be set for cookies to invalidate the items after a certain period of time. The following example shows how Cookie can be used in an ASP.NET application:

if (this.Request.Cookies["MY_NAME"] == null) {
    this.Response.Cookies.Add(new HttpCookie("MY_NAME",
                                       "Jintendra Gupta"));
}
else
{
    this.Response.Write(this.Request.Cookies["MY_NAME"].Value);
}

ViewState
ASP.NET ViewState is a new concept. Here the data related to the pages and controls are stored in ViewState which retains the values across multiple requests to the server. If you remember correctly, in VB-ASP applications we used to store data across multiple requests using hidden fields. ViewState is actually implemented internally as hidden fields in ASP.NET but here the data is hashed to improve security as against hidden fields. To see how ViewState is implemented, you can view the source of the page in which ViewState is used in the Internet browser. ViewState should not be used to store large amounts of data as it is passed to the server for each request
protected void Page_Load(object sender, EventArgs e) {
    if (this.ViewState["NAME"] == null)
    {
        this.ViewState["NAME"] = "Yashwant Patel";
    }
        //txtName is a TextBox control
    this.txtName.Text = this.ViewState["NAME"].ToString();
}

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE” value="/wEPDwUAAAHSJWSKJSKLlAQ8PFgIeBFRleHQFEzQvNS8yMDA2IDE6Mzc6MTEgUE1kZGROWHn/rt75XF/pMGnqjqHlH66cyt==" />


Hidden fields
Hidden fields are very popular among VB-ASP web developers. Hidden field is similar to any other control in a page but the visible state of this control is always false. Like ViewState we should not use it for storing large amounts of data. 
Note:Similarly hidden frames can be used to cache data in the client side. But please note that hidden frames are not supported by all Internet browsers.
<!--In ASP.NET-->
<asp:HiddenField ID="myHiddenField" Value="Yashwant Patel"  runat="server" />                                    
<!--In HTML-->
<input id="myHiddenField" type="hidden" value="Yashwant Patel" />


Query Strings
Query strings provide a simple but limited way of maintaining some state information.You can easily pass information from one page to another, But most browsers and client devices impose a 255-character limit on the length of the URL. In addition, the query values are exposed to the Internet via the URL so in some cases security may be an issue. 
http://www.sunilgurjar.blogspot.com/Default.aspx?Page_id=4
Example
string Page_id;
Page_id=Request.Params["Page_id"];


Limitations for Query Strings:
1. Some Browsers and client devices impose a 2083 – character limit on the length of the URL.
2. You must submit the page using an HTTP GET command in order for query string values to be available during page processing. Therefore, you shouldn’t add query strings to button targets in forms.
3. You must manually add query string values to every hyperlink that the user might click.
Example: 

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Powered by Blogger