Saturday, 4 August 2012

State Management in ASP.NET part-1 (Cookies)

Hi,

I am Back with State Management Series.
In this post we are going to Talk about Cookies. After Reading this, you must be able to do following things:

  • Create Cookie
  • Access Cookie
  • Can answer Some Basic Q & A about Cookie
What is Need of Cookie?
Cookies are Required to Store Temporary data in Users system which may be Required during Session or after Session.
How Many Type of Cookie are there?
Cookies are generally of Two Type. Session wide or Persistent. Sessional cookies Expire as soon as User Closed Session means Browser. Persistent cookies expire after Defined Time. This can be Defined at the Time of Creation.
Who Make Cookies?
Cookie is always made by Application (Server) in Users/ Clients Browser and stored in Hard Disk of User. These are used to store Users Customized Appearance, other Values , Login Time etc for future Retrieval so that website can server him better.
Limitations of Cookie?
  • Cookies are open Invitations to Hackers.
  • Cookies can only store Little and Only String Type Data.
Now Lets Learn with Coding. First We will Create a Cookie named myCookie and Solve Earlier Problem with the Help of Cookie.

Now Code is Like Below:
 protected void Page_Load(object sender, EventArgs e)
    {

    }
    int x;    // Made a Variable with Datatype Int for Future Use
    HttpCookie myCookie;   // Defined a Cookie named myCookie.
    protected void Button1_Click(object sender, EventArgs e)
    { 
        x = Convert.ToInt32(TextBox1.Text);  // Converted textbox Value which we earlier Did.
        myCookie = new HttpCookie("txtValue");  // Assigned Variable myCookie.
        myCookie.Value = Convert.ToString(x);   // Value assigned to myCookie.
        Response.Cookies.Add(myCookie); //This Simple Made a Cookie that will Expire in Session End.
        myCookie.Expires = DateTime.Now.AddMinutes(15);  // We made is Persistent and stored it for Next 15 minutes.
      
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
       
        HttpCookie storedCook = Request.Cookies["txtValue"];  // Requested from Server for Cookie
        if (storedCook != null)  
            x = Convert.ToInt32(storedCook.Value);  // Converted to Integer again.
        TextBox1.Text = Convert.ToString(x * x);    // Now Printed Value in Textbox.
    }
Now Check....
Cool na, I'll be waiting for Feedback.

No comments:

Post a Comment

Popular posts