Skip to content

Instantly share code, notes, and snippets.

@jstemerdink
Created December 22, 2017 10:11
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 jstemerdink/1819197e00671bc2d7b2b507adbacbdf to your computer and use it in GitHub Desktop.
Save jstemerdink/1819197e00671bc2d7b2b507adbacbdf to your computer and use it in GitHub Desktop.
Use the new tracking integration packages of Episerver

Use the new tracking integration packages of Episerver

Powered by ReSharper image

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EPiServer;
using EPiServer.Cms.Shell;
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.Personalization;
using EPiServer.ServiceLocation;
using EPiServer.Tracking.Core;
using EPiServer.Web;
using EPiServer.Web.Routing;
/// <summary>
/// Class CmsTrackingAttribute.
/// </summary>
/// <seealso cref="System.Web.Mvc.ActionFilterAttribute" />
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Event)]
public class CmsTrackingAttribute : ActionFilterAttribute
{
/// <summary>
/// The context mode resolver
/// </summary>
private readonly Injected<IContextModeResolver> contextModeResolver;
/// <summary>
/// The route helper
/// </summary>
private readonly Injected<IContentRouteHelper> routeHelper;
/// <summary>
/// The tracking service
/// </summary>
private readonly Injected<ITrackingService> trackingService;
/// <summary>
/// The category repository
/// </summary>
private readonly Injected<CategoryRepository> categoryRepository;
/// <summary>
/// Initializes a new instance of the <see cref="CmsTrackingAttribute"/> class.
/// </summary>
/// <param name="trackingType">Type of the tracking.</param>
public CmsTrackingAttribute(string trackingType)
{
this.TrackingType = trackingType;
}
/// <summary>
/// Gets the type of the tracking.
/// </summary>
/// <value>The type of the tracking.</value>
protected string TrackingType { get; }
/// <summary>
/// Called by the ASP.NET MVC framework before the action method executes.
/// </summary>
/// <param name="filterContext">The filter context.</param>
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
IContent content = this.routeHelper.Service.Content;
if (content == null || !this.PageIsInViewMode())
{
return;
}
HttpContextBase httpContext = filterContext.HttpContext;
EPiServerProfile current = EPiServerProfile.Current;
UserData userData = new UserData { Name = current.UserName, Email = current.Email };
this.trackingService.Service.Track(
new TrackingData<CmsTrackingData>
{
EventType = this.TrackingType,
PageTitle = content.Name,
Value = content.ContentLink.ToString(),
PageUri = httpContext.Request.Url?.AbsoluteUri ?? string.Empty,
Payload = new CmsTrackingData
{
Name = content.Name,
ContentGuid = content.ContentGuid,
ContentLink = content.ContentLink,
ContentTypeID = content.ContentTypeID,
ParentLink = content.ParentLink,
Language = content.LanguageBranch(),
Categories = this.GetCategoryNames(content, "|")
},
User = userData
},
httpContext: httpContext);
base.OnActionExecuting(filterContext: filterContext);
}
/// <summary>
/// Pages the is in view mode.
/// </summary>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
private bool PageIsInViewMode()
{
return this.contextModeResolver.Service.CurrentMode == ContextMode.Default;
}
/// <summary>
/// Gets the category names.
/// </summary>
/// <param name="content">The content.</param>
/// <param name="seperator">The seperator.</param>
/// <returns>Concatenated categories names.</returns>
private string GetCategoryNames(IContent content, string seperator = ", ")
{
ICategorizable categorizableContent = content as ICategorizable;
if (categorizableContent == null || categorizableContent.Category.Count < 1)
{
return string.Empty;
}
List<string> catNames = categorizableContent.Category.Select(catId => this.categoryRepository.Service.Get(catId).Name).ToList();
return string.Join(seperator, catNames);
}
}
using System;
using EPiServer.Core;
public class CmsTrackingData
{
public string Categories { get; set; }
public Guid ContentGuid { get; set; }
public ContentReference ContentLink { get; set; }
public int ContentTypeID { get; set; }
public string Name { get; set; }
public ContentReference ParentLink { get; set; }
public string Language { get; set; }
public string Location { get; set; }
}
using System.Threading.Tasks;
using System.Web;
using EPiServer.Forms.Helpers.Internal;
using EPiServer.Framework;
using EPiServer.Logging;
using EPiServer.ServiceLocation;
using EPiServer.Tracking.Core;
/// <summary>
/// Class LogTracker.
/// </summary>
/// <seealso cref="EPiServer.Tracking.Core.ITrackingAdapter" />
[ServiceConfiguration(ServiceType = typeof(ITrackingAdapter), Lifecycle = ServiceInstanceScope.Singleton)]
public class LogTracker : ITrackingAdapter
{
/// <summary>
/// The logger
/// </summary>
private readonly ILogger logger = LogManager.GetLogger();
/// <summary>
/// Tracks the specified tracking data.
/// </summary>
/// <typeparam name="TPayload">The type of the t payload.</typeparam>
/// <param name="trackingData">The tracking data.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The tracking task.</returns>
public Task Track<TPayload>(TrackingData<TPayload> trackingData, HttpContextBase httpContext)
{
Validator.ThrowIfNull(nameof(trackingData), value: trackingData);
this.logger.Log(level: Level.Debug, message: trackingData.ToJson());
Task<Task> task = Task.FromResult((Task)null);
return task;
}
}
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Web;
using EPiServer.Personalization;
using EPiServer.ServiceLocation;
using EPiServer.Tracking.Core;
/// <summary>
/// Class LogTrackerDataInterceptor.
/// </summary>
/// <seealso cref="EPiServer.Tracking.Core.ITrackingDataInterceptor" />
[ServiceConfiguration(ServiceType = typeof(ITrackingDataInterceptor))]
public class LogTrackerDataInterceptor : ITrackingDataInterceptor
{
/// <summary>
/// The geo location provider
/// </summary>
private readonly GeolocationProviderBase geoLocationProvider;
/// <summary>
/// The HTTP context accessor
/// </summary>
private readonly ServiceAccessor<HttpContextBase> httpContextAccessor;
/// <summary>
/// Initializes a new instance of the <see cref="LogTrackerDataInterceptor" /> class.
/// </summary>
/// <param name="httpContextAccessor">The HTTP context accessor.</param>
/// <param name="geoLocationProvider">The geo location provider.</param>
public LogTrackerDataInterceptor(
ServiceAccessor<HttpContextBase> httpContextAccessor,
GeolocationProviderBase geoLocationProvider)
{
this.httpContextAccessor = httpContextAccessor;
this.geoLocationProvider = geoLocationProvider;
this.SortOrder = 200;
}
/// <summary>
/// Gets the sort order.
/// </summary>
/// <value>The sort order.</value>
public int SortOrder { get; }
/// <summary>
/// Intercepts the specified tracking data.
/// </summary>
/// <typeparam name="TPayload">The type of the t payload.</typeparam>
/// <param name="trackingData">The tracking data.</param>
public void Intercept<TPayload>(TrackingData<TPayload> trackingData)
{
if (trackingData == null)
{
return;
}
CmsTrackingData payload = trackingData.Payload as CmsTrackingData;
if (payload == null)
{
return;
}
payload.Location = this.GetCurrentUsersLocation()?.CountryCode ?? string.Empty;
}
/// <summary>
/// Gets the current users location.
/// </summary>
/// <returns>IGeolocationResult.</returns>
private IGeolocationResult GetCurrentUsersLocation()
{
IPAddress ipAddress = this.GetUsersIp();
return ipAddress == null ? null : this.geoLocationProvider.Lookup(address: ipAddress);
}
/// <summary>
/// Gets the users ip.
/// </summary>
/// <returns>IPAddress.</returns>
private IPAddress GetUsersIp()
{
HttpContextBase httpContextBase = this.httpContextAccessor();
if (httpContextBase?.Request?.UserHostAddress == null)
{
return null;
}
IPAddress ipAddress;
if (!IPAddress.TryParse(ipString: httpContextBase.Request.UserHostAddress, address: out ipAddress))
{
return null;
}
if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
{
ipAddress = Dns.GetHostEntry(address: ipAddress).AddressList
.First(x => x.AddressFamily == AddressFamily.InterNetwork);
}
return ipAddress;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment