State Management in ASP.NET

August 3, 2009 at 1:46 pm | Posted in ASP.NET | Leave a comment
Tags: , , , , ,

Web form pages are HTTP-Based, they are stateless, which means theydon’t know whether the requests are all from the same client, and pagesare destroyed and recreated with each round trip to the server,therefore information will be lost, therefore state management isreally an issue in developing web applications

We could easilysolve these problems in ASP with cookie, query string, application,session and so on. Now in ASP.NET, we still can use these functions,but they are richer and more powerful, so let’s dive into it.

Mainly there are two different ways to manage web page’s state: Client-side and Server-side.

Client-side state management :

There is no information maintained on the server between round trips.Information will be stored in the page or on the client’s computer.

A. Cookies.

Acookie is a small amount of data stored either in a text file on theclient’s file system or in-memory in the client browser session.Cookies are mainly used for tracking data settings. Let’s take anexample: say we want to customize a welcome web page, when the userrequest the default web page, the application first to detect if theuser has logined before, we can retrieve the user informatin fromcookies:
[c#]
if (Request.Cookies[“username”]!=null)
lbMessage.text=”Dear “+Request.Cookies[“username”].Value+”, Welcome shopping here!”;
else
lbMessage.text=”Welcome shopping here!”;

If you want to store client’s information, you can use the following code:
[c#]
Response.Cookies[“username’].Value=username;

So next time when the user request the web page, you can easily recongnize the user again.

B. Hidden Field

Ahidden field does not render visibly in the browser, but you can setits properties just as you can with a standard control. When a page issubmitted to the server, the content of a hidden field is sent in theHTTP Form collection along with the values of other controls. A hiddenfield acts as a repository for any page-specific information that youwould like to store directly in the page. Hidden field stores a singlevariable in its value property and must be explicitly added it to thepage.
ASP.NET provides the HtmlInputHidden control that offers hidden field functionality.
[c#]
protected System.Web.UI.HtmlControls.HtmlInputHidden Hidden1;
//to assign a value to Hidden field
Hidden1.Value=”this is a test”;
//to retrieve a value
string str=Hidden1.Value;

Note:Keep in mind, in order to use hidden field, you have to use HTTP-Postmethod to post web page. Although its name is ‘Hidden’, its value isnot hidden, you can see its value through ‘view source’ function.

C. View State

Eachcontrol on a Web Forms page, including the page itself, has a ViewStateproperty, it is a built-in struture for automatic retention of page andcontrol state, which means you don’t need to do anything about gettingback the data of controls after posting page to the server.

Here, which is useful to us is the ViewState property, we can use it to save information between round trips to the server.
[c#]
//to save information
ViewState.Add(“shape”,”circle”);
//to retrieve information
string shapes=ViewState[“shape”];

Note: Unlike Hidden Field, the values in ViewState are invisible when ‘view source’, they are compressed and encoded.

D. Query Strings

Querystrings provide a simple but limited way of maintaining some stateinformation.You can easily pass information from one page to another,But most browsers and client devices impose a 255-character limit onthe length of the URL. In addition, the query values are exposed to theInternet via the URL so in some cases security may be an issue.
A URL with query strings may look like this:

http://www.examples.com/list.aspx?categoryid=1&productid=101

When list.aspx is being requested, the category and product information can be obtained by using the following codes:
[c#]
string categoryid, productid;
categoryid=Request.Params[“categoryid”];
productid=Request.Params[“productid”];

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

Server-side state management :

Information will be stored on the server, it has higher security but it can use more web server resources.

A. Aplication object

TheApplication object provides a mechanism for storing data that isaccessible to all code running within the Web application, The idealdata to insert into application state variables is data that is sharedby multiple sessions and does not change often.. And just because it isvisible to the entire application, you need to used Lock and UnLockpair to avoid having conflit value.
[c#]
Application.Lock();
Application[“mydata”]=”mydata”;
Application.UnLock();

B. Session object

Sessionobject can be used for storing session-specific information that needsto be maintained between server round trips and between requests forpages. Session object is per-client basis, which means differentclients generate different session object.The ideal data to store insession-state variables is short-lived, sensitive data that is specificto an individual session.

Each active ASP.NET session isidentified and tracked using a 120-bit SessionID string containingURL-legal ASCII characters. SessionID values are generated using analgorithm that guarantees uniqueness so that sessions do not collide,and SessionID’s randomness makes it harder to guess the session ID ofan existing session.
SessionIDs are communicated acrossclient-server requests either by an HTTP cookie or a modified URL,depending on how you set the application’s configuration settings. Sohow to set the session setting in application configuration? Ok, let’sgo further to look at it.

Every web application must have aconfiguration file named web.config, it is a XML-Based file, there is asection name ‘sessionState’, the following is an example:

<sessionStatemode=”InProc” stateConnectionString=”tcpip=127.0.0.1:42424″sqlConnectionString=”data source=127.0.0.1;user id=sa;password=”cookieless=”false” timeout=”20″ />

‘cookieless’ option can be‘true’ or ‘false’. When it is ‘false’(default value), ASP.NET will useHTTP cookie to identify users. When it is ‘true’, ASP.NET will randomlygenerate a unique number and put it just right ahead of the requestedfile, this number is used to identify users, you can see it on theaddress bar of IE:

http://localhost/Management/(2yzakzez3eqxut45ukyzq3qp)/Default.aspx

Ok, it is further enough, let is go back to session object.
[c#]
//to store information
Session[“myname”]=”Mike”;
//to retrieve information
myname=Session[“myname”];

C. Database

Databaseenables you to store large amount of information pertaining to state inyour Web application. Sometimes users continually query the database byusing the unique ID, you can save it in the database for use acrossmultiple request for the pages in your site.

Advantages and disadvantages of Viewstate

November 19, 2008 at 7:10 pm | Posted in ASP.NET | 6 Comments
Tags: , , ,

The primary advantages of the ViewState feature in ASP.NET are:

1. Simplicity. There is no need to write possibly complex code to store form data between page submissions.
2. Flexibility. It is possible to enable, configure, and disable ViewState on a control-by-control basis, choosing to persist the values of  some fields but not others.

There are, however a few disadvantages that are worth pointing out:

1. Does not track across pages. ViewState information does not automatically transfer from page to page. With the session approach, values can be stored in the session and accessed from other pages. This is not possible with ViewState, so storing data into the session must be done explicitly.

2. ViewState is not suitable for transferring data for back-end systems. That is, data still has to be transferred to the back end using some form of data object.


Entries and comments feeds.