Tuesday, March 19, 2024

Creating and Using Cookies

 COOKIES

Cookie is a small text file which is created by the client's browser and also stored on the client hard disk by the browser. It does not use server memory. Generally a cookie is used to identify users.

A cookie is a small file that stores user information. Whenever a user makes a request for a page the first time, the server creates a cookie and sends it to the client along with the requested page and the client browser receives that cookie and stores it on the client machine either permanently or temporarily (persistent or non persistence). The next time the user makes a request for the same site, either the same or another page, the browser checks the existence of the cookie for that site in the folder. If the cookie exists it sends a request with the same cookie, else that request is treated as a new request.

Types of Cookies

1. Persistence Cookie: Cookies which you can set an expiry date time are called persistence cookies. Persistence cookies are permanently stored till the time you set.

Example to create persistence cookie

Response.Cookies[“name”].Value = “Vishwa Academy”;
Response.Cookies[“name”].Expires = DateTime.Now.AddMinutes(10);

In above code we use Response.Cookies object for create Cookie.
In above example we have set 10 Minute time for Expire Cookie, we can retrieve cookie values up to 10 minutes, after 10 minutes the cookies automatically expires.

2. Non-Persistence Cookie: Non persistence cookies are not permanently stored on the user client hard disk folder. It maintains user information as long as the user accesses the same browser. When user closes the browser the cookie will be discarded. Non Persistence cookies are useful for public computers.

Example to create non-persistnce cookie

HttpCookiestrname = new HttpCookie(“name”);
strname.Value = “Vishwa Academy”;
Response.Cookies.Add(strname);

Limitation of cookies: The number of cookies allowed is limited and varies according to the browser. Most browsers allow 20 cookies per server in a client's hard disk folder and the size of a cookie is not more than 4096 bytes or 4 KB of data that also includes name and value data. 

Creating Cookies:

 Type 1:

HttpCookie StudentCookies = new HttpCookie("studData");

StudentCookies.Value = TextBox1.Text;

StudentCookies.Expires = DateTime.Now.AddHours(1);

Response.Cookies.Add(StudentCookies);

 Type 2:

Response.Cookies["studData"].Value = TextBox1.Text;
Response.Cookies["studData"].Expires = DateTime.Now.AddDays(1);

 

Type 3:(Writing Multiple values in single cookie)

Response.Cookies["studData"]["RollNumber"] = TextBox1.Text;
Response.Cookies["studData"]["FirstName"] = "Vishwanath";
Response.Cookies["studData"]["MiddleName"] = "D";
Response.Cookies["studData"]["LastName"] = "Panchal";
Response.Cookies["studData"]["TotalMarks"] = "350";

Response.Cookies["studData"].Expires = DateTime.Now.AddMinutes(5);

 

Reading Cookies:

 

For Type 1 and Type 2

 string str1 = Request.Cookies["StudentCookies"].Value;

 

For Type 3

 string str1;

str1= Request.Cookies["StudentCookies"]["RollNumber"];
str1= str1 + " " + Request.Cookies["StudentCookies"]["FirstName"];
str1= str1 + " " + Request.Cookies["StudentCookies"]["MiddleName"];
str1= str1 + " " + Request.Cookies["StudentCookies"]["LastName"];
str1= str1 + " " + Request.Cookies["StudentCookies"]["TotalMarks"];
Label1.Text = str1; 

 

Example:

To Create Cookie ASPX File:

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="CreateCookie.aspx.cs" Inherits="CreateCookie" %>

 <!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></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        Enter Data: <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

        <br />

        <asp:Button ID="btnCreate" runat="server" Text="CreateCookeis"

            onclick="btnCreate_Click" />

    </div>

    </form>

</body>

</html>

 

To Create Cookie ASPX.CS File:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 public partial class CreateCookie : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

     }

    protected void btnCreate_Click(object sender, EventArgs e)

    {

        //Create Cookies

        Response.Cookies["mydata"].Value = TextBox1.Text;

        Response.Cookies["mydata"].Expires = DateTime.Now.AddMinutes(10);

        Response.Redirect("http://localhost:50618/WebSite18/ReadCookies.aspx");

    }

}

 

To Read Cookie ASPX File:

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ReadCookies.aspx.cs" Inherits="ReadCookies" %>

 

<!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></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

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

    </div>

    </form>

</body>

</html>

 

To Read Cookie ASPX.CS File:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 public partial class ReadCookies : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        string str;

        str = Request.Cookies["mydata"].Value;

        Label1.Text = "Your Cookie Data is " + str;

    }

}