X



Home>Tutorial>

What is Cookies, Types of Cookies and Examples of Cookies

Nuelson Penuel Friday, August 28, 2020 ASP.Net

Introduction

In this post, I am going to discuss with you what is cookies in asp.net. I will show you how to preserve information even after postback

What is Cookies?

Cookie is an ASP.Net state management technique that is used to store information on client side even after a postback occurs. Cookie can be used to store user-specific information on the client's system like the last a user visit your site. For more about state management, check here In order words, a cookie is a small piece of data stored on the client's's device by the web browser while browsing a website. Cookies are also known to have many names like HTTP Cookies, Browser Cookies, Web Cookies, Session Cookies and so on. Cookies were designed to be a reliable mechanism for websites to remember stateful information or to record the user's browsing activity.

Types of Cookies

There are two types of cookies which are persistent and non-persistent cookie

Persistent Cookies

These are cookies stored on a user’s device in order to remember user's information, preferences, or username and password that a user has previously saved. This helps create a convenient and faster website experience. These cookies have an expiration date issued to it by the webserver. Basically, this type of cookie is saved on your computer so when you close it and start it up again, the cookie is still there. Once the expiration date is reached, it is destroyed by the owner. Persistent cookies can be used by webmaster to 1. Track visitors as they move around the website, 2. Figure out what people like about the website and 3. Improve the user experience. A very good example of persistent cookie is Google analytics.

Non-Persistent Cookies

Non-persistent cookies are not permanently stored i.e they are temporary. They can also be called in-memory cookies or session-based cookies. These cookies are active as long as the browser remains active, in other words if the browser is closed then the cookies automatically expire.

Advantages of Cookies

1. Cookies are simple to use and implement 2. They do not require any server resources 3. They are stored on the user’s device 4. They are light in size, so they occupy less memory and you do not need to send back the data to the server . 5. They leverage server resources 6. Cookies are persistent in nature until cleared by user or deleted by web server

Disadvantages of Cookies

Though cookies leverage website resources, it also have disadvantages. Some are outlined as follows; 1. Size limitation: Individual cookies is restricted to only 4kb of information 2. Complex data cannot be stored in cookies 3. Cookies data are easy to access and can easily be manipulated 4. Cookies are useless if the client disable cookies 4. Most browsers only allow maximum of 20 cookies In this example, the program will write to cookies, read from cookies and delete from cookies Here is the HTML source of the program
<%@ Page Language="VB" AutoEventWireup="true"  CodeFile="Default.aspx.vb" Inherits="_Default" EnableViewState="false" Debug="true" Trace="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Cookies Example</title>
    </head>
    <body>
        <form id="form1" runat="server">
<asp:Label ID="lblstatus" runat="server" Text="" /><br/>
            <div>Username<br/>
                <asp:TextBox ID="txtusername" Text="" runat="server"/><br/>
Password<br/>
                <asp:TextBox ID="txtpassword" Text="" runat="server"/><br/>
 <asp:Button ID="btnsavePersist" runat="server" Text="Save As Persistent Cookie" />
<asp:Button ID="btnsaveNonPersist" runat="server" Text="Save As Non-Persistent Cookie" />
                <asp:Button ID="btnRead" runat="server" Text="Read" />  <asp:Button ID="btndelete" runat="server" Text="Delete" />
            </div>
        </form>
    </body>
</html>
Here is the code behind to write or save to cookies. When this button is click, the person's username and password will be saved to cookie. Recall, we talked about persistent and non-persistent cookie. So I have demonstrated both here. Here is the code for persistent cookie writing;
Protected Sub btnsavePersist_Click(ByVal sender As Object, ByVal e As EventArgs) 
    If txtusername.Text = String.Empty And txtpassword.Text = String.Empty Then
       ScriptManager.RegisterStartupScript(Page,Page.GetType(),"mykey","alert ('Enter username and password');",True)
   Else
      CreatePersistentCookie()
End If
End Sub
Here is a subroutine function that will be called by the savePersist button.
Sub CreatePersistentCookie()
Dim cookieEx As New HttpCookie("info")
cookieEx.Value.Add("uname",txtusername.Text)
cookieEx.Value.Add("pwd",txtPwd.Text)
cookieEx.Expires = Date.Now.Adds(7) 'cookies that expires in 7 days
Response.Cookies.Add(cookieEx)
Here is the code for non-persistent cookie writing;
Protected Sub btnsaveNonPersist_Click(ByVal sender As Object, ByVal e As EventArgs) 
    If txtusername.Text = String.Empty And txtpassword.Text = String.Empty Then
       ScriptManager.RegisterStartupScript(Page,Page.GetType(),"mykey","alert ('Enter username and password');",True)
   Else
      CreateNonPersistentCookie()
End If
End Sub
Here is a subroutine function that will be called by the saveNonPersist button.

Sub CreateNonPersistentCookie()
Dim cookieEx As New HttpCookie("info")
cookieEx.Value.Add("uname",txtusername.Text)
cookieEx.Value.Add("pwd",txtPwd.Text)
Response.Cookies.Add(cookieEx)
You might be wondering what is the difference between Persistent and Non-persistent code here. The difference is clear, in Non-persistent, there is expiration declared. Now that you have know how to write cookies, let us see how we can get their values as the computer can't just output the cookies value without you given command. Copy or type this code in btnRead click event
Protected Sub btnRead_Click(ByVal sender As Object, ByVal e As EventArgs) 
    If Not Request.Cookies("info")("uname").Value Is Nothing Then
      Dim uname As String = String.Empty
Dim pwd As String = String.Empty

uname = Request.Cookies("info")("uname").Value
pwd = Request.Cookies("info")("pwd").Value
 ScriptManager.RegisterStartupScript(Page,Page.GetType(),"mykey","alert ('Username: ' + uname + ' Password: ' + pwd + ');",True)

lblstatus.Text = "Username: " &  uname &  " Password: " & pwd
   Else    ScriptManager.RegisterStartupScript(Page,Page.GetType(),"mykey","alert ('No information saved yet');",True)
lblstatus.Text ="No information saved yet"
End If
End Sub
To delete cookies values is not possible cos you don't have access to the client system. However, there is a way to achieve this by recreating the cookie and setting expiration date.
Protected Sub btndelete_Click(ByVal sender As Object, ByVal e As EventArgs) 
    If Not Request.Cookies("info")("uname").Value Is Nothing Then
      
Dim cookieEx As New HttpCookie("info")
cookieEx.Expires = Date.Now.Adds(-1) 'delete cookies
Response.Cookies.Add(cookieEx)

     Else    ScriptManager.RegisterStartupScript(Page,Page.GetType(),"mykey","alert ('No information saved yet');",True)
lblstatus.Text ="No information saved yet"
End If
End Sub
For suggestions and improvement, let me know on the comment section

| | Views(796)

See Demo | Download File


Add your comment. Indicate code using code tag


Words: 0 | Chars: 0 | Reading Duration: 0



Images Attachment




Emmason Integratded Services(2017-2024)
All Rights Reserved
Designed and Maintained By Emmason Integrated Services