Sunday, September 21, 2014

Session wrapper c#

Here I am trying to be more lazy.

After spending a lot of time to search in google I have created a wrapper class to handle session keys and values which can full fill my requirements.

My Requirements:
1. Do not want to write Session["nameofkey"], this key name is a text and if I spelled it wrongly then it will not throw any error.
2. I don't want to cast the returned object into my desired type every time.
3. Write less code to handle all of this.


Full Code:
Install from NuGet package, it will set the class "SessionManagement" in your project .
in NuGet search with "Session Wrapper"
OR
Install-Package SessionWrapper


Details:
Created one static class - Session Manager
to set value in session -
public static bool Set(string key, dynamic value)
        {
            HttpContext current = HttpContext.Current;
            if (current == null)
            {
                return false;
            }

            current.Session.Add(key, value);
            return true;
        }

Here I have used value as dynamic variable so any type of data can be passed and it will directly store that data with his type in session.

to get value from session-
 public static dynamic Get(string key, dynamic defaultValue = null)
        {
            HttpContext current = HttpContext.Current;
            if (current == null)
            {
                return defaultValue;
            }

            var valueFromSession = current.Session[key];
            if (valueFromSession != null)
            {
                return valueFromSession;
            }
            return defaultValue;
        }

Here it is returning the value as dynamic datatype so while you are getting value from session it is basically returning you the value with its original type so no need to type cast the value from object to desired type.

Like:
SessionManager.Set("mydate", DateTime.Now);
DateTime d = SessionManager.Get("mydate");

Now to make it easier I created property which can be used as sessionkeys.

Like:
public static int? Session_UserID
        {
            get
            {
                return GetFromSession(MethodBase.GetCurrentMethod());
            }
            set
            {
                SetInSession(MethodBase.GetCurrentMethod(), value);
            }
        }



Here main point is that you just have to copy the getter and setter for all your properties it will be same.

Now to use this just write
SessionManager.Session_UserID = 120;
int? existinguserid = SessionManager.Session_UserID;

It will handle your data storing that in session.
Easy to manage and less error prone.