Skip to main content

A cookie wrapper class. Easily read, create, update and delete cookies in MVC


Create a new class with name CookieHelper.cs In your project and paste the following code.

public class CookieHelper
    {
        #region Constants

        /// <summary>
        /// The cookie name
        /// </summary>
        public const string cookieName = "UserName";

        #endregion

        #region Enums

        public enum EnumCookieInterval
        {
            SECOND = 0,
            MINUTE = 1,
            DAY = 2,
            MONTH = 3,
            YEAR = 4
        };

        #endregion

        #region Utilities

        /// <summary>
        /// Calculates the cookie lifetime.
        /// </summary>
        /// <param name="duration">The duration.</param>
        /// <param name="durationType">Type of the duration.Use enum to specify</param>
        /// <returns>Expire date for cookie</returns>
        private static DateTime CalculateCookieLifetime(int duration, Enum durationType)
        {
            DateTime cookieExpire = DateTime.Now;

            switch (Convert.ToInt32(durationType))
            {
                case 0:
                    cookieExpire = DateTime.Now.AddSeconds(duration);
                    break;

                case 1:
                    cookieExpire = DateTime.Now.AddMinutes(duration);
                    break;

                case 2:
                    cookieExpire = DateTime.Now.AddDays(duration);
                    break;

                case 3:
                    cookieExpire = DateTime.Now.AddMonths(duration);
                    break;

                case 4:
                    cookieExpire = DateTime.Now.AddYears(duration);
                    break;

                default:
                    cookieExpire = DateTime.Now.AddDays(duration);
                    break;
            }
            return cookieExpire;
        }
        
        #endregion

        #region Methods

        /// <summary>
        /// Creates the cookie.
        /// </summary>
        /// <param name="cookieName">Name of the cookie.</param>
        /// <param name="cookieValue">The cookie value.</param>
        /// <param name="durationType">Type of the duration.Use enum to specify</param>
        /// <param name="duration">The duration.</param>
        /// <returns></returns>
        public static string CreateCookie(string cookieName, string cookieValue, Enum durationType, int duration)
        {

            HttpCookie myCookie = new HttpCookie(cookieName);

            // Set the cookie value.
            myCookie.Value = cookieValue;

            // Set the cookie expiration date.
            myCookie.Expires = CalculateCookieLifetime(duration, durationType);

            // Add the cookie.
            //Response.Cookies.Add(myCookie);
            HttpContext.Current.Response.Cookies.Add(myCookie);

            return cookieValue;

        }

        /// <summary>
        /// Reads the cookie.
        /// </summary>
        /// <param name="cookieName">Name of the cookie.</param>
        /// <returns></returns>
        public static string ReadCookie(string cookieName)
        {

            string cookieValue = string.Empty;

            HttpCookie myCookie = new HttpCookie(cookieName);
            myCookie = HttpContext.Current.Request.Cookies[cookieName];

            // Read the cookie information and display it.
            if (myCookie != null)
                cookieValue = myCookie.Value;


            return cookieValue;
        }

        /// <summary>
        /// Updates the cookie.
        /// </summary>
        /// <param name="cookieName">Name of the cookie.</param>
        /// <param name="cookieValue">The cookie value.</param>
        /// <param name="durationType">Type of the duration.Use enum to specify</param>
        /// <param name="duration">The duration.</param>
        /// <returns></returns>
        public static string UpdateCookie(string cookieName, string cookieValue, Enum durationType, int duration)
        {

            HttpCookie myCookie = new HttpCookie(cookieName);
            myCookie = HttpContext.Current.Request.Cookies[cookieName];

            // Set the cookie value.
            myCookie.Value = cookieValue;

            // Set the cookie expiration date.
            myCookie.Expires = CalculateCookieLifetime(duration, durationType);

            // Add the cookie.
            //Response.Cookies.Add(myCookie);
            HttpContext.Current.Response.Cookies.Add(myCookie);

            return cookieValue;

        }

        /// <summary>
        /// Deletes the cookie.
        /// </summary>
        /// <param name="cookieName">Name of the cookie.</param>
        public static void DeleteCookie(string cookieName)
        {
            HttpCookie myCookie = new HttpCookie(cookieName);

            DateTime cookieExpire = DateTime.Now;

            // Set the cookie expiration date.
            myCookie.Expires = cookieExpire.AddDays(-1);
            HttpContext.Current.Response.Cookies.Add(myCookie);

        }

        #endregion
    }



How to use?


1. Create cookie 

string cookie = CookieHelper.CreateCookie(CookieHelper.cookieName, "Here is cookie value", CookieHelper.EnumCookieInterval.DAY, 7);

string cookie = CookieHelper.CreateCookie(CookieHelper.cookieName, "Here is cookie value", CookieHelper.EnumCookieInterval.MONTH, 1);

2. Read Cookie

string cookie = CookieHelper.ReadCookie(CookieHelper.cookieName);

3. Update Cookie

string newCookie = CookieHelper.UpdateCookie(CookieHelper.cookieName, "Updated cookie value", CookieHelper.EnumCookieInterval.DAY, 14);

4. Delete Cookie

CookieHelper.DeleteCookie(CookieHelper.cookieName);

Hope it will helps you. Let me know your thoughts!



Comments

Popular posts from this blog

दान धर्माची बदललेली परिभाषा

नमस्कार! बरेच वेळा मनात विचार येतात पण लिहिण्याचा प्रयत्न पहिल्यांदाच करत आहे. तरी चूक भूल माफी असावी. आजकाल Whatsapp आणि Facebook यांच्यामुळे जग जवळ आले आहे, पण सगळ्याच गोष्टी share करण्याचा जणु छंदच लोकांना जडला आहे. अर्थात थोड्याफार प्रमाणात मी पण share करत असतो पण अगदी थोडक्या प्रमाणात. आता कोणी दानधर्म करत असेल तर तो पण यावर सर्रास Share केला जातो, मुळात दान याची वाख्याच लोक विसरत चालले आहे. याचीसुद्धा मार्केटिंग होऊ लागली आहे. मुळात दान हे निस्वार्थ भावनेने केले पाहिजे (असे दान ज्याला परताव्याची इच्छा नसते), जेव्हा लोक आपण दान करतो असा दाखवायचा प्रयत्न करतात मग ते facebook share असो किवां whatsapp status,post किवां इतर कोणतेही माध्यम याचा अर्थ असा कि दान करताना या लोकांनी मला प्रसिद्धी मिळेल किवां मी किती दानशुर आहे हे दाखवण्याची भावना मनात ठेवून केलेले दान होय. अशी परताव्याची भावना मनात ठेवून केलेले दान हे दान नसून व्यवहाराच नाही का? व्यवहारात जस आपण पैसे देऊन त्या बदल्यात वस्तू,सेवा खरेदी करतो, तसेच परताव्याचा विचार करून केलेले दान म्हणजे व्यवहाराच. असो माझे विचार

Why Interface For Decoupled System? A Note On How To Design Decoupled System in ASP.NET MVC

An Interface At first, interfaces came into focus because there was no multiple inheritance supported by C#, meaning you could not inherit from multiple classes, but you could implement multiple interfaces. The interfaces are grouping of object in terms of behavior. An interface contains only signatures. There is no implementation, only the signatures of the functionality the interface provides. An interface can contain signatures of methods, properties, indexers & events. Interface doesn't do anything like classes and abstract classes, it just defines what the class will perform if some class inherits it. An interface can also be inherited from another interface. If we take an example of USB (Universal Serial Bus), it's an interface which has signature of Connection functionality. The USB interface only knows I have to connect with Desktop Computer or laptop or anything, but it does not know what implementation will come to connection. It may be Pen d