Monday, 6 August 2012

State Manangement


HTTP Protocol and the Need for State Management Techniques

Hyper Text Transfer Protocol (HTTP) is a communication protocol which is implemented in the "World Wide Web(WWW)". It is a request/response style protocol. Clients (browsers, spider, etc) will request to a server (web server) and the server responds to these requests. HTTP uses TCP protocol for communication. It connects to a specific port (default is 80) to the server and communicates via that port. Once the response is received completely, client programs will be disconnected from the server. For each request, client programs have to acquire a connection with servers and do all the request cycles again.
ASP.NET files are just text files which will be placed in the server and served upon the request. When a request comes for a page, the server will locate the requested file and ask the ASP.NET engine to serve the request. The ASP.NET engine will process the server tags and generate HTML for it and return back to the client. HTTP is a stateless protocol and the server will abandon the connection once the request is served.
Since HTTP is stateless, managing state in web applications is challenging. State management techniques are used to maintain user state throughout the application. Managing state in a stand-alone application is trivial as they don't have a request/response nature. Information you want to maintain over the lifetime of a web applications depends on your context. It can be from simple numbers to very complex objects.
Understanding the state management techniques play a major role in creating efficient web applications. ASP.NET is very rich in state management techniques. The following are the commonly used state management techniques.
  • QueryString
  • Cookies
  • Cache
  • ViewState
  • Session state
  • Application state
  • Static variables
  • Profiles

Client side State management Options:ASP.NET provides various client side state management options like Cookies, QueryStrings (URL), Hidden fields, View State and Control state (ASP.NET 2.0). Let's discuss each of client side state management options.
Bandwidth should be considered while implementing client side state management options because they involve in each roundtrip to server. Example: Cookies are exchanged between client and server for each page request.

View State

The ViewState property provides a dictionary object for retaining values between multiple requests for the same page. This is the default method that the page uses to preserve page and control property values between round trips.
When the page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field, or multiple hidden fields if the amount of data stored in the ViewState property exceeds the specified value in the MaxPageStateFieldLength property. When the page is posted back to the server, the page parses the view-state string at page initialization and restores property information in the page.
You can store values in view state as well. For more information on using View State, see ASP.NET View State Overview. For recommendations about when you should use view state, see ASP.NET State Management Recommendations.
-----------------------------------------------------------------------------------------------------------------------------

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 addingEnableViewState=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["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

Control State

Sometimes you need to store control-state data in order for a control to work properly. For example, if you have written a custom control that has different tabs that show different information, in order for that control to work as expected, the control needs to know which tab is selected between round trips. The ViewState property can be used for this purpose, but view state can be turned off at a page level by developers, effectively breaking your control. To solve this, the ASP.NET page framework exposes a feature in ASP.NET called control state.
The ControlState property allows you to persist property information that is specific to a control and cannot be turned off like the ViewState property.

Hidden Fields

ASP.NET allows you to store information in a HiddenField control, which renders as a standard HTML hidden field. A hidden field does not render visibly in the browser, but you can set its properties just as you can with a standard control. When a page is submitted to the server, the content of a hidden field is sent in the HTTP form collection along with the values of other controls. A hidden field acts as a repository for any page-specific information that you want to store directly in the page.


A HiddenField control stores a single variable in its Value property and must be explicitly added to the page. 
In order for hidden-field values to be available during page processing, you must submit the page using an HTTP POST command. If you use hidden fields and a page is processed in response to a link or an HTTP GET command, the hidden fields will not be available. For usage recommendations, see ASP.NET State Management Recommendations.
-------------------------------------------------------------------------------------------------------------------------------

Hidden fields are used to store data at the page level. As its name says, these fields are not rendered by the browser. It's just like a standard control for which you can set its properties. Whenever a page is submitted to server, hidden fields values are also posted to server along with other controls on the page. Now that all the asp.net web controls have built in state management in the form of view state and new feature in asp.net 2.0 control state, hidden fields functionality seems to be redundant. We can still use it to store insignificant data. We can use hidden fields in ASP.NET pages using following syntax
protected System.Web.UI.HtmlControls.HtmlInputHidden Hidden1;

//to assign a value to Hidden field
Hidden1.Value="Create hidden fields";
//to retrieve a value
string str=Hidden1.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

Cookies

A cookie is a small amount of data that is stored either in a text file on the client file system or in-memory in the client browser session. It contains site-specific information that the server sends to the client along with page output. Cookies can be temporary (with specific expiration times and dates) or persistent.
You can use cookies to store information about a particular client, session, or application. The cookies are saved on the client device, and when the browser requests a page, the client sends the information in the cookie along with the request information. The server can read the cookie and extract its value. A typical use is to store a token (perhaps encrypted) indicating that the user has already been authenticated in your application.




Note: The location where the cookie is stored is completly controlled by the browser. Sometimes it may keep the cookie in its memory instead of creating a file.
Creating and using a cookie is trivial in ASP.NET. The HttpCookie class is a key/value collection which allows storing string values. The following code shows how to create a cookie and send it to the client. Cookies are added usingResponse property and retrieved using Request.

Some Useful Properties you Must Know Before Using Cookies

Property nameDescription
DomainSpecifies which domain is associated with this cookie. Default is the current domain. See security constraints later in this article
ExpiresA DateTime value specifies the expiry time of the cookie
HttpOnlyCookies can be accessed using java script. Setting this property prevents cookies being accessed from java script
SecureSet this if cookies are transmitted over SSL
NameCookie name
ValueCookie value (string)

Multi-valued Cookies

RFC states that a browser should not store more than 20 cookies from a domain. Multi-Valued cookie is very handy when you have more items to keep in cookie. To create a multi-valued cookie, you instantiate the HttpCookieinstance and set it's values. Consider the following code
  HttpCookie cookie = new HttpCookie("user");
  cookie["name"] = "Foo";
  cookie["age"] = "22";
  cookie.Expires = DateTime.Now.AddDays(1);
  Response.Cookies.Add(cookie);
Here is how you read it
  HttpCookie cookie = Request.Cookies["user"];
  // for safety, always check for NULL. If cookie doesn't exist, it will be NULL
  if (cookie != null) {
      string name = cookie["name"];
      string age = cookie["age"];
  }
  else
     // Cookie not exist

Pros and Cons

A cookie is a very handy and easily usable state management technique. It is useful when you want to keep small information that is needed for long periods of time. The processing overhead of cookies is much less compared to sessions. However, it has the following disadvantages:
  • Cookies have a size limitation of 4KB. Storing huge information is not possible.
  • Cookies can be easily tampered as they are kept in the client's machine. So additional security checking has to be done when using them.
  • The user can disable cookies.
  • ---------------------------------------------------------------------------------------------------------------------------------------------------
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. 

Let's see an example which makes use of cookies to customize web page.

if (Request.Cookies["UserId"] != null)
    lbMessage.text = "Dear" + Request.Cookies["UserId"].Value + ", Welcome to our website!";else    lbMessage.text = "Guest,welcome to our website!";
If you want to store client's information use the below code
Response.Cookies["UserId"].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





Query Strings

A query string is information that is appended to the end of a page URL. A typical query string might look like the following example:
http://www.contoso.com/listwidgets.aspx?category=basic&price=100
In the URL path above, the query string starts with a question mark (?) and includes two attribute/value pairs, one called "category" and the other called "price."
Query strings provide a simple but limited way to maintain state information. For example, they are an easy way to pass information from one page to another, such as passing a product number from one page to another page where it will be processed. However, some browsers and client devices impose a 2083-character limit on the length of the URL


This is the most simple and efficient way of maintaining information across requests. The information you want to maintain will be sent along with the URL.

 www.somewebsite.com/search.aspx?query=foo


The URL part which comes after the ? symbol is called a QueryString. QueryString has two parts, a key and a value. In the above example, query is the key and foo is its value. You can send multiple values through querystring, separated by the & symbol. The following code shows sending multiple values to the foo.aspx page.

 Response.Redirect("foo.aspx?id=1&name=foo");
The foo.aspx page will get the values like in the following table.

KeyValue
id1
namefoo

The following code shows reading the QueryString values in foo.aspx
 string id = Request.QueryString["id"];
 string name = Request.QueryString["name"];
Request.QueryString has two overloaded indexers. One accepts the key name and another a zero-based index. The latter is useful when you don't know the query string names. If you try to get a value which is not in the QueryString collection, you will get a NULL reference.


Pros and Cons



Query string is lightweight and will not consume any server resources. It is very easy to use and it is the most efficient state management technique. However, it has many disadvantages.
  • You can pass information only as a string. If you need to pass objects in any case through QueryString, methods explained in this excellent article [^] will work. But it involves more effort.
  • URL length has limitations. So you can't send much information through URL.
  • Information passed is clearly visible to everyone and can be easily altered.
  • --------------------------------------------------------------------------------------------------------------------------------------------------
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


ASP.NET offers you a variety of ways to maintain state information on the server, rather than persisting information on the client. With server-based state management, you can decrease the amount of information sent to the client in order to preserve state, however it can use costly resources on the server. The following sections describe three server-based state management features: application state, session state, and profile properties.

Application State

ASP.NET allows you to save values using application state — which is an instance of the HttpApplicationState class — for each active Web application. Application state is a global storage mechanism that is accessible from all pages in the Web application. Thus, application state is useful for storing information that needs to be maintained between server round trips and between requests for pages. For more information, seeASP.NET Application State Overview.
Application state is stored in a key/value dictionary that is created during each request to a specific URL. You can add your application-specific information to this structure to store it between page requests.
Once you add your application-specific information to application state, the server manages it. For usage recommendations, see ASP.NET State Management Recommendations.

Session State

ASP.NET allows you to save values by using session state — which is an instance of the HttpSessionState class — for each active Web-application session. For an overview, see ASP.NET Session State Overview.
Session state is similar to application state, except that it is scoped to the current browser session. If different users are using your application, each user session will have a different session state. In addition, if a user leaves your application and then returns later, the second user session will have a different session state from the first.
Session state is structured as a key/value dictionary for storing session-specific information that needs to be maintained between server round trips and between requests for pages. For more information, seeASP.NET Session State Overview.
You can use session state to accomplish the following tasks:
  • Uniquely identify browser or client-device requests and map them to an individual session instance on the server.
  • Store session-specific data on the server for use across multiple browser or client-device requests within the same session.
  • Raise appropriate session management events. In addition, you can write application code leveraging these events.
Once you add your application-specific information to session state, the server manages this object. Depending on which options you specify, session information can be stored in cookies, on an out-of-process server, or on a computer running Microsoft SQL Server. For usage recommendations, see ASP.NET State Management Recommendations.

Profile Properties

ASP.NET provides a feature called profile properties, which allows you to store user-specific data. This feature is similar to session state, except that the profile data is not lost when a user's session expires. The profile-properties feature uses an ASP.NET profile, which is stored in a persistent format and associated with an individual user. The ASP.NET profile allows you to easily manage user information without requiring you to create and maintain your own database. In addition, the profile makes the user information available using a strongly typed API that you can access from anywhere in your application. You can store objects of any type in the profile. The ASP.NET profile feature provides a generic storage system that allows you to define and maintain almost any kind of data while still making the data available in a type-safe manner.
To use profile properties, you must configure a profile provider. ASP.NET includes a SqlProfileProvider class that allows you to store profile data in a SQL database, but you can also create your own profile provider class that stores profile data in a custom format and to a custom storage mechanism such as an XML file, or even to a web service.
Because data that is placed in profile properties is not stored in application memory, it is preserved through Internet Information Services (IIS) restarts and worker-process restarts without losing data. Additionally, profile properties can be persisted across multiple processes such as in a Web farm or a Web garden. For more information, see ASP.NET Profile Properties Overview.












NOTE:-----This page is under construction...some points related to client side state management is be updated in upcoming days and server side state management is few world only introduction about that.....that will be also update in upcoming days......



Thanks
Amitesh Anand
Software Developer





No comments:

Post a Comment