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,
  1. public sealed class Sessions : System.Web.UI.Page
  2. {
  3. private const string SESSION_MANAGER = "PROJECTNAME_SESSION_OBJECT";
  4.  
  5. private Sessions()
  6. {
  7. //You can initialize any variables here.
  8. }
  9.  
  10. public static Sessions Current
  11. {
  12. get
  13. {
  14. Sessions session = (Sessions)HttpContext.Current.Session[SESSION_MANAGER];
  15. if (session == null)
  16. {
  17. session = new Sessions();
  18. HttpContext.Current.Session[SESSION_MANAGER] = session;
  19. }
  20.  
  21. return session;
  22. }
  23. }
  24.  
  25. // properties
  26. public string Username{ get; set; }
  27. public DateTime LoggedinDtae { get; set; }
  28. public int UserId { get; set; }
  29. }
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;