Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | ASP.NET 2.0 Tutorials | Web Services | How Do I...? | Class Browser | WPF Quick Starts | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Gauge for SharePoint
Search :       Advanced Search »
Home » ASP.NET 2.0/3.5 » How to create cookie? Why we use cookie?

How to create cookie? Why we use cookie?

This article is showing that how and why we use cookie.

Author Rank :
Page Views : 14693
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Team Foundation Server Hosting
Become a Sponsor
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Description of Cookie

 

Cookie object is used to store the sort amount of data onto client end. It executes on server and resides on client browser.

 

When any user request first time for any web application then the web server generate an unique session id  that is farther send back to client in the form of cookies. This cookie is known as the session cookie or default cookie and the name of the cookie is asp.net_session id.

 

The default time for cookie existence on the browser when the browser will close cookie will expired (in case of session cookie).

 

Cookies are domain specific that is when the domain of web application will be change cookie will be change.

 

To store data in a cookie is not secure due to it's location at client end. Cookie was introduced with first version of Netscape navigator (that was 1.0).
 

There are two type of cookie:

  • Session cookie  
  • Persistent cookie

Session cookie can not store on the hard disk and Persistent cookie can be store on the hard disk.

It can be found as-

C/: document and setting/user profile/cookie

We can create cookie manually using http cookie class.Asp.net supports the multi values cookie. Numbers of cookies are depending on the domain, space on hard disk.

If cookie less property is check in browser that is browser does not support cookies there server create cookie less server that is the session id is upended into browser URL.

To write a cookie by creating an instance of the Http Cookie object:

  • Create an object of type Http Cookie and assign it a name. 
  • Assign values to cookie's sub keys and set any cookie properties.
  • Add the cookie to the Cookies collection.  

HttpCookie ck1, ck2;

protected void Button1_Click(object sender, EventArgs e)

    {

        ck1 = new HttpCookie("cookiename1", TextBox1.Text);

        ck2 = new HttpCookie("cookiename2", TextBox2.Text);

        Response.Cookies.Add(ck1);

        Response.Cookies.Add(ck2); 

    }

 

Here we  are creating two cookies and  storing the information in those cookies and we are accesing the values of those both cookies on another page.

 

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

 

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

{

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

    HttpCookie ck1,ck2;// Here we are creating the instance of cookie

 

    protected void Button1_Click(object sender, EventArgs e)

    {

        ck1 = new HttpCookie("xx",TextBox1.Text); // here we are storing the  value in a cookie

        ck2 = new HttpCookie("yy",TextBox2.Text);

        Response.Cookies.Add(ck1); 

        Response.Cookies.Add(ck2);

        Response.Redirect("new webform.aspx");// redirect to another page

    }

}

 

Second page coding to access the value of cookies from previous page

 

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

 

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

{

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

    protected void Button1_Click(object sender, EventArgs e)

    {

        TextBox1.Text = Request.Cookies["xx"].Value;

        // Accessing the values of cookies in a text box

        TextBox2.Text = Request.Cookies["yy"].Value;

    }

 

    // To show the no. of cookies

    protected void Button2_Click(object sender, EventArgs e)

    {

        foreach (string str in Request.Cookies)

        {

            Response.Write(str + "=" + Request.Cookies[str].Value + "<br>");

        }

    }

} 

 

The following files are generete when cookie  creates.

  • App_data
  • .aspx(asp.net server page)
  • .aspx.cs (visual c# source file)
  • Web.config(xml configuration file)

Authentication:

  • Cookies can be used to recognize authenticated users by a server This can be done for example as follows:User enters username and password in the text fields of a login page and sends them to the server.
  • The server receives username and password and checks them; if correct, it sends back a page confirming that login has been successful together with a cookie, storing the pair user/cookie . 
  • Every time the user requests a page from the server, the browser automatically sends the cookie back to the server; the server compares the cookie with the stored ones; if a match is found, the server knows which user has requested that

Why we use Cookie ? 

  • To collect demographic information about who is visiting the Web site. Sites often use this information to track how often visitors come to the site and how long they remain on the site.
  • To monitor advertisements. Web sites will often use cookies to keep track of what ads it lets you see and how often you see ads.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Purushottam Rathore

I am working as a Software Developer and has 4 years of experience on Microsoft Technology and having a Master Degree in Computer Application. I really like to work in the .NET platform. and working with ASP.NET 2.0/3.5, Web Services, WPF, WCF, Silverlight, AJAX, JavaScript, JQuery, Ado.net, MsAccess, SQL Server 2005/2008.

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.