Tuesday, February 10, 2015

Clean way to maintain Session in a single class in ASP.Net application

We can use a wrapper class around the ASP.NET session to maintain session in a single class in ASP.Net application. This class stores one instance of itself in the ASP.NET session and allows you to access your session properties in a type-safe way from any class. Check the below code,
public sealed class Sessions : System.Web.UI.Page

     private Sessions()
          //You can initialize any variables here.

     public static Sessions Current
               Sessions session = (Sessions)HttpContext.Current.Session[SESSION_MANAGER];
               if (session == null)
                     session = new Sessions();
                     HttpContext.Current.Session[SESSION_MANAGER] = session;

               return session;

     // properties
     public string Username{ get; set; }
     public DateTime LoggedinDtae { get; set; }
     public int UserId { get; set; }
And you can access those session properties like below,
     //to get UserId
     int userId= Sessions.Current.UserId;
     //to set UserId
     Sessions.Current.UserId = 101;

     //to get Username
     string username= Sessions.Current.Username;
     //to set Username
     Sessions.Current.Username = "test name";

     //to get LoggedinDate
     DateTime loggedinDate = Sessions.Current.LoggedinDate;
     //to set LoggedinDate
     Sessions.Current.LoggedinDate= DateTime.Now;