settembre 24, 2009

- Programming Asp.Net: Beginner's Guide to ASP.NET Cookies

Introduction

Cookies, Session, and Application Object are in Queue. Now, It's time for reading about cookies. I have spend a lots of times to prepared this article. And you will be very surprised to know that Introduction part is the last topic which I am writing before posting article. I have read many articles, books before writing this article. Done some hands on also. Hope I have explained this well , and hope you people also like it. Please give your suggestion and feedback.

What are Cookies ?

Cookies are the small files that are created on the client's system or client browser memory (if temporary). Its use for State management that I have already discuss on my view state article. So we can store small piece of information in a client system and we can use it when we needed. Most interesting thing is that Its works transparently with the user. It can be easily used any where of you web application. Cookies store information in a plain text format. If any web application using cookies, Server send cookies and client browser will store it. The browser then returns the cookie to the server at the next time the page is requested. The most common example of using a cookie is to store User information, User preferences , Password Remember Option etc. Cookies has many advantages and disadvantages. I will comes to this points , but first have a look how cookies are started.

How Cookies are started ?

When client request to the server, server send the cookies into client . The same cookies can be referred for subsequent request. As for example, if codeproject.com stores session id as a cookies, when any client hits first times on the server, server generates the session id and send it as a cookies to client. [As given in Fig 1.0]

Cookie1.jpg

Fig 1.0 : Initial state of cookie creation

Now for all other subsequent from the same client it uses the session-id from cookies, just like the picture below:

Cookie2.jpg

Fig 1.1 : Subsequent request for other pages

Browser and web server are responsible for exchange cookies information. For different sites, browser keeps cookies differently. If any pages need information from cookies, when that URL is being hit, first its search for local system for cookies information then its moved to server with that information.

Advantages of Cookies

Following are main advantages of using cookies in web application:

  • It's very simple to use and implement.

  • Browser's taking care send data.

  • For multiple sites cookies, Browser automatically arranges them.

Disadvantages of Cookies

Main disadvantages of cookies are:

  • Its store data in a simple text format. so it's not secure at all.

  • There is a size limit of cookies data ( 4096 bytes / 4KB).

  • Number if cookies also limited. Most Browser provides limits of storing cookies is 20. If new cookies came, it will discard the old one. Some of browser support up to 300.

  • We need to configure browser. It will not work on a high security configuration of browser. [I have explained about this in details.]

How to create cookies ?

For working with cookies we need to use namespace System.web

Cookie3.gif

Now , have a look, on the code , that how can we create a cookies and add it with web response .3

Cookie4.gif

The cookies which has been created will persist , until browser has been closed. we can persist the cookies. But how? Just after few point I have discussed it.

How to Read data from cookies ?

Now , its times to retrieve data from cookies. Ok, before reading cookies, first of all we need to check whether a cookies was found or not. "Its always good practice to check cookie before read it, because is browser is disable cookies.

Cookie7.gif

What is Persistent and Non Persistent Cookies ?

We can classified cookies in two way,

  • Persistent Cookies

  • Non Persistent Cookies

Persistent Cookies : This can be called as permanent cookies, which is stored in client hard-drive until it expires . persistent cookies should have set with expiration dates.How to make Persist Cookies ?" section. Sometimes its stays until the user deletes the cookie. Persistent cookies are used to collect identifying information about the user from that system. I have discuss about the creation of persistent cookies on "

Non Persistent Cookies : This can be called as Temporary Cookies. If there is no expires time defined then the cookie is stored in browser memory . The Example which I have given already its a Non-Persistent Cookies.

Therefore there is no difference between modifying persistent or non-persistent cookies. Only difference between them are Persistent cookies should have an Expatriation time defined within it.

How to make Persistent Cookies ?

I have already given an example of non-persistent cookies, For Persistent cookies we need only add to expiry times of cookies. In that given code I have added Expire time to 5 days. Just check the example.

Collapse code snippet
        //Creting a Cookie Object
HttpCookie _userInfoCookies = new HttpCookie("UserInfo");

//Setting values inside it
_userInfoCookies["UserName"] = "Abhijit";
_userInfoCookies["UserColor"] = "Red";
_userInfoCookies["Expire"] = "5 Days";

//Adding Expire Time of cookies
_userInfoCookies.Expires = DateTime.Now.AddDays(5);

//Adding cookies to current web response
Response.Cookies.Add(_userInfoCookies);

Now , Looks the most interesting things that where they are store in hard drive.

Where does cookies are stored in local Hard drive ?

This is one of the interesting things to find out the cookies in your local drive. First of all, From "Explorer Folder Option ", Select, show hidden files and folder.

Cookie8.jpg

Fig 1.2 : Show Hidden files and Folder Settings

Now Browse into document & settings of the current user and open the cookies folder. Now looks the picture.

Cookie9.jpg

Fig 1.3 : Reading Cooking info in local System

How to remove a persistent cookies before it's Expiration time ?

This is also a funny task. If you want to remove some persistent cookies before its Expiration date, the only way to replacing the cookies with some before expiration date.

Collapse
        HttpCookie _userInfoCookies = new HttpCookie("UserInfo");
//Adding Expire Time of cookies before existing cookies time
_userInfoCookies.Expires = DateTime.Now.AddDays(-1);
//Adding cookies to current web response
Response.Cookies.Add(_userInfoCookies);

How to control cookies Scope ?

We can controlling the scope of cookies by following way

  • Limiting Cookies to Path

  • Limiting Cookies Domain

What is Cookie Munging?

By Default ASP.Net uses cookies to stores session ID's , but I have already discuss some browser does not support cookies, To over comes this problem, ASP.NET uses "Cookie Munging" to manages session variable with out cookies.

[Though this is also related with Session, I am just giving a Basic overview. I will explain it in details on my Next article which will be on session.]

Why we are using Cookie Munging in ASP.NET ?

There are some specific reason to use cookie munging in ASP.NET

  • Some Browser does not support cookies.

  • Sometimes, user disable cookies in Browser.

How Cookie Munging Works ?

When user request for a page on a server, Server encoded the session id and add it with every href link in page. When user click any links ASP.NET decodes that session id and passes it the page that user requesting. Now the requesting page can retrieve any session variable. This all happens automatically, if ASP.NET detects that the users browser does not support cookies.

Cookie10.jpg

Fig 1.4 : Steps of Cookie Munging

How to Implement Cookie Munging ?

For that we have to make session state to Cookie less.

Collapse
<sessionState cookieless= "true />

Ooo... Now I am stopping here on this topic. I will explain it in details when I write an article of Session.

How to Configure cookies in Browser ?

Now, we can just have a look on how can we configure browser for enabled /Disabled cookies. Here I have discussed about settings of IE Browser. Click on Tool -> Internet Option -> Go To Privacy Tab. There you will able to see a scroll bar, with following options

  • Accept All Cookies

  • Low

  • Medium

  • Medium High

  • Block All Cookies

Test.gif

First option will Accepts All cookies and Last Option Will block all cookies. you can get the details of those settings while scrolling the bar.

Summary

There are many topics to learn with cookies . I have covered a small portion hope this will helps all the beginners to startup. Please give your feedback and suggestion.

Nessun commento:

Posta un commento