Skip to main content

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:
  1. string fName=Request.QueryString["firstName"].toString();  
  2.   string lName=Request.QueryString["lirstName"].toString();  
  3.   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:
  1. int intCount=0;  
  2. protected void Page_Load(object sender, EventArgs e)  
  3. {  
  4. HiddenField  hdn=new HiddenField();  
  5.    if(!IsPostBack)  
  6.   {  
  7.        intCount=10;  
  8.        hdn.Value=intCount.ToString();  
  9.        Response.Write("Not PostBack " +intCount);  
  10.   }  
  11.   else if(IsPostBack)  
  12.  {  
  13.        Response.Write("PostBack intCount " + intCount + "  
  14. ");  
  15.        Response.Write("PostBack hidden value is " + hdn.Value);  
  16.  }  
  17. }  
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:
  1. int intCount = 0;      
  2.     protected void Page_Load(object sender, EventArgs e)  
  3.     {  
  4.         if (!IsPostBack)  
  5.         {  
  6.             intCount = 10;  
  7.             ViewState["PID"] = 10;  
  8.             Response.Write("not post back " + intCount);  
  9.         }  
  10.         else if (IsPostBack)  
  11.         {  
  12.             Response.Write("post back intCount " + intCount + "  
  13. ");  
  14.             Response.Write("post back " + ViewState["PID"]);  
  15.         }  
  16.     }  

>> 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)


  1. <b>Default.aspx</b>  
  2.   
  3. protected void Page_Load(object sender, EventArgs e)  
  4.     {  
  5.         HttpCookie cookie = new HttpCookie("Uname""ramesh");  
  6.         Response.Cookies.Add(cookie);  
  7.         Response.Redirect("Default2.aspx");  
  8.     }  
  9.   
  10. <b>Default2.aspx</b>  
  11.   
  12.     protected void Page_Load(object sender, EventArgs e)  
  13.     {  
  14.         if (Request.Cookies["Uname"] != null)  
  15.             Response.Write(Request.Cookies["Uname"].Value);  
  16.         else Response.Write("Cookie not available");  
  17.     }  

2)Persistant cookie or permanent cookie

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

eg:1)
  1. protected void Page_Load(object sender, EventArgs e)  
  2.     {  
  3.         if (Request.Cookies["Uname"] != null)          
  4.         {  
  5.             //Response.Redirect("Default2.aspx");  
  6.             TextBox1.Text = Convert.ToString(Request.Cookies["Uname"].Value);  
  7.             TextBox2.Text = Convert.ToString(Request.Cookies["Pwd"].Value);  
  8.         }  
  9.     }  
  10.     protected void Button1_Click(object sender, EventArgs e)  
  11.     {  
  12.         if (Request.Cookies["Uname"] == null)  
  13.         {  
  14.             HttpCookie obj = new HttpCookie("Uname", txtUname.Text);  
  15.             HttpCookie obj2 = new HttpCookie("Pwd", txtPwd.Text);  
  16.             obj.Expires = DateTime.Now.AddDays(1);  
  17.             obj2.Expires = DateTime.Now.AddDays(1);  
  18.             Response.Cookies.Add(obj);  
  19.             Response.Cookies.Add(obj2);  
  20.             Response.Redirect("Default2.aspx");  
  21.         }  
  22.     }  

3)Dictionary cookie or Multivalued cookie

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

eg:1)

Default.aspx

  1. protected void Page_Load(object sender, EventArgs e)  
  2.     {  
  3.         HttpCookie objCookie = new HttpCookie("Trainees");  
  4.         objCookie.Values.Add("Name1""100");  
  5.         objCookie.Values.Add("Name2""200");  
  6.         objCookie.Values.Add("Name3""300");  
  7.         objCookie.Expires = DateTime.Now.AddDays(1);  
  8.         Response.Cookies.Add(objCookie);  
  9.         Response.Redirect("Default2.aspx");  
  10.     }  

Default2.aspx
  1. protected void Page_Load(object sender, EventArgs e)  
  2.     {  
  3.         if (Request.Cookies["Trainees"] != null)  
  4.             Response.Write(Request.Cookies["Trainees"]["Name2"]);  
  5.     }  

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]).





Comments

Popular posts from this blog

Tip/Trick: Fix Common SEO Problems Using the URL Rewrite Extension

Search engine optimization (SEO) is important for any publically facing web-site.  A large % of traffic to sites now comes directly from search engines, and improving your site’s search relevancy will lead to more users visiting your site from search engine queries.  This can directly or indirectly increase the money you make through your site. This blog post covers how you can use the free Microsoft  URL Rewrite Extension  to fix a bunch of common SEO problems that your site might have.  It takes less than 15 minutes (and no code changes) to apply 4 simple  URL Rewrite  rules to your site, and in doing so cause search engines to drive more visitors and traffic to your site.  The techniques below work equally well with both ASP.NET Web Forms and ASP.NET MVC based sites.  They also works with all versions of ASP.NET (and even work with non-ASP.NET content). [In addition to blogging, I am also now using Twitter for quick updates and to sh...

ASP.NET MVC - Set custom IIdentity or IPrincipal

Here's how I do it. I decided to use IPrincipal instead of IIdentity because it means I don't have to implement both IIdentity and IPrincipal. Create the interface interface ICustomPrincipal : IPrincipal { int UserId { get ; set ; } string FirstName { get ; set ; } string LastName { get ; set ; } } CustomPrincipal public class CustomPrincipal : ICustomPrincipal { public IIdentity Identity { get ; private set ; } public bool IsInRole ( string role ) { return false ; } public CustomPrincipal ( string email ) { this . Identity = new GenericIdentity ( email ); } public int UserId { get ; set ; } public string FirstName { get ; set ; } public string LastName { get ; set ; } } CustomPrincipalSerializeModel - for serializing custom information into userdata field in FormsAuthenticationTicket object. public class CustomPrincipalSerializeMode...

How to create a countdown timer in jquery

Create a countdown timer in jQuery First we need to include the jQuery library file to the HTML page to perform this task. To do that we need to understand that what exactly a jQuery library fie is ? JQuery library file is the library of JavaScript, which means this file contains the predefined functions of jQuery. We just need to call these functions to perform the task. jQuery functions reduces the lines of code and makes our task easy. As this jQuery library file contains the javascript functions so we need to call the function within <script> </script> tag. Now after including the file, we need to define a variable which will store that for how long you want the timer on the page(c=60) and now the time you set needs to be changed in hours , minutes and seconds using the code “ var hours = parseInt( time / 3600 ) % ;var minutes = parseInt( time / 60 ) % 60; var seconds = time % 60;” Now we need to put the condition if timer got finished (if (t...