Unosquare is a bi-national corporation providing software development, testing, and support for a set of highly valued customers. We serve North American clients from offices in Oregon and our Nearshore delivery center in Guadalajara, Mexico.

Sunday, May 9, 2010

The SessionManager pattern revisited

NOTICE: This blog entry was imported from our previous blogging platform.
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);
            }
        }


    }
}

No comments:

Post a Comment

About Unosquare

My photo
Portland, OR, United States
Unosquare provides US based IT consulting and Mexico based software development and testing.