In Silverlight, one can access cookies through the 'HtmlPage' class. This class provides browser functionalities and other details like Cookie data, Browser name and version, Popup Window, Platform, UserAgent, Product name and version. Below is a diagram illustrating how the Silverlight plug-in access cookies through the browser. In traditional web programming, the Response Object or java script is used to set a cookie. A user can disable cookies on his browser, so while using the response object we should check if cookies are enabled or not. To verify if cookies are enabled, set a cookie and try to read it back, if you can't read it means cookies are disabled. Silverlight code executes on client PC, so we can directly check if cookies are enabled or not just by using 'HtmlPage.BrowserInformation.CookiesEnabled'.
Securing cookie data is very important and should be take in account during application design. To prevent unauthorized access of cookies, combination of tricks can be used like encryption, expiration time, HttpOnly,etc. Silverlight code executes on client PC and cannot access HttpOnly cookies. Cookie class is a part of 'System.Net' and is used to retrieve information about cookies that are received with Http responses. Cookies are stored in a CookieContainer on a Web request, and a CookieCollection on a Web response. You must always create a CookieContainer to send with a request if you want cookies to be returned on the response, also for HTTPOnly cookies.
Limitation if a cookie is that it can store only string data types.
1) Some user may disable cookies on their browser in some case user may manually delete cookies
2) Size limitations Most browsers place a 4096-byte limit on the size of a cookie, although support for 8192-byte cookies is becoming more common in newer browser and client-device versions.
3) User-configured refusal Some users disable their browser or client device's ability to receive cookies, thereby limiting this functionality.
4) Potential security risks Cookies are subject to tampering. Users can manipulate cookies on their computer, which can potentially cause a security risk.
I have created a simple class that aggregates common functionality related to cookies. All members in the class are static so there is no need to create new instances every time you read or write a cookie. The overloaded method SetCookie() will create a new cookie or reset the value of an existing cookie, you can also set the expiration time, path, domain, security using the same method. GetAllCookieList() method will return a list of all available cookies. DeleteCookie() method will delete the cookie by setting the expiration time to yesterday. GetCookieAsString() will return the full cookie data as a string.
- using System;
- using System.Net;
- using System.Text;
- using System.Linq;
- using System.Collections.Generic;
- using System.Windows.Browser;
- namespace Utilities
- {
- public static class CookieManager
- {
- // 1) If same name cooke exist, SetCookie() will over-ride value.
- // 2) Exception handling should be done in user code
- // 3) - expireDays = 0, indicates a session cookie that will not be written to disk
- // - expireDays = -1, indicates that the cookie will not expire and will be permanent
- // - expireDays = n, indicates that the cookie will expire in n days
- public static bool IsCookieEnabled()
- {
- return HtmlPage.BrowserInformation.CookiesEnabled;
- }
- public static bool SetCookie(string key, string value)
- {
- return SetCookie(key, value, null, null, null, false);
- }
- public static bool SetCookie(string key, string value, TimeSpan? expiry)
- {
- return SetCookie(key, value, expiry, null, null, false);
- }
- public static bool SetCookie(string key, string value, TimeSpan? expiry, string path, string domain, bool secure)
- {
- if (!IsCookieEnabled()) return false; //If cookies not enabled return false.
- StringBuilder sbCookie = new StringBuilder();
- sbCookie.Append(string.Concat(key, "=", value));
- if (expiry.HasValue)
- {
- DateTime expire = DateTime.UtcNow + expiry.Value; sbCookie.Append(string.Concat(";expires=", expire.ToString("R")));
- }
- if (path != null)
- {
- sbCookie.Append(string.Concat(";path=", path));
- }
- if (domain != null)
- {
- sbCookie.Append(string.Concat(";domain=", domain));
- }
- if (secure)
- {
- sbCookie.Append(";secure");
- }
- HtmlPage.Document.SetProperty("cookie", sbCookie.ToString()); // User should handle exceptions if any while writing cookie.
- return true;
- }
- public static List<Cookie> GetAllCookieList()
- {
- string[] cookies = HtmlPage.Document.Cookies.Split(';');
- List<Cookie> cookieList = new List<Cookie>();
- foreach (string cookie in cookies)
- {
- string[] cookieParts = cookie.Split('=');
- if (cookieParts.Count() >= 1)
- {
- cookieList.Add(new Cookie(cookieParts[0].Trim(), cookieParts[1].Trim()));
- }
- }
- return cookieList; //User should check for count to know how many cookies are retrieved.
- ////LINQ code
- //return (from cookie in cookies
- // select cookie.Split('=')
- // into cookieParts
- // where cookieParts.Count() >= 1
- // select new Cookie(cookieParts[0].Trim(), cookieParts[1].Trim())).ToList(); //User should check for count to know how many cookeies are retrieved.
- }
- public static CookieCollection GetAllCookieCollection()
- {
- string[] cookies = HtmlPage.Document.Cookies.Split(';');
- CookieCollection cookieCollection = new CookieCollection();
- foreach (string cookie in cookies)
- {
- string[] cookieParts = cookie.Split('=');
- if (cookieParts.Count() >= 1)
- {
- cookieCollection.Add(new Cookie(cookieParts[0].Trim(), cookieParts[1].Trim()));
- }
- }
- return cookieCollection; //User should check for count to know how many cookies are retrieved.
- //LINQ code
- //foreach (string[] cookieParts in
- // cookies.Select(cookie => cookie.Split('=')).Where(cookieParts => cookieParts.Count() >= 1))
- //{
- // cookieCollection.Add(new Cookie(cookieParts[0].Trim(), cookieParts[1].Trim()));
- //}
- //return cookieCollection; //User should check for count to know how many cookies are retrieved.
- }
- public static string GetCookieAsString(string key)
- {
- string[] cookies = HtmlPage.Document.Cookies.Split(';');
- foreach (string cookie in cookies)
- {
- string[] keyValue = cookie.Split('=');
- if (keyValue.Length == 2)
- {
- if (keyValue[0].ToString().Trim() == key) //sometime we get one space infront of the cookie so need to Trim()
- {
- return cookie;
- }
- }
- }
- return null;
- //LINQ code
- //return (from cookie in cookies
- // let keyValue = cookie.Split('=')
- // where keyValue.Length == 2
- // where keyValue[0].ToString().Trim() == key
- // select cookie).FirstOrDefault();
- }
- public static string GetValue(string key)
- {
- string[] cookies = HtmlPage.Document.Cookies.Split(';');
- foreach (string cookie in cookies)
- {
- string[] keyValue = cookie.Split('=');
- if (keyValue.Length == 2)
- {
- if (keyValue[0].ToString().Trim() == key) //sometime we get one space infront of the cookie so need to Trim()
- {
- return keyValue[1]; //this will return only Value
- }
- }
- }
- return null;
- //LINQ code
- //return (from cookie in cookies
- // select cookie.Split('=')
- // into keyValue
- // where keyValue.Length == 2
- // where keyValue[0].ToString().Trim() == key
- // select keyValue[1]).FirstOrDefault();
- }
- public static bool DeletCookie(string key)
- {
- if (Exists(key, ""))// check if cookie is present or not
- {
- DateTime expireDate = DateTime.Now - TimeSpan.FromDays(1); // yesterday
- string expires = ";expires=" + expireDate.ToString("R");
- string cookie = key + "=" + expires;
- HtmlPage.Document.SetProperty("cookie", cookie);
- return true;
- }
- else
- {
- return false;
- }
- }
- public static bool Exists(string key, string value)
- {
- if (string.IsNullOrEmpty(key))
- return false; //If key not provided, return false
- return string.IsNullOrEmpty(value)
- ? HtmlPage.Document.Cookies.Contains(key + "=")
- : HtmlPage.Document.Cookies.Contains(key + "=" + value);
- }
- }
- }
Cookie FAQ
http://www.cookiecentral.com/faq/
Silverlight cookies
http://msdn.microsoft.com/en-us/library/dd920298%28v=VS.95%29.aspx
HttpOnly cookies
http://msdn.microsoft.com/en-us/library/system.web.httpcookie.httponly.aspx