The default behavior for Marketing Campaigns in Sitecore Analytics is such that they will only be applied to a visit if the campaign is applied on the first page of the visit. This could be a landing page flagged with that marketing campaign, or via the sc_camp
query string parameter.
I find this behavior to be somewhat problematic in certain commerce scenarios. It's also different than how Google Analytics handles marketing campaigns. Google Analytics will start a new visit for the user if he/she re-enters the site via a different marketing campaign.
I'd like to emulate this behavior in Sitecore Analytics for a POC I'm working on. I've attempted this via the initializeTracker
pipeline. I can successfully detect a change in the marketing campaign for the visit, but I'm unable to end and restart the visit. I've tried both utilizing Tracker.EndVisit()
and simply changing the ID of the visit. Neither seems to result in a new visit, associated with the marketing campaign.
Does anyone know how I can successfully end the previous visit, and start a new one, within the same request?
I am working in CMS/DMS 7.1 rev 140130. My current code is below.
using System;
using System.Web;
using Sitecore.Analytics;
using Sitecore.Analytics.Pipelines.InitializeTracker;
using Sitecore.Analytics.Web;
using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Web;
namespace ActiveCommerce.Training.PriceTesting.Analytics
{
public class RestartVisitOnNewCampaign : InitializeTrackerProcessor
{
public override void Process(InitializeTrackerArgs args)
{
if (HttpContext.Current == null)
{
args.AbortPipeline();
}
//no need to restart visit if visit is new
if (Tracker.CurrentVisit.VisitPageCount < 1)
{
return;
}
//look for campaign id in query string
Guid campaign;
var campaignStr = WebUtil.GetQueryString(Settings.GetSetting("Analytics.CampaignQueryStringKey")).Trim();
if (string.IsNullOrEmpty(campaignStr) || !Guid.TryParse(campaignStr, out campaign))
{
return;
}
//don't restart if the campaign isn't changing
if (!Tracker.CurrentVisit.IsCampaignIdNull() && Tracker.CurrentVisit.CampaignId == campaign)
{
return;
}
//Tracker.EndVisit(false);
//restart visit by setting new ID
var visitCookie = new VisitCookie();
visitCookie.VisitId = ID.NewID.Guid;
visitCookie.Save();
}
}
}