Showing posts with label Cookies. Show all posts
Showing posts with label Cookies. Show all posts

13 March 2014

Cookies in asp.net



Cookies are small pieces of text, stored on the client's computer to be used only by the website setting the cookies. This allows webapplications to save information for the user, and then re-use it on each page if needed. Here is an example where we save a users choice of background color:


<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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</title>
</head>
<body runat="server" id="BodyTag">
    <form id="form1" runat="server">
    <asp:DropDownList runat="server" id="ColorSelector" autopostback="true" onselectedindexchanged="ColorSelector_IndexChanged">
        <asp:ListItem value="White" selected="True">Select color...</asp:ListItem>
        <asp:ListItem value="Red">Red</asp:ListItem>
        <asp:ListItem value="Green">Green</asp:ListItem>
        <asp:ListItem value="Blue">Blue</asp:ListItem>
    </asp:DropDownList>
    </form>
</body>
</html>


The page simply contains a DropDownList control, which automatically posts back each time a new item is selected. It has 3 different colors, besides the default one, which is simply white. Once a new item is selected, the ColorSelector_IndexChanged method is fired, from our CodeBehind file:

using System;
using System.Data;
using System.Web;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(Request.Cookies["BackgroundColor"] != null)
        {
            ColorSelector.SelectedValue = Request.Cookies["BackgroundColor"].Value;
            BodyTag.Style["background-color"] = ColorSelector.SelectedValue;
        }
    }

    protected void ColorSelector_IndexChanged(object sender, EventArgs e)
    {
        BodyTag.Style["background-color"] = ColorSelector.SelectedValue;
        HttpCookie cookie = new HttpCookie("BackgroundColor");
        cookie.Value = ColorSelector.SelectedValue;
        cookie.Expires = DateTime.Now.AddHours(1);
        Response.SetCookie(cookie);
    }
}
Okay, two different parts to be explained here. First, the Page_Load method, which is called on each page request. Here we check for a cookie to tell us which background color should be used. If we find it, we set the value of our dropdown list to reflect this, as well as the background color of the page, simply by accessing the style attribute of the body tag. 

Then we have the ColorSelector_IndexChanged method, which is called each time the user selects a new color. Here we set the background color of the page, and then we create a cookie, to hold the value for us. We allow it to expire after one hour, and then we set it by calling the SetCookie method on the Response object. 

Try running the example, and set a color. Now close the browser, and start it up again. You will see that the choice of color is saved, and it will remain saved for an hour. However, nothing prevents you from saving the choice for much longer. Simply add a bigger value to the expiry date, or set an absolute value for it.

27 February 2014

How To Create And Read Cookies In Asp.Net And C#.Net

Cookies store user information in a text file and stored on user hard drive.here are some exmaples of how we can create cookies and read from them.

Creating Induvisual cookies

Indivisulal cookies are cookies which can store only single value

First way to create cookie Indivisulal (using Response object)

Response.Cookies["un"].Value = TextBox1.Text;
Response.Cookies["un"].Expires = DateTime.Now.AddMinutes(10);

Second way to create cookie Indivisulal (using HttpCookie Class)

HttpCookie ck = new HttpCookie("un1", TextBox1.Text);
ck.Expires = DateTime.Now.AddMinutes(10);Response.Cookies.Add(ck);

Reading from indivisual cookies

Response.Write(Request.Cookies["un"].Value);
//or
HttpCookie d = Request.Cookies["un1"].Value;Response.Write(d.Value);

Creating Sub-Key cookies
//First Method
Response.Cookies["myckk"]["un"] = TextBox1.Text;
Response.Cookies["myckk"]["up"] = TextBox2.Text;
Response.Cookies["myckk'"].Expires = DateTime.Now.AddMinutes(10);

//Second method 
HttpCookie ck = new HttpCookie("myckk");
ck.Values.Add("un", TextBox1.Text);
ck.Values.Add("up", TextBox2.Text);
ck.Expires = DateTime.Now.AddMinutes(10);
Response.Cookies.Add(ck);
Response.Redirect("Default2.aspx");

Reading Sub-Key cookies

//First Mehtod ( with Request object)
Response.Write(Request.Cookies["myckk"]["un"].ToString());
Response.Write(Request.Cookies["myckk"]["up"].ToString());
Response.Redirect("Default2.aspx");

//Second Method
HttpCookie ck = Request.Cookies["myckk"];
Response.Write(ck.Values["un"].ToString());
Response.Write(ck.Values["un"].ToString());
Try it