Monday, January 30, 2012

Best Extension Methods: Cookie Extension Methods

Best Cookies Extension Methods
public static class CookieExtensions
{

    /// 
    /// Sets a persistent cookie which expires after the given number of days
    /// 
    /// The HtmDocument to extend
    /// the cookie key
    /// the cookie value
    /// The number of days before the cookie expires
    public static void SetCookie(this HtmlDocument doc, string key, string value, int days)
    {
        DateTime expiration = DateTime.UtcNow + TimeSpan.FromDays(days);
        SetCookie(doc, key, value, expiration);
    }

    /// 
    /// Sets a persistent cookie with an expiration date
    /// 
    /// The HtmDocument to extend
    /// the cookie key
    /// the cookie value
    public static void SetCookie(this HtmlDocument doc, string key, string value, DateTime expiration)
    {
        string oldCookie = doc.GetProperty("cookie") as String;
        string cookie = String.Format("{0}={1};expires={2}", key, value, expiration.ToString("R"));
        doc.SetProperty("cookie", cookie);
    }

    /// 
    /// Retrieves an existing cookie
    /// 
    /// The HtmDocument to extend
    /// cookie key
    /// null if the cookie does not exist, otherwise the cookie value
    public static string GetCookie(this HtmlDocument doc, string key)
    {
        string[] cookies = doc.Cookies.Split(';');
        key += '=';
        foreach (string cookie in cookies)
        {
            string cookieStr = cookie.Trim();
            if (cookieStr.StartsWith(key, StringComparison.OrdinalIgnoreCase))
            {
                string[] vals = cookieStr.Split('=');

                if (vals.Length >= 2)
                {
                    return vals[1];
                }

                return string.Empty;
            }
        }

        return null;
    }

    /// 
    /// Deletes a specified cookie by setting its value to empty and expiration to -1 days
    /// 
    /// The HtmDocument to extend
    /// the cookie key to delete
    public static void DeleteCookie(this HtmlDocument doc, string key)
    {
        string oldCookie = doc.GetProperty("cookie") as String;
        DateTime expiration = DateTime.UtcNow - TimeSpan.FromDays(1);
        string cookie = String.Format("{0}=;expires={1}", key, expiration.ToString("R"));
        doc.SetProperty("cookie", cookie);
    }
}

Compiled By: Rajesh Rolen

Share This!


No comments:

Powered By Blogger · Designed By Seo Blogger Templates