Thursday, 23 January 2014

State Management in ASP.NET

State management means to preserve state of a control, web page, object/data, and user in the application explicitly because all ASP.NET web applications are stateless, i.e., by default, for each page posted to the server, the state of controls is lost. 

HTTP is a stateless protocol. Once the server serves any request from the user, it cleans up all the resources used to serve that request. These resources include the objects created during that request, the memory allocated during that request, etc. If we have to track the users' information between page visits and even on multiple visits of the same page, then we need to use the State management techniques provided by ASP.NET. State management is the process by which ASP.NET let the developers maintain state and page information over multiple request for the same or different pages.

Types of state management

Here we are here with various options for ASP.NET developer to implement state management techniques in their applications. Broadly, we can classify state management techniques as client side state management or server side state management. Each technique has its own pros and cons. Let's start with exploring client side state management options.

There are mainly two types of state management that ASP.NET provides:
  1. Client side state management
  2. Server side state management
When we use client side state management, the state related information will be stored on client side. This information will travel back and forth with every request and response. This can be visualized as:
client side
Note: Image taken from Microsoft press' Book.
The major benefit of having this kind of state management is that we relieve the server from the burden of keeping the state related information, it saves a lot of server memory. The downside of client side state management is that it takes more bandwidth as considerable amount of data is traveling back and forth. But there is one more problem which is bigger than the bandwidth usage problem. The client side state management makes the information travel back and forth and hence this information can be intercepted by anyone in between. So there is no way we can store the sensitive information like passwords, creditcard number and payable amount on client side, we need server side state management for such things.
Server side state management, in contrast to client side, keeps all the information in user memory. The downside of this is more memory usage on server and the benefit is that users' confidential and sensitive information is secure.
client side
Note: Image taken from Microsoft press' Book.
We cannot say that we will use any one type of state management in our application. We will have to find a mix of client side and server side state management depending on the type and size of information. Now let us look at what are the different ways we can manage state on client side and server side.
Client side state management techniques
  • View State
  • Control State
  • Hidden fields
  • Cookies
  • Query Strings

Server side state management techniques

  • Application State
  • Session State

1. View State

ASP.NET uses this mechanism to track the values of the controls on the web page between page request for same page. We can also add custom values to view state. ASP.NET framework takes care of storing the information of controls in view state and retrieving it back from viewstate before rendering on postback.
If we need to use viewstate to store our information, we just need to remember that the viewstate is adictionary object. We can have our data stored as key value pair in viewstate (see code below). The controls information is also being hashed into this dictionary during request and populated back during response.

Since this information is stored in the web page itself, ASP.NET encrypts the information. 

<Configuration>
       <system.web>
       <pages viewStateEncryptionMode="Always"/>
       <system.web/>
   <Configuration/> 

or page declarative:

<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" ViewStateEncryptionMode="Always"%> 

Let us now look at a small implementation for viewstate.  When we run the page and write something in the textbox and press the button, a postback occurs but my name still remains in the textboxViewstate made that possible so after postback, the page looks like:

When we look at the source, the view state looks like:

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTkwNjc4NTIwMWRkfIZa4Yq8wUbdaypyAjKouH5Vn1Y=" />

// Add item to ViewState
ViewState["myviewstate"]  = myValue;

//Reading items from ViewState
Response.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

2. Control State

We now know what a viewstate is and we also know that we can disable viewstate for controls on the page. But imagine if we are developing a custom control and we internally are using viewstate to store some information but the user of the control can disable the viewstate for our control. To avoid this problem, we can have viewstate like behavior which cannot be disabled by control users and it is called ControlState. 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. Control states lies inside custom controls and work the same as viewstate works.To use control state in a custom control, we have to override the OnInit method and call the RegisterRequiresControlState method during initialization. Then we have to override the SaveControlState and  LoadControlState methods.

3. Hidden Fields

Hidden field are the controls provided by the ASP.NET and they let use store some information in them. The only constraint on hidden filed is that it will keep the information when HTTP post is being done, i.e., button clicks. It will not work with HTTP getHidden 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

 HiddenField1.Value="Create hidden fields";

//to retrieve a value

string str= HiddenField1.Value;

protected void Button1_Click(object sender, EventArgs e)
{
    HiddenField1.Value = (Convert.ToInt32(HiddenField1.Value) + 1).ToString();
 
    Label1.Text = string.Format("Clicked {0} times", HiddenField1.Value);
}


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

4. Cookies

There are scenarios when we need to store the data between page requests. So far, the techniques we have discussed store the data for the single page requests. Now we look at the techniques that store information between page requests. A cookie is a small amount of data which is either stored at client side in text file or in memory of the client browser session. Cookies are always sent with the request to the web server and information can be retrieved from the cookies at the web server. Every time a user visits a website, cookies are retrieved from the user machine and help identify the user.
Cookies are useful for storing small amounts of frequently changed information on the client. The information is sent with the request to the server.

Sample:

 // Creating a cookie
myCookie.Values.Add("muffin""chocolate");
myCookie.Values.Add("babka""cinnamon");

// Adding Cookie to Collection
Response.Cookies.Add(myCookie);

// Getting Values stored in a cookie
Response.Write(myCookie["babka"].ToString());

// Setting cookie pathmyCookie.Path = "/forums";

// Setting domain for a cookiemyCookie.Domain = "forums.geekpedia.com";

// Deleting a cookiemyCookie.Expires = DateTime.Now.AddDays(-1);
Code Example:

//Storing value in cookie
HttpCookie cookie = new HttpCookie("NickName");
cookie.Value = "David";
Request.Cookies.Add(cookie);
//Retrieving value in cookieif (Request.Cookies.Count > 0 && Request.Cookies["NickName"] != null)
         lblNickName.Text = "Welcome" + Request.Cookies["NickName"].ToString();
else         lblNickName.Text = "Welcome Guest"

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

5. Query Strings

A Query string is used to pass the values or information form one page to another page. They are passed along with URL in clear text. Query strings provide a simple but limited way of maintaining some state information A query string is information that is appended to the end of a page URL. They can be used to store/pass information from one page to another to even the same page. 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.When surfing the internet you should have seen weird internet addresses such as:

http://www.localhost.com/Webform2.aspx?name=ABC&lastName=XYZ

This HTML address uses a QueryString property to pass values between pages.Here we pass two parameter in the query string i.e name and lastName and value of the parameter are ABC & XYZ respectively.

In the webform2.aspx page we can get the value of the Query String parameter :- 
Code Example:

using System;using System.Web.UI;
public partial class _Default : Page{
    protected void Page_Load(object sender, EventArgs e)
    {
        string v = Request.QueryString["name"];
        if (v != null)
        {
            Response.Write("name is ");
            Response.Write(v);
        }
        string x = Request.QueryString["lastName"];
        if (x != null)
        {
            Response.Write("   lastName");
        }
    }
}

Advantages:
  • Simple to Implement
  • Widespread used
  • No Server Resources required
Disadvantages:
  • Human Readable 
  • Client browser limit on URL length
  • Cross paging functionality makes it redundant 
  • Easily modified by end user
  • Limited Capacity

1. Application State

ASP.NET allows us 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. This information will also be available to all the users of the website. Application state is stored in the memory of the windows process which is processing user requests on the web server. Application state is useful in storing a small amount of often-used data. If application state is used for such data instead of frequent trips to the database, then it increases the response time/performance of the web application.
In classic ASP, an application object is used to store connection strings. It's a great place to store data that changes infrequently.
ASP.NET provides three events that enable you to initialize Application variables (free resources when the application shuts down) and respond to Application errors:

  • Application_Start: Raised when the application starts. This is the perfect place to initialize Applicationvariables.
  • Application_End: Raised when an application shuts down. Use this to free application resources and perform logging.
  • Application_Error: Raised when an unhandled error occurs. Use this to perform error logging.



//global.asax



void Application_Start(object sender, EventArgs e)

{
    //Declare Application Variable 

    Application["number"] = 0;
}

//In web pages
Application.Lock();
//Store value in Application Variable
Application["number"] = Convert.ToInt32(Application["number"]) + 1;
Application.UnLock();

Label5.Text = Application["number"].ToString();

Advantages:
  • Simple to Implement
  • Application Scope
Disadvantages:
  • Resource requirment 
  • Limited durability of data

2. Session State

ASP.NET Session state provides a place to store values that will persist across page requests. Values stored in Session are stored on the server and will remain in memory until they are explicitly removed or until the Session expires. It is defined as the period of time that a unique user interacts with a Web application. Session state is a collection of objects, tied to a session stored on a server. when we need user specific information, then we better use sessionstate.


Sample:

//Storing informaton in session state
Session["NickName"] = "ABC";

//Retrieving information from session state
string str = Session["NickName"]; 

 
Code Example:

object sessionObject = Session["someObject"];

if (sessionObject != null)
{
 myLabel.Text = sessionObject.ToString();
}


Advantages:
  • Session Specific event
  • Cookie less support
Disadvantages:
  • Performance Consideration

3. Profile Properties

ASP.NET provides a feature called profile properties, which allows you to store user-specific data. It is similar to session state, except that unlike session state, 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. In this each user has its own profile object.

Sample:
<profile>
  <properties>
    <add item="item name" />
  </properties>
</profile>
 
Code Example:
 <authentication mode="Windows" /> 
      <profile>  
      <properties>  
     <add name="FirstName"/>  
     <add name="LastName"/>  
     <add name="Age"/>  
     <add name="City"/>  
      </properties>  
   </profile> 

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>    
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 vale 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.

                                                                                           Continue   :-    sessionState mode

Ref By :- 

http://www.codeproject.com
http://www.c-sharpcorner.com

No comments:

Post a Comment