Friday, July 11, 2014

Session Helper

I am writing this for my own repository of  using session variables and though may be useful to others friends also.  Over use of session variables are not good. Try to avoid using it. It takes server memory. If you want to use it then this code example shows how to use it without worrying to remember Session keys and simply access like a property with appropriate type.

I am explaining everything using code and code comments. 



/// Session Helper class
   public static class SessionHelper
   {
 
       /// The userinfo Key
       const string USERINFO = "USERINFO";
 
       /// The userclaiminfo Key
       const string USERCLAIMINFO = "USERCLAIMINFO";
 
       
       /// Property to Get or sets the user claim information from or to Session.
       public static UserClaimsInfo UserClaimInfo
       {
           get
           {
               return GetInfoFromSession<UserClaimsInfo>(USERCLAIMINFO);
           }
           set{
               SetInforToSession<UserClaimsInfo>(value, USERCLAIMINFO);
           }
       }
 
       
       /// Property to Get or set the user information from or to session.
       public static Userinfo UserInfo
       {
           get
           {
               return GetInfoFromSession<Userinfo>(USERINFO);
           }
           set{
               SetInforToSession<Userinfo>(value, USERINFO);
           }
       }
 
       
       /// Priavate generic method to Get information from session using Key.
       private static T GetInfoFromSession<T>(string key)
       {
       if (HttpContext.Current.Session[key] != null && HttpContext.Current.Session[key] is T)
           {
               return (T) HttpContext.Current.Session[key];
           }
           return default(T);
       }
 
       
       /// Priavate method to set information to session using Key.
       private static void SetInforToSession<T>(T info, string key)
       {
           HttpContext.Current.Session[key] = info;
       }
   }

In above code block You can add individual property for each session variable.  You can to define constant variable for defining key.  Session variable property can use generic method  GetInfoFromSession<T> and SetInfoToSession<T> to get and set values to and from session. 

Thanks.