Cookies for the Beginners

Ganeshji
Posted by in ASP.NET category on for Beginner level | Views : 5129 red flag
Rating: 4.67 out of 5  
 3 vote(s)

Here i have tried to explain the Cookie and ways of creating, accessing and deleting cookies.

Introduction


A Cookie is a small text file that is either saved on a client’s hard drive or client’s web browser. It contains site specific information that the server sends to the client along with the page output. The cookies are saved on the client device, and whenever the browser requests for a page, the information in the cookie is sent to the server by the client. The cookie is then read and its value is extracted by the server. Cookies are associated with a Web Site not with a specific page, so the browser and the server will exchange cookie information. Hence, it doesn’t matter which page the user requests from your site.

Required Namespace: System.Web


Advantages of Cookies: 



  1. They work transparently without the user being aware that information needs to be stored.

Disadvantages of Cookies:

  1. Most browsers support cookies of up to 4096 bytes.
  2. Most browsers allow only 20 cookies per site; if u try to store more, the oldest cookies are deleted.
  3. Some browsers also put an absolute limit, usually 300, on the number of cookies they will accept from all sites combined.
  4. Users can set their browser to refuse cookies.

 

There are two types of Cookies:

  1. Hard Cookies/Persisting Cookies/Permanent Cookies
  2. Soft Cookies/Non-Persisting Cookies/Temporary Cookies

 

Let me explain these types elaborately.

  1. Persisting Cookies – These cookies are stored in the hard disk of the client’s machine. Their expiry date and time can be configured.
  2. Non-Persisting Cookies – These cookies are stored in the client browser. As soon as the browser is closed, these cookies are destroyed. 

More than one value in a single Cookie

Multiple name value pairs can be stored in a single cookie. Here, the name-value pairs are referred as subkeys. Example : Instead of creating two separate cookies name UserName and EmailId, you can create a single cookie named ganeshji that has the sub-keys UserName and EmailId.

Before accessing the value of the cookie, you should make sure that the cookie exists; if the cookie doesn’t exist, you will get a NullReferenceException exception. The HtmlEncode method was called to encode the contents of the cookie and display it in browser.

Modify Cookies :


A cookie cannot be directly modified.  Only the way of modifying it is to create a new cookie  with the same name and with new values and then sending the cookie to the browser to overwrite the old version on the client.

Deleting Cookies :


A cookie cannot be directly removed, because the cookie is on the client’s Computer. You can make the browser to delete a cookie for you. Create a new cookie, with the same name as the cookie to be deleted and set the cookies expiration to a date earlier than today. On checking the cookie’s expiration, the browser will discard the outdated cookie.

Default.aspx

<table>

            <tr>

                <td>

                    <asp:Label ID="lblUserName" runat="server" Text="User Name"></asp:Label>

                </td>

                <td>

                    <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>

                </td>

            </tr>

            <tr>

                <td>

                    <asp:Label ID="lblEmail" runat="server" Text="Email Id"></asp:Label>

                </td>

                <td>

                    <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>

                </td>

            </tr>

            <tr>

                <td>

                    <asp:Button ID="btnCreate" runat="server" Text="Create Cookie" OnClick="btnCreate_Click" />

                </td>

                <td>

                    <asp:Button ID="btnDelete" runat="server" Text="Delete Cookie" OnClick="btnDelete_Click" />

                </td>

                <td>

                    <td>

                        &nbsp;

                    </td>

                    <td>

                        <asp:Label ID="lblMsg" runat="server"></asp:Label>

                    </td>

            </tr>

        </table>

Coding : Default.aspx.cs

protected void btnCreate_Click(object sender, EventArgs e)

    {

        if (Request.Cookies["ganeshji"] != null)

        {  

            //HtmlEncode encodes the value of a cookie before displaying it in the page

            lblMsg.Text = "Existing Cookie's UserName is "+Server.HtmlEncode(Request.Cookies["ganeshji"]["UserName"].ToString())+"
"+" and Email Id is "+Server.HtmlEncode(Request.Cookies["ganeshji"]["EmailId"].ToString()); } else { //Create the Cookie object HttpCookie obj = new HttpCookie("ganeshji"); //Set a value in it obj.Values["UserName"] = txtUserName.Text; //Add another value obj.Values["EmailId"] = txtEmail.Text; //This particular cookie's life time is 1 day obj.Expires = DateTime.Now.AddDays(1); //Add it to the current web response Response.Cookies.Add(obj); lblMsg.Text = "Cookie created successfully."; } } protected void btnDelete_Click(object sender, EventArgs e) { if (Request.Cookies["ganeshji"] == null) { lblMsg.Text = "Cookie doesn't exist."; } else { //Create the Cookie object HttpCookie obj = new HttpCookie("ganeshji"); //This particular cookie's expiration is set to a date earlier than today. obj.Expires = DateTime.Now.AddDays(-1); //Add it to the current web response Response.Cookies.Add(obj); txtUserName.Text = " "; txtEmail.Text = " "; lblMsg.Text = "Cookie deleted successfully."; } }



Following Snap shows the Cookie Created Message:




If the cookie already exists then the values are shown as follows:



Following Snap shows the Cookie Deleted Message:




Following Snap shows that no more cookie exist for deletion:


Cookies Stored in Client's Browser :


TOOLS->OPTIONS->PRIVACY->SHOW COOKIES






Click on localhost and find out the cookies saved in the Browser








REFERENCE:

http://www.codeproject.com/KB/aspnet/Beginners_Cookies.aspx


Page copy protected against web site content infringement by Copyscape

About the Author

Ganeshji
Full Name: Zinnia Sarkar
Member Level:
Member Status: Member
Member Since: 7/24/2010 12:50:40 PM
Country: India
Regards, Ganeshji


Login to vote for this post.

Comments or Responses

Posted by: Raja on: 7/27/2010
Very good small and cute article on cookie, keep it up Ganeshji!
Posted by: Akiii on: 5/26/2011 | Points: 25
excellent article........
keep posting.....

Thanks and Regards
Akiii
Posted by: Ganeshji on: 5/29/2011 | Points: 25
Many thnx Akii!

Login to post response

Comment using Facebook(Author doesn't get notification)