Sunday, October 30, 2011

Silverlight Cookie Manager

Cookies are popular in web programming for state management, mostly used for persisting small data on client computer. Each cookie is a name-value pairs, this information is stored as small files on client hard-disk. You can also set expiration  date and time of a cookie. If no expiration is provided cookie will be discarded when user closes the browser, this type of non-persistent cookies is useful to store secure or short time data.

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.

  1. using System;
  2. using System.Net;
  3. using System.Text;
  4. using System.Linq;
  5. using System.Collections.Generic;
  6. using System.Windows.Browser;
  7.  
  8. namespace Utilities
  9. {
  10.     public static class CookieManager
  11.     {
  12.         // 1) If same name cooke exist, SetCookie() will over-ride value.
  13.         // 2) Exception handling should be done in user code
  14.         // 3) - expireDays = 0, indicates a session cookie that will not be written to disk
  15.         //    - expireDays = -1, indicates that the cookie will not expire and will be permanent
  16.         //    - expireDays = n, indicates that the cookie will expire in n days
  17.  
  18.  
  19.         public static bool IsCookieEnabled()
  20.         {
  21.             return HtmlPage.BrowserInformation.CookiesEnabled;
  22.         }
  23.  
  24.         public static bool SetCookie(string key, string value)
  25.         {
  26.             return SetCookie(key, value, null, null, null, false);
  27.         }
  28.  
  29.         public static bool SetCookie(string key, string value, TimeSpan? expiry)
  30.         {
  31.             return SetCookie(key, value, expiry, null, null, false);
  32.         }
  33.  
  34.         public static bool SetCookie(string key, string value, TimeSpan? expiry, string path, string domain, bool secure)
  35.         {
  36.             if (!IsCookieEnabled()) return false; //If cookies not enabled return false.
  37.  
  38.             StringBuilder sbCookie = new StringBuilder();
  39.             sbCookie.Append(string.Concat(key, "=", value));
  40.  
  41.             if (expiry.HasValue)
  42.             {
  43.                 DateTime expire = DateTime.UtcNow + expiry.Value; sbCookie.Append(string.Concat(";expires=", expire.ToString("R")));
  44.             }
  45.  
  46.             if (path != null)
  47.             {
  48.                 sbCookie.Append(string.Concat(";path=", path));
  49.             }
  50.  
  51.             if (domain != null)
  52.             {
  53.                 sbCookie.Append(string.Concat(";domain=", domain));
  54.             }
  55.  
  56.             if (secure)
  57.             {
  58.                 sbCookie.Append(";secure");
  59.             }
  60.  
  61.             HtmlPage.Document.SetProperty("cookie", sbCookie.ToString());  // User should handle exceptions if any while writing cookie.
  62.  
  63.             return true;
  64.         }
  65.  
  66.         public static List<Cookie> GetAllCookieList()
  67.         {
  68.             string[] cookies = HtmlPage.Document.Cookies.Split(';');
  69.             List<Cookie> cookieList = new List<Cookie>();
  70.             foreach (string cookie in cookies)
  71.             {
  72.                 string[] cookieParts = cookie.Split('=');
  73.                 if (cookieParts.Count() >= 1)
  74.                 {
  75.                     cookieList.Add(new Cookie(cookieParts[0].Trim(), cookieParts[1].Trim()));
  76.                 }
  77.             }
  78.  
  79.             return cookieList; //User should check for count to know how many cookies are retrieved.
  80.  
  81.             ////LINQ code
  82.             //return (from cookie in cookies
  83.             //        select cookie.Split('=')
  84.             //            into cookieParts
  85.             //            where cookieParts.Count() >= 1
  86.             //            select new Cookie(cookieParts[0].Trim(), cookieParts[1].Trim())).ToList(); //User should check for count to know how many cookeies are retrieved.
  87.         }
  88.  
  89.         public static CookieCollection GetAllCookieCollection()
  90.         {
  91.             string[] cookies = HtmlPage.Document.Cookies.Split(';');
  92.             CookieCollection cookieCollection = new CookieCollection();
  93.             foreach (string cookie in cookies)
  94.             {
  95.                 string[] cookieParts = cookie.Split('=');
  96.                 if (cookieParts.Count() >= 1)
  97.                 {
  98.                     cookieCollection.Add(new Cookie(cookieParts[0].Trim(), cookieParts[1].Trim()));
  99.                 }
  100.             }
  101.             return cookieCollection; //User should check for count to know how many cookies are retrieved.
  102.  
  103.             //LINQ code
  104.             //foreach (string[] cookieParts in
  105.             //   cookies.Select(cookie => cookie.Split('=')).Where(cookieParts => cookieParts.Count() >= 1))
  106.             //{
  107.             //    cookieCollection.Add(new Cookie(cookieParts[0].Trim(), cookieParts[1].Trim()));
  108.             //}
  109.             //return cookieCollection; //User should check for count to know how many cookies are retrieved.
  110.         }
  111.  
  112.         public static string GetCookieAsString(string key)
  113.         {
  114.             string[] cookies = HtmlPage.Document.Cookies.Split(';');
  115.  
  116.             foreach (string cookie in cookies)
  117.             {
  118.                 string[] keyValue = cookie.Split('=');
  119.  
  120.                 if (keyValue.Length == 2)
  121.                 {
  122.                     if (keyValue[0].ToString().Trim() == key) //sometime we get one space infront of the cookie so need to Trim()
  123.                     {
  124.                         return cookie;
  125.                     }
  126.                 }
  127.             }
  128.             return null;
  129.             //LINQ code
  130.             //return (from cookie in cookies
  131.             //        let keyValue = cookie.Split('=')
  132.             //        where keyValue.Length == 2
  133.             //        where keyValue[0].ToString().Trim() == key
  134.             //        select cookie).FirstOrDefault();
  135.         }
  136.  
  137.         public static string GetValue(string key)
  138.         {
  139.             string[] cookies = HtmlPage.Document.Cookies.Split(';');
  140.  
  141.             foreach (string cookie in cookies)
  142.             {
  143.                 string[] keyValue = cookie.Split('=');
  144.  
  145.                 if (keyValue.Length == 2)
  146.                 {
  147.                     if (keyValue[0].ToString().Trim() == key) //sometime we get one space infront of the cookie so need to Trim()
  148.                     {
  149.                         return keyValue[1]; //this will return only Value                        
  150.                     }
  151.                 }
  152.             }
  153.  
  154.             return null;
  155.             //LINQ code
  156.             //return (from cookie in cookies
  157.             //        select cookie.Split('=')
  158.             //            into keyValue
  159.             //            where keyValue.Length == 2
  160.             //            where keyValue[0].ToString().Trim() == key
  161.             //            select keyValue[1]).FirstOrDefault();
  162.         }
  163.  
  164.         public static bool DeletCookie(string key)
  165.         {
  166.  
  167.             if (Exists(key, ""))// check if cookie is present or not
  168.             {
  169.                 DateTime expireDate = DateTime.Now - TimeSpan.FromDays(1); // yesterday
  170.                 string expires = ";expires=" + expireDate.ToString("R");
  171.                 string cookie = key + "=" + expires;
  172.                 HtmlPage.Document.SetProperty("cookie", cookie);
  173.                 return true;
  174.             }
  175.             else
  176.             {
  177.                 return false;
  178.             }
  179.         }
  180.  
  181.         public static bool Exists(string key, string value)
  182.         {
  183.             if (string.IsNullOrEmpty(key))
  184.                 return false; //If key not provided, return false
  185.  
  186.             return string.IsNullOrEmpty(value)
  187.                        ? HtmlPage.Document.Cookies.Contains(key + "=")
  188.                        : HtmlPage.Document.Cookies.Contains(key + "=" + value);
  189.         }
  190.  
  191.     }
  192. }


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