Wednesday, 30 November 2011

State Management in ASP.Net

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 :
1.      Server-Side State Management
2.      Client-Side State Management

Server-Side State Management
 
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”] = “Saurav”   //User’s first name
Session[“lastName”] = “Arora”     //User’s last name
// Clear the session variable
Session[“FirstName”] = null;
//Clear all Session variables
Session.Abandon();  

ASP.NET application object
ASP.NET provides an object called Application object to store data that is accessible to all user requests. The life span of this object is tied to the application and it is re-created every time the application starts. Unlike ASP.NETSession object this object is accessible to all user requests. Since this storage is created and maintained in an application domain space, this should not be used for data storage in a web farm scenario. This option is very useful to store data like the application metadata (CONFIG files data) that can be loaded to the Application object during application start up and can be used during the life of the application without reloading it every time for each user request. But if there is a requirement to invalidate the cached data whenever there is any change to the CONFIG files while the application is running, this option should not be used as it doesn't provide any feature to expire the cached data. So in this case other options like the ASP.NET Cache object should be used, which is explained below.

Types of Cache –Dependencies
When anyone add an item to cache, he/she can define the dependency relationships that can force that item to be removed from the cache under specific activities of dependencies.
For example: If the cache is dependent on file and when the file data changes you want the cache object to be updated.
Following are the difference dependencies:

File Dependency :
Allows invalidating a specific cache item when a disk based file or files change.
object errorData;
 //Load errorData from errors.xml
 CacheDependency fileDependency =
     new CacheDependency(Server.MapPath("errors.xml"));
 Cache.Insert("ERROR_INFO", errorData, fileDependency);

Time based expiration :
Allows to invalidate a specific cache item depending on predefined time.
//Absolute Expiration
Cache.Insert("EMP_NAME", "Shubhabrata", null,
             DateTime.Now.AddDays(1), Cache.NoSlidingExpiration);
//Sliding Expiration
Cache.Insert("EMP_NAME", "Shubhabrata", null,
             Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(60));

Key dependency :
Allows to invalidate a specific cache item depending when another cache item changes.
string[] relatedKeys = new string[1];
relatedKeys[0] = "EMP_NUM";
CacheDependency keyDependency = new CacheDependency(null, relatedKeys);
Cache["EMP_NUM"] = 5435;
Cache.Insert("EMP_NAME", "Shubhabrata", keyDependency);
Cache.Insert("EMP_ADDR", "Bhubaneswar", keyDependency);
Cache.Insert("EMP_SAL", "5555USD", keyDependency);

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["NAME"] == null) {
    this.Response.Cookies.Add(new HttpCookie("NAME",
                                       "Shubhabrata Mohanty"));
}
else
{
    this.Response.Write(this.Request.Cookies["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"] = "Shuby";
    }
        //txtName is a TextBox control
    this.txtName.Text = this.ViewState["NAME"].ToString();
}

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="Shubhy"  runat="server" />                                    
<!--In HTML-->
<input id="myHiddenField" type="hidden" value="Shubhy" />

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.CodeDigest.com/?authorid=4
Example
string authorid;
authorid=Request.Params[“authorid”];

You can only use HTTP-Get method to post the web page, or you will never get the value from query strings.




No comments:

Post a Comment