30 January 2014

Asp.net Client State Management - Cookies

      Cookies are associated with a Web site, not with a specific page, so the browser and server will exchange cookie information no matter what page the user requests from your site. As the user visits different sites, each site might send a cookie to the user's browser as well; the browser stores all the cookies separately.

      Cookies help Web sites store information about visitors. More generally, cookies are one way of maintaining continuity in a Web application—that is, of performing state management. Except for the brief time when they are actually exchanging information, the browser and Web server are disconnected.

      Each request a user makes to a Web server is treated independently of any other request. Many times, however, it's useful for the Web server to recognize users when they request a page.

      For example, the Web server on a shopping site keeps track of individual shoppers so the site can manage shopping carts and other user-specific information. A cookie therefore acts as a kind of calling card, presenting pertinent identification that helps an application know how to proceed.

      Cookies are used for many purposes; all relating to helping the Web site 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. A site that asks a user to log on might use a cookie to record that the user already logged on so that the user does not have to keep entering credentials.


Types of Cookies

There two type of cookies in ASP.NET

    1) Persistent cookies
    2) Non-persistent cookies

 Persistent cookies:
     Cookies are stored on your computer hard disk. They stay on your hard disk and can be accessed by web servers until they are deleted or have expired.
Example to Create  Persistent cookies:
    public void SetPersistentCookies(string name, string value)
   {
     HttpCookie cookie = new HttpCookie(name);

    cookie.Value = value;
     cookie.Expires = Convert.ToDateTime(“12/12/2008″);
     Response.Cookies.Add(cookie);
   }
Non-persistent cookies:

    Cookies are saved only while your web browser is running.They can be used by a web server only until you close your browser.They are not saved on your disk.
    
Example to Create  Persistent cookies:

     public void SetNonPersistentCookies(string name, string value)
       {
           HttpCookie cookie = new HttpCookie(name);
           cookie.Value = value;
           Response.Cookies.Add(cookie);
      }

Cookies Implementation

Creating/Writing Cookies

There are many ways to create cookies; I am going to outline some of them below:

Way 1 (by using HttpCookie class)
 W//First way
HttpCookie StudentCookies = new HttpCookie("StudentCookies");
StudentCookies.Value = TextBox1.Text;
StudentCookies.Expires = DateTime.Now.AddHours (1);
Response.Cookies.Add (StudentCookies);

Way 2 (by using Response directly)
//Second Way
Response. Cookies["Student Cookies"].Value = TextBox1.Text;
Response.Cookies ["Student Cookies"].Expires = DateTime.Now.AddDays(1);

Way 3 (multiple values in same cookie)
//Writing Multiple values in single cookie
Response.Cookies ["Student Cookies"]["RollNumber"] = TextBox1.Text;
Response.Cookies["StudentCookies"]["FirstName"] = "Omkar";
Response.Cookies["StudentCookies"]["MiddleName"] = "Kumar";
Response.Cookies["StudentCookies"]["LastName"] = "Varun";
Response.Cookies["StudentCookies"]["TotalMarks"] = "499";
Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(1);

Reading/Getting Cookies

In the above code, I have used many ways to write or create cookies so I need to write here using all the above ways separately.

For Way 1
string roll = Request.Cookies["StudentCookies"].Value; //For First Way

For Way 2
string roll = Request.Cookies["StudentCookies"].Value;  //For Second Way

For Way 3

//For Multiple values in single cookie
String roll;
roll = Request.Cookies["StudentCookies"]["RollNumber"];
roll = roll + " " + Request.Cookies["StudentCookies"]["FirstName"];
roll = roll + " " + Request.Cookies["StudentCookies"]["MiddleName"];
roll = roll + " " + Request.Cookies["StudentCookies"]["LastName"];

Cookie Limitations

          Most browsers support cookies of up to 4096 bytes. Because of this small limit, cookies are best used to store small amounts of data, or better yet, an identifier such as a user ID. The user ID can then be used to identify the user and read user information from a database or other data store

          Browsers also impose limitations on how many cookies your site can store on the user's computer. Most browsers allow only 20 cookies per site; if you try to store more, the oldest cookies are discarded. Some browsers also put an absolute limit, usually 300, on the number of cookies they will accept from all sites combined.A cookie limitation that you might encounter is that users can set their browser to refuse cookies. 

        However, you might have to avoid cookies altogether and use a different mechanism to store user-specific information. A common method for storing user information is session state, but session state depends on cookies

No comments:

Post a Comment