Search This Blog

Showing posts with label Cookies. Show all posts
Showing posts with label Cookies. Show all posts

Thursday, October 3, 2013

Saving & retrieving/updating data using cookies

Saving & retrieving/updating data using cookies.

Like me, I believe most of you might had to use cookies in one way or the other, in my case, I had the following scenario. In a website, the user logs in who has access to numerous retail brands and every time he/she works with only one particular brand and this particular brand in which he/she works most has to be set as a preferred brand. So when the user is done with his/her work and closes the session, the last chosen brand has to be persisted and that has to be his/her preferred brand.

So going by the requirement, the most simple and quick resolution will seem to save the preferred brand in cookies of the browser. So the following two functions does exactly that. The get function gets the saved preferred brand when the user first opens the session to the website and the set functions sets a preferred brand when the user switches from one brand to the other. From where you want to call these functions is left abstract as your site may have master pages, or may not have master pages or your pages might be inherited from a Base Page class hence there can be numerous such scenarios.

     /// <summary>
    /// gets the preferred brand for the user from saved cookie.
    /// </summary>
    /// <param name="userId"></param>
    /// <returns></returns>
    public int getPreferredBrand(string userId)
    {
        int preferredBrandId = 0;
        try
        {
            //1. check to see if cookie exists with preferred brandid.
            //2. if yes then return the preferred brandid.
            HttpCookie authCookie = HttpContext.Current.Request.Cookies[PrefBrandCookieName];
            if (authCookie != null)
            {
                System.Web.Security.FormsAuthenticationTicket ticket = System.Web.Security.FormsAuthentication.Decrypt(authCookie.Value);
                preferredBrandId = int.TryParse(ticket.UserData.ToString(), out preferredBrandId) == true ? preferredBrandId : 0;
            }
            else
                preferredBrandId = 0;
        }
        catch (Exception ex)
        {
            Exception customEx = new Exception("Error while trying to retrieve cookiename<<" + userId + ">>.See detailed exception.." + ex.Message);
            ExceptionManager.Publish(customEx);
        }
        return preferredBrandId;
    }
    /// <summary>
    /// sets preferred brand for the user when session expires or browser is closed.
    /// </summary>
    /// <param name="userId"></param>
    /// <param name="brandId"></param>
    public void setPreferredBrand(string userId, int brandId)
    {
        try
        {
            //1. Check if cookie exists
            System.Web.Security.FormsAuthenticationTicket authTicket = null;
            HttpCookie authCookie = HttpContext.Current.Request.Cookies[PrefBrandCookieName];
            authTicket = new System.Web.Security.FormsAuthenticationTicket(1, userId, DateTime.Now, DateTime.MaxValue, true, brandId.ToString());

            //2. Persist selected brand in cookies.
            //will persist cookie even when the browser is shutdown.
            if (authCookie != null)
                authCookie.Value = System.Web.Security.FormsAuthentication.Encrypt(authTicket);
            else
                authCookie = new HttpCookie(LCoreUser.PrefBrandCookieName, System.Web.Security.FormsAuthentication.Encrypt(authTicket));
            authCookie.Expires = DateTime.MaxValue;
            HttpContext.Current.Response.Cookies.Add(authCookie);
        }
        catch (Exception ex)
        {
            Exception customEx = new Exception("Error while persisting cookie for user<<" + userId + ">> and brand<<" + brandId.ToString() + ">>.See detailed exception.." + ex.Message);
            ExceptionManager.Publish(customEx);
        }
    }

The above code is pretty self explanatory. In the set function, I first check if the cookie does exist or not and if it does, then update the cookie value by assigning a new ticket into it. And if the cookie does not exist then all I do is create a new cookie and assign the ticket value.