Managing Cookies in a WPF Application using VB.NET
A cookie is a piece of data that is stored on a user's machine. Cookies are usually used on Browser applications.
There are two types of cookies - session cookies and persistent cookies. Session cookies data is available during an application session only and once the session is expired, the cookie is deleted.
Persistent cookies on the other hand are stored in the Temporary Internet Files folder and can be stored for longer time and the life time of these cookies are set within the cookie data as an expiration date and time.
A cookie data is in the name and value pair format where NAME=VALUE. Here is an example of a cookie data.
If a cookie data has expires data followed by a semi colon in it, it is considered as a persistent cookie. Here is an example of a persistent cookie. Here is the format of a persistent cookie.
NAME=VALUE; expires=DAY, DD-MMM-YYYY HH:MM:SS GMT
Here is an example of a persistent cookie data.
"UserName=Mahesh; expires=Friday, 10-Dec-2010 00:00:00 GMT"
Application.SetCookie method creates a cookie on users' machine. This method takes two parameters - an Uri and a string. The first parameter, the Uri specifies a location where the cookie will be created at and second parameter is a cookie data.
Code snippet in Listing 1 creates two cookies using SetCookie method. One is a session cookie and other is a persistent cookie.
Dim simpleCookie As String = "CSCUser1=Mahesh"
Dim cookieWithExpiration As String = "CSCUser2=Mahesh;expires=Sat, 10-Oct-2012 00:00:00 GMT"
Dim cookieUri1 As New Uri("C:\Junk\SimpleMC")
Dim cookieUri2 As New Uri("C:\Junk\PersMC")
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.
Dim cookiePath As New Uri("C:\Junk\MC")
Dim cookie As String = Application.GetCookie(cookiePath)