Search content within the blog

Thursday, July 28, 2011

Managing cookies in WPF

A cookie is an arbitrary piece of data that can be stored by an application on the client machine during application sessions (session cookies) or across application sessions (persistent cookies). You can create both types of cookies by calling SetCookie.

Cookie data typically takes the form of a name/value pair in the following format:

Name=Value

You pass a string of this format to SetCookie, along with the Uri of the location for which the cookie should be set (typically, the application domain).

Whether a cookie is a session cookie or a persistent cookie depends on whether the cookie string that you pass to SetCookie includes an expiry date. The string for a session cookie does not include an expiry date. The string for a persistent cookie does, and must be in the following format:

NAME=VALUE; expires=DAY, DD-MMM-YYYY HH:MM:SS GMT

Persistent cookies are stored in the current Windows installation's Temporary Internet Files folder until they expire, in which case they are deleted. You can delete a persistent cookie from your application by setting its expiry date to a date/time value that is in the past.


Code snippet in Listing 1 creates two cookies using SetCookie method. One is a session cookie and other is a persistent cookie.

string simpleCookie = "CSCUser1=Mahesh";
string cookieWithExpiration = "CSCUser2=Mahesh;expires=Sat, 10-Oct-2012 00:00:00 GMT";


Listing 1
Uri cookieUri1 = new Uri(@"C:\Junk\SimpleMC");
Uri cookieUri2 = new Uri(@"C:\Junk\PersMC");

Application.SetCookie(cookieUri1, simpleCookie);
Application.SetCookie(cookieUri2, cookieWithExpiration);


Application.GetCookie method retrieves cookie data from the given Uri.
The code listed in Listing 2 uses the GetCookie method to get the cookie data and displays it in a MessageBox.

Listing 2
Uri cookiePath = new Uri(@"C:\Junk\SimpleMC");
string cookie = Application.GetCookie(cookiePath);
MessageBox.Show(cookie);

No comments:

Post a Comment