Skip to content

Instantly share code, notes, and snippets.

@philoushka
Created June 25, 2015 22:03
Show Gist options
  • Save philoushka/73cbddcd737ab993efbc to your computer and use it in GitHub Desktop.
Save philoushka/73cbddcd737ab993efbc to your computer and use it in GitHub Desktop.
using System;
using System.Web;
public class Cookies
{
private const string ApplicationName = "MyCoolApplication";
private enum CookieItem
{
UserGuid,
UserFullName,
UserLoginExpiry,
UserHadForBreakfast,
UserTimezone
}
// All cookie values are accessible by public static methods.
// No typos/duplicates are possible from calling code!
public static string UserFullName
{
get { return GetCookieVal(CookieItem.UserFullName); }
set { UpdateCookieVal(CookieItem.UserFullName, value, 365); }
}
public static Guid UserGuid
{
get { return new Guid(GetCookieVal(CookieItem.UserGuid)); }
set { UpdateCookieVal(CookieItem.UserGuid, value.ToString(), 365); }
}
public static DateTime UserLoginExpiry
{
get { return DateTime.Parse(GetCookieVal(CookieItem.UserLoginExpiry)); }
set { UpdateCookieVal(CookieItem.UserLoginExpiry, value.ToString(), 365); }
}
public static string UserHadForBreakfast
{
get { return GetCookieVal(CookieItem.UserHadForBreakfast); }
set { UpdateCookieVal(CookieItem.UserHadForBreakfast, value, 1); }
}
private static string GetCookieVal(CookieItem item)
{
HttpCookie cookie = GetAppCookie(false); //get the existing cookie
return (cookie != null && (cookie.Values[item.ToString()] != null)) //value or empty if doesn't exist
? cookie.Values[item.ToString()]
: string.Empty;
}
private static void UpdateCookieVal(CookieItem item, string val, int expireDays)
{
//get the existing cookie (or new if not exists)
HttpCookie cookie = GetAppCookie(true);
//modify its contents & meta.
cookie.Expires = DateTime.Now.AddDays(expireDays);
cookie.Values[item.ToString()] = val;
//add back to the http response to send back to the browser
HttpContext.Current.Response.Cookies.Add(cookie);
}
private static HttpCookie GetAppCookie(bool createIfDoesntExist)
{
//get the cookie or a new one if indicated
return HttpContext.Current.Request.Cookies[ApplicationName]
?? ((createIfDoesntExist) ? new HttpCookie(ApplicationName) : null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment