Article
One Community, One World
ASP.NET Client-Based State Management Part01:Cookies
by Ahmed Rafie  on Jun 6 2007 12:00AM
  PageViews 4245   |    Add to Fav   |     Send to Friend   |    no downloads available

Introduction
By studying the life cycle of the web page, we will find that when the user send a Request to the web server, A new instance of the web page class is created, this means That all information associated with the page and its controls would be lost .To Preserve data on the page you have to choose one of the ASP.NET State Management Option, the server-based or the client-based .in these set of articles I will explain all The client-based on options.  

Client-based State Management option:
All client-based options involve storing data on the client computer or in the page itself, this means that these options doesn't use server resources. this  will fast the server performance because the demand on the server resources  is  modest .On the Other  hand  these  options  typically  have  minimal  security .

These options are:  

  • Cookies
  • Query strings
  • Hidden fields
  • View state
  • Control state

Cookies:
A cookie  is  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 , when a user visits your web Site, you can  use  cookies to store information  in a folder on the user's hard disk , if The user visits your web site again you can retrieve the information you stored earlier.  

If user requests a page from your website, the web application sends not just a page, But also a cookie containing the date and time of creation. When the user's browser gets the page the browsers also gets the cookies.  

Cookies are used for many purposes, all relating to helping the website remember users , for example a site conducting a poll might use a cookie simply as a Boolean value  to  indicate  whether a user's browser has already participated in voting so that the user cannot vote twice.
  

How To: write a cookie 
Cookie are sent to the client using the HTTP Response object, which exposes a Properly  called Cookies, when you write a new cookie, you must specify name and value. The name must be unique so that application can identify it.  

There are two ways to write a cookie

  1. Set the cookies properties on the cookies collection       

    C#
    Response.Cookies["User ID"].Value = "1234";       
    Response.Cookies["User ID"].Expires = DateTime.Now.AddDays(1);
    
    
  2. Creating an instance of HTTP Cookie object

    C#
        
    HttpCookie XC = new HttpCookie["Last Visit"];       
    XC.Value = DateTime.Now.ToString{};       
    XC.Expires = DateTime.Now.AddDays{1};       
    Response.Cookies.Add(XC);
    
    

How to: Read a cookie
You can read only cookies that have been created by pages in the current Domain or path.       

C#
if (Response.Cookies["User ID"] != null)      
    {         
        Response.Write(Server.HtmlEncode(Response.Cookies["User ID"].Value));            
    } 



Before trying to get the value of a cookie you should make sure that cookie exists. If the cookie doesn't exist you will get a Null Reference Exception. The HTMLEncode(  )method called to encode the content  of a cookie before displaying it. This makes certain that malicious user has not added executable Script into the cookie.  

How to: Modify a cookie
You cannot directly modify a cookie, Instead of changing a cookie consists of creating a new cookie with new values and then sending the cookie to the Browser to over write the old version on the client.        

C#
if (Response.Cookies["User ID"] != null)        
    {           
        Response.Cookies["User ID"].Value = "5678";           
        Response.Cookies["User ID"].Expires = DateTime.Now.AddDays(1);        
    }



How to: Delete a cookie
You can no directly remove a cookie because the cookie is on the user's computer. But you can have the browser delete the cookie for you. You can do that by creating a new cookie with the same name as on the cookie to be deleted and set its expiration Date to be an earlier than to day. When the browser check the cookie's expiration date. It will delete it.         
    
C#
if(Response.Cookies["User ID"] != null)
   {             
         HttpCookie m = new HttpCookie("User ID");             
         m.Expires = DateTime.Now.AddDays(-1);             
         Response.Cookies.Add(m);
    }



Cookies with more than one value
You can store one value in a cookie,and you can also multiple name-value Pairs in a single cookie. These pairs referred to as sub keys, you might use sub keys for several reasons:

  1. It is convenient to put related information into a single cookie. And expiration date applies to all information.
  2. A cookie with sub keys also helps you limit the size of cookie files.  

How to: Create a cookie with sub keys    

C#
Response.Cookies["User Info"]["User ID"] = "1234";    
Response.Cookies["User Info"]["Lastvisit"] = DateTime.Now.ToString();    
HttpCookie XC = new HttpCookie("UserInfo");   
XC.Values["UserID"] = "1234";       
XC.Values["Uservisit"] = DateTime.Now.ToString();       
Response.Cookies.Add(XC);  



Determining whether a browser accepts cookies 
You have one way to determine whether cookies are accepted is by trying to write a cookie and then trying to read it back again. The cookies properly don't indicate whether cookies are enabled. It indicates only whether cookies are browser supports cookies. If you can't read a cookie you write then cookies not accepted by the visitor's browser.  

Controlling Cookies Scope: 
By default, all cookies are sent to the server with any request to the website, this means every page in a site gets all the cookies for that site, you can get set the scope of the cookies in two ways.    

(i)  Limiting cookies to a folder or Application to limit cookies to a folder on the server, set the path properly of the cookie.      

C#
HttpCookie XC = new HttpCookie("App");      
XC.Value = "Limited";      
XC.Expires = DateTime.Now.AddDays(1);      
XC.Path = "/Application1";              
Response.Cookies.Add(XC);

 

If your domain is www.Hut.com/application1, the previous example cookie will be limited only to www.Hut.com/Application2.  

(ii)  Limiting Cookie Domain Scope 

If the cookies associated with a specific domain such as www.Hut.com and you have sub domains such as D1.HUT.COM and D2.HUT.COM to set the cookie to sub domain, you can set the cookies domain property.    

C#
Response.Cookies["UserID"].Domain = "D1.hut.com"; 


And to make cookies to be shared among multiple sub Domains   

C#
Response.Cookies["UserID"].Domain = "hut.com"; 



Cookies Limitations:
1. Most browsers support cookies of up to 4096 bytes because of this small limit, cookies are best used to store small amount of data. 
2. Browsers also impose limitation on how many cookie your website can store on the user's computer. Most browsers allow only 20 cookies per site. 
3. Users can set their browsers to reuse cookies. If you define a P3P privacy policy and place it in the root of your website. More will accept cookies from your website.    

Conclusion 
In this part of ASP.NET client-based state management option, I introduced the cookies world which is very effective option that ASP.NET Offer. Finally you have to add a full description in your privacy statement Page of how you used cookies in your website and which type of information you store in.

Comments