Cookie - DotNet and DataBase

Friday, 10 August 2018

Cookie



A cookie is a small information resides under the client machine/browser. The cookie is also a state management technique which is to store data in the client system for some days(as supplied by the developer) and temporarily as well.

The cookies are of two types.
1)Non-persistent cookie.
2)Persistent cookie.

Non-persistent(Temporary cookie) cookie
 Non-Persistent cookies are stored in the client's browser. These cookies retain the data until the web browser is running. 

Example:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
                    <td>
                        <asp:Label ID="lblUserName" runat="server" Text="UserName"></asp:Label></td>
                    <td>
                        <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox></td>
                </tr>
                <tr>
                    <td><asp:Label ID="lblPhone" runat="server" Text="Phone"></asp:Label></td>
                    <td><asp:TextBox ID="txtPhone" runat="server"></asp:TextBox></td>
                </tr>
                <tr>
                   
                    <td colspan="2" style="text-align:right">
                        <asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click" /></td>
                </tr>
            </table>
        </div>
    </form>
</body>

</html>

Code behind
using System;
using System.Web;

namespace WebProgramming
{
    public partial class CookieCreate : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnSend_Click(object sender, EventArgs e)
        {
            HttpCookie cookie = new HttpCookie("Userdetails");
            cookie["Name"] = txtUserName.Text;
            cookie["Phone"] = txtPhone.Text;
            Response.Cookies.Add(cookie);
        }
    }

}

HttpCookie is the constructor which takes cookie name which we user further to read cookie information.

Read Cookie

ASPX page
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CookieRead.aspx.cs" Inherits="WebProgramming.CookieRead" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
                    <td>
                       UserName: <asp:Label ID="lblUserName" runat="server" Text="UserName"></asp:Label></td>                   
                </tr>
                <tr>
                    <td>Phone Number: <asp:Label ID="lblPhone" runat="server" Text="Phone"></asp:Label></td>
                </tr>
            </table>
        </div>
    </form>
</body>

</html>

Code behind
using System;
using System.Web;

namespace WebProgramming
{
    public partial class CookieRead : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpCookie cookie = Request.Cookies["Userdetails"];
            if (cookie!=null)
            {
                lblUserName.Text = cookie["Name"];
                lblPhone.Text = cookie["Phone"];
            }
        }
    }

}

Before we assign cookie value to a variable, we need to check data exists in the cookie or not(if (cookie!=null)) otherwise, it causes expectation in case the cookie is null.

The data exist in the cookie(Request.Cookies["Userdetails"];) until the browser close. One browser close, this cookie deletes itself.





To maintain the cookie even after the browser close, we need to use  "Persistent cookie".

Persistent cookie
Persistent cookies are the cookies stored on the hard disk of the client computer as a text file which keeps the supplied data for some days defined by the developer.

To make the cookie persistent, we need to supply the expiry date to the cookie. Then, it remains in the browser for the supplied period of time (cookie.Expires = DateTime.Now.AddDays(5);
).

Codebehind
using System;
using System.Web;

namespace WebProgramming
{
    public partial class CookieCreate : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnSend_Click(object sender, EventArgs e)
        {
            HttpCookie cookie = new HttpCookie("Userdetails");
            cookie["Name"] = txtUserName.Text;
            cookie["Phone"] = txtPhone.Text;
            cookie.Expires = DateTime.Now.AddDays(5);
            Response.Cookies.Add(cookie);
            Response.Redirect("~/CookieRead.aspx");
        }
    }

}
Expiry period could be in different forms like days, months years etc..


Delete the cookie


protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Cookies["Userdetails"] != null)
            {
                Response.Cookies["Userdetails"].Expires = DateTime.Now.AddDays(-1);
            }

        }

Limitations:
  1. Can store only string
  2. Cannot store database objects like a dataset object.
  3. Most browsers support cookies of up to 4096 bytes.
  4. Most browsers allow only 20 cookies per site if we try to store more, the previous cookies are discarded
  5. The user might be set the browser not to accept the cookies
  6. The user can delete cookies.

When to use cookies and when to not
  1. When data is not critical importance
  2. We should not save the password in cookies
  3. We should not save any data in cookies which we don’t want to share with the user.
  4. As we discussed above to save the search criteria, that’s good, we can save these kinds of data




2 comments:

  1. Naga your explanation is very nice, and a small request from my side can you please provide the procedure and sample code for writing forgot password in asp actually ,i have tried this but it is throwing "5.5.1 authentication error the client is unauthorized " exception.

    ReplyDelete

x

Get Updates On

Discussion updates

Straight Into Your INBOX!

Enter your email address to subscribe to this website and receive notifications of new posts by email.