Last updated: Aug 29 2018

Area: Episerver Profile Store Applies to versions: Not applicable

Using Tracking.Core API with Profile Store

This topic describes how to use the EPiServer.Tracking.Core API with Episerver Profile Store, including installation and configuration of the tracking.

In this topic


Configure the API URLs and subscription keys:

<add key="episerver:profiles.TrackingApiBaseUrl" value="https://"...>
<add key="episerver:profiles.TrackingApiSubscriptionKey" value="...>
<add key="episerver:profiles.ProfileStoreTrackingEnabled" value="true"...>
<add key="episerver:tracking.Enabled" value="true">
<add key="episerver:tracking.IgnoreDNT" value="true">

Note: See Do Not Track and Turn "Do not track" on or off for information about Do not Track (DNT)

Install EPiServer.Profiles.Client

  1. Install the EPiServer.Profiles.Client NuGet package from Episerver NuGet source to your site by entering the following command at the Package manager prompt (PM>).
    install-package episerver.profiles.client
  2. In web.config, fill tracking baseUrl and subscriptionKey values in appsetting section.
    <add key="episerver:profiles.TrackingApiBaseUrl" value="ChangeThis" />
    <add key="episerver:profiles.TrackingApiSubscriptionKey" value="ChangeThis" />
  3. Set the following:
  4. Optionally, specify episerver:profiles.Scope = <default_scope_you_want_to_send>. The default Scope must be lowercase and cannot include special characters such as: + - _ \ / # < > ...
  5. Verify your tracking data in Insight UI.

Install EPiServer.Tracking.Core

Install the EPiServer.Tracking.Core NuGet package from the Episerver NuGet source to your site.

Prepare tracking client APIs

This example uses an Alloy sample site and its Start Page.

  1. Create custom tracking data.
    class MyCustomTrackingData
    	public string Value1 { get; set; }
    	public string Value2 { get; set; }
    	public string Value3 { get; set; }
    	public UserData User { get; set; }
  2. Declare ITrackingService and inject it into StartPageController using constructor dependency injection pattern.
    public class StartPageController : PageControllerBase
    	private readonly ITrackingService _trackingService;
    	public StartPageController(ITrackingService trackingService)
              _trackingService = trackingService;
  3. Use the Track method of ITrackingService for tracking object.
    public async Task Index(StartPage currentPage) {
    	HttpContextBase context = ControllerContext.HttpContext;
    	string currentUsername = EPiServer.Security.PrincipalInfo.CurrentPrincipal.Identity.Name;
    	string email = EPiServer.Personalization.EPiServerProfile.Current.Email;
    	var userInformation = new Dictionary<string, string>();
    	userInformation.Add("Website", $"http://a-website.com");
    	userInformation.Add("Facebook", $"http://facebook.com/a-fakeid");
    	var userData = new UserData
    		Email = currentUsername,
    		Name = email,
    		Info = userInformation
    		var myPayload = new MyCustomTrackingData
    			Value1 = "Home Value 1",
    			Value2 = "Home Value 2",
    			Value3 = "Home Value 3",
    			User = userData
    		var trackingData = new TrackingData
    			EventType = "StartPage",
    			PageTitle = currentPage.MetaTitle, //or Title on QuickSilver site
    			Value = "sample-value",
    			PageUri = context.Request.Url.AbsoluteUri,
    			Payload = myPayload,
    			User = userData,
    			Scope = "myscope" // Optional, default is episerver:profiles.Scope setting.
    		await _trackingService.Track(trackingData, context);
    	catch (Exception ex)
    		throw ex;

    The next example sends a page view in the Payload; this is the recommended way of sending page views. Episerver Advance needs the Payload for page views to be structured in this way, to make recommendations work:

    public async Task Index(StartPage currentPage) {
    	var local = currentPage as ILocale;
    var language = (currentPage as ILocale)?.Language;

    var siteDefinitionResolver = ServiceLocator.Current.GetInstance<ISiteDefinitionResolver>();
    var site = siteDefinitionResolver.GetByContent(currentPage.ContentLink, true);

    var contentLoader = ServiceLocator.Current.GetInstance<IContentLoader>();
    var ancestors = contentLoader.GetAncestors(currentPage.ContentLink).Select(c => c.ContentGuid).ToArray();
    var trackingData = new TrackingData<dynamic> { EventType = "epiPageView", PageTitle = currentPage.Name, Value = currentPage.ContentLink.ToString(), Payload = new { epi = new
    contentGuid = currentPage.ContentGuid,
    language = language.Name,
    siteId = site.Id,
    ancestors = ancestors
    } } };

    var trackingService = ServiceLocator.Current.GetInstance<ITrackingService>(); trackingService.Track(trackingData, ControllerContext.RequestContext.HttpContext); }

Note: For site tracking, this code should be in every page. You can also use PageViewTracking Attribute.

Tracking custom events

You can track custom events to Profile Store. Update StartPageController to track page views in the same way as the PageViewTrackingAttribute, but directly to tracking service using ITrackingService:

public class StartPageController : PageControllerBase<StartPage>
private readonly ITrackingService _trackingService;
private readonly HttpContextBase _httpContextBase;
private readonly ISiteDefinitionResolver _siteDefinitionResolver;
private readonly IContentLoader _contentLoader;

public StartPageController(
  ITrackingService trackingService, 
  HttpContextBase httpContextBase, 
  ISiteDefinitionResolver siteDefinitionResolver,
  IContentLoader contentLoader)
	_trackingService = trackingService;
	_httpContextBase = httpContextBase;
	_siteDefinitionResolver = siteDefinitionResolver;
	_contentLoader = contentLoader;

public ActionResult index(StartPage currentpage)
{ var model = PageViewModel.Create(currentPage); if (SiteDefinition.Current.StartPage.CompareToIgnoreWorkID(currentPage.ContentLink)) // Check if it is the StartPage or just a page of the StartPage type. { //Connect the view models logotype property to the start page's to make it editablevar editHints = ViewData.GetEditHints<PageViewModel<StartPage>, StartPage>(); editHints.AddConnection(m => m.Layout.Logotype, p => p.SiteLogotype); editHints.AddConnection(m => m.Layout.ProductPages, p => p.ProductPageLinks); editHints.AddConnection(m => m.Layout.CompanyInformationPages, p => p.CompanyInformationPageLinks); editHints.AddConnection(m => m.Layout.NewsPages, p => p.NewsPageLinks); editHints.AddConnection(m => m.Layout.CustomerZonePages, p => p.CustomerZonePageLinks); } Track(currentPage); return View(model); } private void Track(PageData pageData) { var trackingData = new TrackingData<dynamic> { EventType = "epiPageView", Value = $"Viewed {pageData.Name}", Payload = new { epi = new { contentGuid = pageData.ContentGuid, language = pageData.Language.Name, siteId = _siteDefinitionResolver.GetByContent(pageData.ContentLink, true).Id, ancestors = _contentLoader.GetAncestors(pageData.ContentLink).Select(x => x.ContentLink) } } }; if (!string.IsNullOrWhiteSpace(EPiServer.Personalization.EPiServerProfile.Current.Email)) { trackingData.User = new UserData { Email = EPiServer.Personalization.EPiServerProfile.Current.Email, Name = EPiServer.Security.PrincipalInfo.CurrentPrincipal.Identity.Name }; } _trackingService.Track(trackingData, _httpContextBase); } }

The tracking services takes two arguments: TrackingData<T>, and HttpContextBase. The following example uses dynamic as the generic type. You should create classes for your tracking data types, because it is better to use the compiler for production code. Using dynamic in this example reduces the amount of code.

Sending request through the tracking service

Use the ITrackingService interface (EPiServer.Tracking.Core.ITrackingService) for tracking any form of tracking data. The interface contains theTrack method, which sends the tracking request.

public class MyEvent
	public string MyString {get; set;}
public class TrackingExample
	private readonly ITrackingService_trackingService;
	private readonly HttpContextBase_httpContextBase;
	public TrackingExample(ITrackingServicetrackingService, HttpContextBasehttpContextBase)
		_trackingService = trackingService;
		_httpContextBase = httpContextBase;
	public void Track()
		var trackingData=newTrackingData<MyEvent>
		  EventType = typeof(MyEvent).Name,
		  User = new UserData
		    Email = EPiServer.Personalization.EPiServerProfile.Current.Email,
		    Name = EPiServer.Security.PrincipalInfo.CurrentPrincipal.Identity.Name
		  Value = "Readablestringaboutthistrackingrequest.",
		  Payload = new MyEvent
		    MyString = "Fortracking,youknow!"
		_trackingService.Track(trackingData, _httpContextBase);

Install EPiServer.Tracking.PageView

EPiServer.Tracking.PageView sends page views in a recommended structure. You do not need to use the package page tracking because you can structure the Payload in the recommended way in a normal call to the ITrackingService:

Payload = new
	epi = new 
contentGuid = currentPage.ContentGuid,
language = language.Name,
siteId = site.Id,
ancestors = ancestors
} }

Also, ensure that EventType = "epiPageView" is set for page views.

Tracking page views is easiest done by installing the EPiServer.Tracking.PageView because it contains a PageViewTrackingAttribute that you can decorate on all controller action where page views should be tracked.

  1. Install the EPiServer.Tracking.PageView NuGet package from the Episerver NuGet source to your site by entering the following command at the Package manager prompt (PM>).
    install-package EPiServer.Tracking.PageView
  2. Add PageViewTrackingAttribute to your controller for page tracking: Select Controllers > DefaultPageController and add the PageViewTrackingAttribute above the index method.
    [TemplateDescriptor(Inherited = true)]
    public class DefaultPageController : PageControllerBase<SitePageData>
    { [PageViewTracking] public ViewResult Index(SitePageData currentPage) { var model = CreateModel(currentPage); return View(string.Format("~/Views/{0}/Index.cshtml", currentPage.GetOriginalType().Name), model); } /// <summary>
    /// Creates a PageViewModel where the type parameter is the type of the page.
    /// </summary>

    /// <remarks>
    /// Used to create models of a specific type without the calling method having to know that type.
    /// </remarks>

    private static IPageViewModel<SitePageData> CreateModel(SitePageData page) { var type = typeof(PageViewModel<>).MakeGenericType(page.GetOriginalType()); return Activator.CreateInstance(type, page) as IPageViewModel<SitePageData>; } }

    All pages that are generated using the DefaultPageController are now tracked as page views to Profile Store in a known format for Advance. The payload field of tracking events will contain subfields in the following structure:

    "epi": {
    	"contentGuid": "",
    	"language": "",
    	"siteId": "",
    	"ancestors": [],
    	"recommendationClick": ""

 Related topics

Do you have feedback on this documentation? Send an email to documentation@episerver.com. For development-related questions and discussions, refer to our Forums on https://world.episerver.com/forum/