MY PRINCIPAL :- "THE GLORY OF LIFE ID TO LOVE NOT TO BELOVED...TO GIVE NOT TO GET..TO SERVE NOT TO BE SERVED."

Friday, December 10, 2010

ASP.Net State management Techniques.(Coockies)



Coockies:-


    -coockies are the concept of browser/http not any technologies like .Net,Java,php etc.
    -coockies are domain specific i.e. travelled between every request/response when requested from          particular domain.
    -Coockie is the name-value pair travel between every request/response and optionally stored also.
    -As coockies are browser/client based, only browser has rights to enable or disable the coockies.
    -we can store only simple/text data in coockie not any objects.
    -For every site there is only 20 coockies are allowed(standerd i.e. we can go beyond that depending on browser)
    -data in the coockies size upto 1mb(std).
    -For every domain 200 coockies are allowed.
    -For the developer to use coockie is the better option when there is no security issue because it has the ability to travel between every request/response.
    -We must not store critical information in the coockies (ex-credentials,passward).it may be tampered by hackers.
    -The default time for coockie is 30 days.
   
Types of Coockies:-

    There are two types of coockies.
     a. In-memory Cockie.
        b. Persistance Coockie.

a. In-Memory coockie:- These coockies are available whenever the user online or working with application      and stored in RAM of users computer.Once user log out or close the browser these coockies automatically get vanished.

b. Persistance Coockies:- These coockies are availble wheather user online or offline. It get stored in hard disk. suppose when we visit the same site again then browser itself search for that coockie in stored location specified and reads the coockie information. EX. Remember me checkbox.
-To make our coockie as Persistance store, we have to specify the time for that coockie.


Declaration and Syntax:-

single valued coockie:

        HttpCoockie ckobj=new HttpCoockie("Coockie name");
        ckobj.value="preference";
        Response.coockies.add(ckobj);

multivalued coockie:

It is single coockie for the browser but for us it is multivalue coockie.

        HttpCoockie ckobj=new HttpCoockie("Coockie name");
        ckobj.values="preference1";
        ckobj.values="preference2";
        ckobj.values="preference3";
        Response.coockies.add(ckobj);

Now, How to Read Coockies:

        if(Request.Coockies("Coockie name")!=Null)
        {
            string str=Request.Coockies["coockie name"].value;
        }

How to specify the  for coockies: ckobj.Expires(DateTime.Now.AddDays(10));

       
Now we will see the real time example of Coockies i.e. changing the Country preferences. You might have seen on the website that they are having
country preferences usually on top right of page.We are going to see that example here only.

ex: Create an application with one dropdown list and bound it to class containing the country list from database or static and one button on it.Onclick of button redirect the user to another page saying "your preference has been save".

Design;

Coding:


 1. DBHelper.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for DBHelper
/// </summary>
public class DBHelper
{
    public DBHelper()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    public static List<string> GetCountries()
    {
        List<string> country = new List<string>();
        country.Add("India");
        country.Add("Pakistan");
        country.Add("Australiya");
        country.Add("Newzeland");
        country.Add("Srilanka");
        country.Add("Bangladesh");

        return country;
    }
}
------------------------

2. Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default"  EnableViewStateMac="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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div style="text-align: center; font-weight: 700; color: #FF3300">
   
        Select Your Preference:
        <asp:DropDownList ID="DropDownList1" runat="server">
        </asp:DropDownList>
        <br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click"
            Text="Set Preference" />
   
    </div>
    </form>
</body>
</html>
---------------------
3. Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DropDownList1.DataSource = DBHelper.GetCountries();
            DropDownList1.DataBind();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string strpreference = DropDownList1.SelectedValue;
        HttpCookie ckobj = new HttpCookie("Country");
        ckobj.Value = strpreference;
        ckobj.Expires = DateTime.Now.AddDays(10);
        Response.Cookies.Add(ckobj);
        Response.Redirect("~/Default2.aspx");
    }
}
-----------------------

4. default2.aspx

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

<!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>
   
        &nbsp;&nbsp;&nbsp;&nbsp; Your preference has been saved as:
        <asp:Label ID="Label1" runat="server"></asp:Label>
   
    </div>
    </form>
</body>
</html>
-------------------
5. Defalut2.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Cookies["country"] != null)
        {
            Label1.Text = Request.Cookies["country"].Value;
        }

    }
}
---------------------------


Now two Practice example for you guys:

ex:2- Create an application Which will contains one shopping cart and save all the data in coockies for ex. product information and when
      user login next time show its purchased products. (use your own logic to developed shopping cart).

ex:3- create an application which will take input from user i.e. username and passward and do login. when the user log in and checks checkbox
      remember me then create coockie containing username only and show that username in username textbox when the user log in next time(make persistance coockie)