Tuesday, August 30, 2011

Client Side State Management Techniques in Asp.net


Generally, Web applications are based on stateless HTTP protocol, which doesn't hold any information about the user requests.
HTTP is stateless protocol means Server takes every request as a new request.Stateless Protocol behaviour is

Go, Get and Forget
Go --> Establish the connection to the server
Get --> Get the response from the server
Forget --> Close the connection to the server.

Http Stateless feature is an advantage for the Server. Because it will reduce the burden on webserver.If connection established to server always, many users are used the server around the world so diffenetely more burden on server.

So our aim is that we must use HTTP protocol and Server should remember user's info.This feature is came with the concept of "State Management".

Definition of StateManagement and StateManagement Types:

State Management:

This is a concept of Web Server, which remembers the user's information. OR
It holds the information about multiple user requests.

Options or Types:

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

Client Side State Management Techniques:

If a user clicks a button or any server side control then what will be happened, the page information goes to the server and back again to user's web browser. So until now there is no automatic information storage structure for client Server applications.
There are mainly Five ways to maintain the state at client side.

a.QueryString(URL)
b. Hidden Fields.
c. ViewState.
d. ControlState(ASP.Net 2.0)
e.Cookies.



a.QueryStrings(URL):

It is a client side management technique. It is used to pass the values or information from one page to another page through URL.
Example:
For example There are two pages named as FirstPage.aspx and SecondPage.aspx
Our aim that we will pass the user's information from the FirstPage to SecondPage through URL.
In FirstPage.aspx, Passing information(fName,lName) to the SecondPage.aspx with the URL. Simply it is an URL, with a question mark ?, followed by a key value pair.

FirstPage.aspx:

Response.Redirect("SecondPage.aspx?firstName=Bhaskar & lastName=Kovvuri");

In SecondPage.aspx, we must use the HttpRequest object to read the user's information which we passed from the FirstPage.aspx.

SecondPage.aspx:


string fName=Request.QueryString["firstName"].toString();
  string lName=Request.QueryString["lirstName"].toString();
  Response.Write("Hello,"+fName+" "+lName);

The Result in the SecondPage.aspx page is
Hello,Bhaskar Kovvuri

Advantages:

1.Very easy to implement.
2. No postback operations from the Server.

Limitations and Disadvantages:

1.Limit on length of querystring the particular browser allows.
Maximum lenght is based on the browser not depend upon the ASP.Net
Internet Explorer(4.0,5.0,6.0,7.0) supports ---> ~2048 characters(i.e.,256bytes)
Opera supports ---> ~4050 characters
NetScape 6 supports ---> ~2000 characters

2.No Security.(It can be read or modified by anyone in URL)
3 No peristency.(Doesn't Remember the information in a querystring after the user leaves that page.)
4. Limited to use only strings.No support for storing Structural Data(ArrayLists,Controls,Structures,Classes etc.,)

NOTE: There is no limit on the number of parameters you can pass in the URL, but Limit only on the "Length".



b.Hidden Fields:

A Control without visibility is callec as "Hidden Field"
Example: TextBox -- Visible=false

This control is used to store a non-displayed value in rendered HTML page.
Main Aim of the Hidden Field concept is "To store a value that needs to be persisted across multiple postbacks to the server".

Example for Hidden Field:

int intCount=0;
protected void Page_Load(object sender, EventArgs e)
{
HiddenField  hdn=new HiddenField();
   if(!IsPostBack)
  {
       intCount=10;
       hdn.Value=intCount.ToString();
       Response.Write("Not PostBack " +intCount);
  }
  else if(IsPostBack)
 {
       Response.Write("PostBack intCount " + intCount + "
");
       Response.Write("PostBack hidden value is " + hdn.Value);
 }
}

In the above example, HiddenField is stored the value of intCount as 10. After PostBack itself, we can retrieve the value, which
we can stored in Hidden Field.

Advantages:

1. Simple to implement
2. No server-side cleanup necessary (for expired data)
3. Accessible to client-side scripts

Limitations:

1. The value of the hidden field cannot be trusted to not be tampered from page to page (as opposed to server-side storage)
2. Big data needs to be posted every time, so this is a problem, and it is not possible for some data (for example uploaded images)



c. ViewState:

Viewstate is used to implement the state for variables/objects for multiple/subsequent requests of same page.
(or)
Viewstate used to maintain values through subsequent requests of the same (!) page

>> Viewstate data will be stored in Base64 encoded format
>> Base64 encoded format is not secure.

Asp.net provides all the statemanagement for controls using a class called "StateBag Class".

StateBag Class:

Manages the view state of ASP.NET server controls, including pages. This class cannot be inherited.

eg:

int intCount = 0;    
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            intCount = 10;
            ViewState["PID"] = 10;
            Response.Write("not post back " + intCount);
        }
        else if (IsPostBack)
        {
            Response.Write("post back intCount " + intCount + "
");
            Response.Write("post back " + ViewState["PID"]);
        }
    }


>> ViewState is recommended to stored only the Primitive Types(int,string,....)
Not suggested to store the complex types like Datatable,Dataset,....
>> We can protect the ViewState by Set the Machine key in Web.Config.
Ex:
>> In Some cases, Browsers may block or truncate the generated ViewState due to it's length.
To solve the above problem, we can divide the viewstate to independent hidden fields based on you provide the number as value.
Ex:
>> We can enable the viewstate encryption at page level
Ex: <%@ page --ViewStateEncryptionMode="Always"%>
Enable ViewState encryption at application level. In Web.Config file
Ex:






Advantages

1)Server resources are not required.
2)Automatic retention of page and control state during postbacks.
3)We can apply enncryption algorithm for viewstate data.

Disadvantages:

1)Performance: The view state is stored in the page itself, so increase the page size.
2)Security: The view state is stoed in a hidden field on the page. Although view state stores data in a hashed format, it can be tampered.



d)Control state (ASP.NET 2.0)


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.

Control state, introduced in ASP.NET version 2.0, is similar to view state but functionally independent of view state. A page developer can disable view state for the page or for an individual control for performance. However, control state cannot be disabled. Control state is designed for storing a control's essential data (such as a pager control's page number) that must be available on postback to enable the control to function even when view state has been disabled. By default, the ASP.NET page framework stores control state in the page in the same hidden element in which it stores view state. Even if view state is disabled, or when state is managed using Session, control state travels to the client and back to the server in the page. On postback, ASP.NET deserializes the contents of the hidden element and loads control state into each control that is registered for control state.



e)Cookies:

What is cookie?

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.

Purpose of cookie:

1)Used to store user-specific information with in user system to reduce burden on server.

ie, user-specific inforamtion can be credentials(unam and pwd), sessionid,security token.


Types of cookies:

1)Inmemory cookie or Temporary cookie or Session cookie
2)Persistant cookie or permanent cookie
3)Dictionary cookie or Multivalued cookie(ie, one cookie multiple values)

1)Inmemory cookie or Temporary cookie:

Cookie can be maintained by the browser process memory is called "Inmemory cookie".

eg:1)

Default.aspx

protected void Page_Load(object sender, EventArgs e)
    {
        HttpCookie cookie = new HttpCookie("Uname", "ramesh");
        Response.Cookies.Add(cookie);
        Response.Redirect("Default2.aspx");
    }

Default2.aspx

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Cookies["Uname"] != null)
            Response.Write(Request.Cookies["Uname"].Value);
        else Response.Write("Cookie not available");
    }


2)Persistant cookie or permanent cookie

Cookies can be maintained with in hard disk memory of the client system

eg:1)

protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Cookies["Uname"] != null)        
        {
            //Response.Redirect("Default2.aspx");
            TextBox1.Text = Convert.ToString(Request.Cookies["Uname"].Value);
            TextBox2.Text = Convert.ToString(Request.Cookies["Pwd"].Value);
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (Request.Cookies["Uname"] == null)
        {
            HttpCookie obj = new HttpCookie("Uname", txtUname.Text);
            HttpCookie obj2 = new HttpCookie("Pwd", txtPwd.Text);
            obj.Expires = DateTime.Now.AddDays(1);
            obj2.Expires = DateTime.Now.AddDays(1);
            Response.Cookies.Add(obj);
            Response.Cookies.Add(obj2);
            Response.Redirect("Default2.aspx");
        }
    }


3)Dictionary cookie or Multivalued cookie

It used to store multiple name-value pairs in a single cookie.

eg:1)

Default.aspx
protected void Page_Load(object sender, EventArgs e)
    {
        HttpCookie objCookie = new HttpCookie("Trainees");
        objCookie.Values.Add("Name1", "100");
        objCookie.Values.Add("Name2", "200");
        objCookie.Values.Add("Name3", "300");
        objCookie.Expires = DateTime.Now.AddDays(1);
        Response.Cookies.Add(objCookie);
        Response.Redirect("Default2.aspx");
    }


Default2.aspx

protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Cookies["Trainees"] != null)
            Response.Write(Request.Cookies["Trainees"]["Name2"]);
    }


1)How do you create a Cookie that never expires?
ans)
To create a Cookie that never expires, set the Expires property of the Cookie object to DateTime.MaxValue.

myCookie.Expires = DateTime.MaxValue;



Advantages

1. Cookies do not require any server resources since they are stored on the client.
2. Cookies are easy to implement.

Disadvantages:

1)Cookies can be disabled on user browsers
2)Cookies are transmitted for each HTTP request/response causing overhead on bandwidth
3)No security for sensitive data

Cookie Limitations:

1)Most browsers support cookies of up to 4096 bytes(4kbytes)
2)Most browsers allow only 20 cookies per site; if you try to store more, the oldest cookies are discarded.
3)Browser supports 300 cookies towards different websites.
4)Complex type of data not allowed(eg: dataset), allows only plain text (ie, cookie allows only string content)
5)Cookies are browser specific (ie, one browser type[IE] stored cookies will not be used by another browser type[firefox]).

Labels: , , ,

3 Comments:

At August 30, 2011 at 5:26 PM , Anonymous Anonymous said...

Good Information...:)

 
At September 1, 2011 at 7:12 PM , Anonymous Anonymous said...

Thanks for sharing.....

 
At September 3, 2011 at 2:01 PM , Anonymous Anonymous said...

Very informative post
Thanks

 

Post a Comment

Subscribe to Post Comments [Atom]

<< Home