Session management in MVC.
Step 1. Create Class with Name 'AppCacheManager' in class library.
using System;
using System.Web;
namespace DotNetByPriyanshu
{
    public class AppCacheManager
    {
        #region Instance Property
        // This approach ensures that only one instance is created and only when the instance is needed. 
        // Also, the variable is declared to be volatile to ensure that assignment to the instance variable 
        // completes before the instance variable can be accessed. 
        // Lastly, this approach uses a syncRoot instance to lock on, rather than locking on the type itself, to avoid deadlocks. 
        //
        // This double-check locking approach solves the thread concurrency problems while avoiding an exclusive lock 
        // in every call to the Instance property method. 
        // It also allows you to delay instantiation until the object is first accessed.
        // In practice, an application rarely requires this type of implementation. 
        // In most cases, the static initialization approach is sufficient.
        private static volatile AppCacheManager _Instance = null;
        private static object syncRoot = new Object();
        /// <summary>
        /// Get/Set a Thread-Safe Instance of the AppCacheManager class
        /// </summary>
        public static AppCacheManager Instance
        {
            get
            {
                if (_Instance == null)
                {
                    lock (syncRoot)
                    {
                        if (_Instance == null)
                        {
                            _Instance = new AppCacheManager();
                        }
                    }
                }
                return _Instance;
            }
            set { _Instance = value; }
        }
        #endregion
        #region
        /// <summary>
        /// Get a specific value from the user (HttpContext.Current.Session) cache.
        /// If the key is not found, a null value is returned.
        /// </summary>
        /// <param name="key">The unique key of the cached value to retrieve</param>
        /// <returns>The cached value or null if the key/value is not found</returns>
        public T GetFromUserCache<T>(string key)
        {
            T ret;
            object value;
            value = HttpContext.Current.Session[key];
            if (value != null)
            {
                ret = (T)value;
            }
            else
            {
                ret = default(T);
            }
            return ret;
        }
        /// <summary>
        /// Call this method to add a key/value pair to cache that is specific for a user of the application.
        /// The SessionID is used to uniquely identify the user.
        /// </summary>
        /// <param name="key">A unique key to identify the cached value</param>
        /// <param name="value">The value to add to the cache</param>
        public void AddToUserCache(string key, object value)
        {
            HttpContext.Current.Session.Add(key, value);
        }
        #endregion
    }
}
Step 2 . Create class with Name 'AppUserSession' in class library.
using System;
namespace DotNetByPriyanshu
{
    /// <summary>
    /// Provides strongly-typed access to session variables.
    /// </summary>
    [Serializable]
    public class AppUserSession
    {
        // Add your own Properties in the following region
        #region Public Properties
        /// <summary>
        /// Get/Set the Last Employee Name used
        /// NOTE: This is a sample only, you can remove this.
        /// </summary>
        public string Name
        {
            get { return AppCacheManager.Instance.GetFromUserCache<string>("Name"); }
            set { AppCacheManager.Instance.AddToUserCache("Name", value); }
        }
        /// <summary>
        /// Get/Set the UserId used
        /// </summary>
        public int UserId
        {
            get { return AppCacheManager.Instance.GetFromUserCache<int>("UserId"); }
            set { AppCacheManager.Instance.AddToUserCache("UserId", value); }
        }
        #endregion
    }
}
Step 3. Create class with Name 'AppController' and inherit Controller in class library.
using System.Web.Mvc;
namespace DotNetByPriyanshu
{
    public class AppController : Controller
    {
        #region Protected Properties
        private AppUserSession _session;
        /// <summary>
        /// Get/Set the User Session information on a page
        /// </summary>
        protected AppUserSession UserSession
        {
            get
            {
                if (_session == null)
                {
                    _session = new AppUserSession();
                }
                return _session;
            }
            set { _session = value; }
        }
        #endregion
        #region Init Method
        /// <summary>
        /// Initialize any items needed by all controllers
        /// </summary>
        public void Init()
        {
        }
        #endregion
        /// <summary>
        /// Get Logged-In User Full-Name
        /// </summary>
        /// <returns></returns>
        public string GetLoggedInUserFullName()
        {
            string value = string.Empty;
            if (UserSession.Name != null)
                return value = UserSession.Name;
            else
                return value = "unknown";
        }
    }
}
Use of Session in MVC application:-
create controller and inherit AppController .
example:-
using DotNetByPriyanshu;
using System;
using System.Collections.Generic;
using System.Data;
using System.Web.Mvc;
namespace DotNetByPriyanshuWebApp.Controllers.Employee
{
        private readonly IUserInfo _userInfo;
        public EmployeeController(IUserInfo userInfo)
        {
            _userInfo = userInfo;
        }
    public class EmployeeController : AppController // change controller in to AppController 
    {
        [HttpGet]
        public ActionResult EmployeeList()
        {
            try
            {
                  var objList =_userInfo.getUserDetailsByUserId(UserSession.UserId);
                  // Here I am using Session
                return View(objList);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
    }
}
 
No comments:
Post a Comment