NOTICE: This blog entry was imported from our previous blogging platform.
The real entry date is November 25, 2009
The real entry date is November 25, 2009
Here's the new and improved SessionManager pattern. I thought I would blog it because it looks so elegant and useful. Here it is:
namespace Unosquare.Patterns
{ public static class SessionManager { private enum SessionKeys { User, IsAuthenticated, ClientEntity, ClientEntityId } private static T GetSessionProperty(SessionKeys key) where T : new() { var sessionKey = key.ToString(); if (HttpContext.Current.Session[sessionKey] == null) { HttpContext.Current.Session[sessionKey] = new T(); } return (T)HttpContext.Current.Session[sessionKey]; } private static void SetSessionProperty(SessionKeys key, T value) where T : new() { var sessionKey = key.ToString(); HttpContext.Current.Session[sessionKey] = value; } public static bool IsAuthenticated { get { var value = GetSessionProperty (SessionKeys.IsAuthenticated); return value.HasValue ? value.Value : false; } set { SetSessionProperty (SessionKeys.IsAuthenticated, value); } } public static User User { get { return GetSessionProperty (SessionKeys.User); } set { SetSessionProperty (SessionKeys.User, value); } } public static ClientEntity ClientEntity { get { return GetSessionProperty (SessionKeys.ClientEntity); } set { SetSessionProperty (SessionKeys.ClientEntity, value); } } public static Guid ClientEntityId { get { var value = GetSessionProperty (SessionKeys.ClientEntityId); return value.HasValue ? value.Value : Guid.Empty; } set { SetSessionProperty (SessionKeys.ClientEntityId, value); } } } }