Skip to content

Instantly share code, notes, and snippets.

@davidbuo
Created November 13, 2019 11:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidbuo/5a42c55237031823c6a9d7713db7f7b0 to your computer and use it in GitHub Desktop.
Save davidbuo/5a42c55237031823c6a9d7713db7f7b0 to your computer and use it in GitHub Desktop.
using EPiServer.Core;
using EPiServer.Personalization.VisitorGroups;
using EPiServer.ServiceLocation;
using EPiServer.Tracking.Cms;
using EPiServer.Tracking.Core;
using EPiServer.Web;
using EPiServer.Web.Routing;
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
namespace Foundation.Infrastructure.Tracking
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Event, AllowMultiple = false)]
public class VisitorGroupTrackingAttribute : ActionFilterAttribute
{
private readonly Injected<ITrackingService> _trackingService;
private readonly Injected<IContextModeResolver> _contextModeResolver;
private readonly Injected<IContentRouteHelper> _routeHelper;
private readonly Injected<IVisitorGroupRepository> _visitorGroupRepo;
//Called before the Action method (Controller) executes.
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
IContent content = this._routeHelper.Service.Content;
if (content == null || !this.PageIsInViewMode())
return;
HttpContextBase httpContext = filterContext.HttpContext;
try
{
//Store matched and unmatched visitor groups
var matchedVGs = new List<string>();
var unmatchedVGs = new List<string>();
//Helper class to check visitor group membership
var vgHelper = new VisitorGroupHelper();
//All visitor groups defined at current website
var visitorGroups = _visitorGroupRepo.Service.List();
foreach (var visitorGroup in visitorGroups)
{
//Check if current user/visitor is member of visitor group
if (vgHelper.IsPrincipalInGroup(httpContext.User, visitorGroup.Name))
{
matchedVGs.Add(visitorGroup.Name);
}
else
{
unmatchedVGs.Add(visitorGroup.Name);
}
}
//Episerver standard tracking data with visitor group payload.
var trackData = new TrackingData<VisitorGroupTrackDataWrapper>
{
Payload = new VisitorGroupTrackDataWrapper
{
Epi = new VisitorGroupTrackingData
{
IncludeVisitorGroups = matchedVGs, //matched group
ExcludeVisitorGroups = unmatchedVGs //unmatched group
}
}
};
_trackingService.Service.TrackVisitorGroupAsync(trackData, httpContext);
}
catch
{
}
base.OnActionExecuting(filterContext);
}
private bool PageIsInViewMode()
{
return this._contextModeResolver.Service.CurrentMode == ContextMode.Default;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment