Thursday, January 28, 2016

Http Cookie


Never read a cookie from Response. It creates a new (blank) cookie and overwrites a cookie with the same name even if there's value in it. Learned the hard way. 


-------------Writing a cookie (write to a Response)----------------

HttpCookie visitorCookie = new HttpCookie(tracker.GetVisitorMultivariateTestCookieName());
visitorCookie.Value = runningTest.ID.ToString();
visitorCookie.Expires = DateTime.Now.AddYears(10);

HttpContext.Current.Response.Cookies.Add(visitorCookie);

----------Reading a cookie (read from the Request) -----------------

public override bool TryGetRunningVisitorTestFromCookie(out TestDefinitionItem test)
{
      string testId = string.Empty;

      try
            {
                //cookie exists and contains value
                if (!string.IsNullOrEmpty(HttpContext.Current.Request.Cookies[_VisitorTestCookieName].Value))
                {
                    Item testItem = Sitecore.Context.Database.GetItem(HttpContext.Current.Request.Cookies[_VisitorTestCookieName].Value);

                    if (testItem != null)
                    {
                        test = new TestDefinitionItem(testItem);

                        if (test.IsRunning)
                        {
                            return true;
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                Log.Error("Error reading a Visitor Multivariate Test cookie ", ex, this);
                test = null;
                return false;
            }

            test = null;
            return false;
        }

No comments:

Post a Comment