You may encounter use cases where you need to track visitor actions not covered by out-of-box options, or where you need to track additional details. Xperience allows you to define custom activities, which can then be logged through both client-side and server-side code.
Let's dive into the process of logging a custom activity when a visitor downloads a file using JavaScript, and logging a custom activity when a user clicks a like button using C#.
This guide requires the following:
Familiarity with C# (opens in a new tab), .NET Core (opens in a new tab), Dependency injection (opens in a new tab), and the MVC pattern (opens in a new tab).
A running instance of Xperience by Kentico, preferably 31.7.2 or higher.
The examples in this guide require that you:
Code samples
You can find a project with completed, working versions of code samples from this guide and others in the finished branch (opens in a new tab) of the Training guides repository.
The main branch (opens in a new tab) of the repository provides a starting point to code along with the guides.
The code samples in this guide are compatible .NET 8 (opens in a new tab) and later. They use C#12 features and syntax (opens in a new tab) , but they do not depend on any features introduced in later C# versions.
They come from a project that uses implicit using directives (opens in a new tab). You may need to add additional using directives to your code if your project does not use this feature.
The first step to logging custom activities is to create the activity types that represent them.
In the Xperience administration interface, navigate to the Activity types tab of the Contact management application and define activity types with the following values.
Let's explore two different approaches for logging custom activities, using one for each of the types we just defined.
The client-side activity logging example from the documentation calls a function from the onclick attribute of a specific button.
This example uses a similar function, but stores it in a separate file rather than inline, and dynamically registers it to any links with the downloadattribute. Make sure to include this attribute on any downloadable file links that you want to track.
handleClick that logs a custom activity as outlined in the documentation example.
a. Assign the filedownload custom activity type.
a. Set the value to the path of the current page.
a. Assign a meaningful title that includes the alt attribute of the specific download link if it exists.window.onload event, iterate through all the links on the page, and assign the handleClick function to the click event of any links with the download attribute present.window.onload = function () {
const links = document.getElementsByTagName("a");
for (let i = 0; i < links.length; i++) {
if (links[i].hasAttribute("download")) {
links[i].addEventListener("click", handleClick);
}
}
}
function handleClick() {
kxt('customactivity', {
type: 'filedownload',
value: window.location.pathname,
title: 'File downloaded - ' + this.getAttribute("alt"),
persona: developer
onerror: t => console.log(t)
});
}For the sake of readability, this example is not minified. In production scenarios, consider storing this file elsewhere and using an automated tool to render a minified version of this script to the wwwroot folder.
Following the same process as earlier in this series, create a view component class to conditionally render a script reference to your new JavaScript file to the page.
Add a folder called CustomActivityScripts in TrainingGuides.Web/Features/Activities/ViewComponents.
Create a view component to conditionally render the custom activity script if the current contact has consented to tracking.
using Microsoft.AspNetCore.Mvc;
using TrainingGuides.Web.Features.Activities.ViewComponents.Shared;
using TrainingGuides.Web.Features.DataProtection.Services;
namespace TrainingGuides.Web.Features.Activities.ViewComponents.CustomActivityScripts;
public class CustomActivityScriptsViewComponent : ViewComponent
{
private readonly ICookieConsentService cookieConsentService;
public CustomActivityScriptsViewComponent(ICookieConsentService cookieConsentService)
{
this.cookieConsentService = cookieConsentService;
}
public IViewComponentResult Invoke()
{
var model = new ContactTrackingAllowedViewModel()
{
ContactTrackingAllowed = cookieConsentService.CurrentContactCanBeTracked()
};
return View("~/Features/Activities/ViewComponents/CustomActivityScripts/CustomActivityScripts.cshtml", model);
}
}Add a view that renders a script tag for your FileDownloadActivityLogger.js file.
@using TrainingGuides.Web.Features.Activities.ViewComponents.Shared
@model ContactTrackingAllowedViewModel
@if (Model.ContactTrackingAllowed)
{
@*Scripts for logging custom activities*@
<script src="~/assets/js/FileDownloadActivityLogger.js"></script>
}The script is ready to be added to the layout view. To make the script work, you need to add Xperience activity logging API to the page, along with a reference to the javascript file from the previous section.
Navigate to ~Views/Shared/_Layout.cshtml in the TrainingGuides.Web project, and add a using directive for your new view component.
...
@using TrainingGuides.Web.Features.Activities.ViewComponents.CustomActivityScripts
...At the bottom of the body tag, use the tag helper to invoke the custom-activity-scripts view component.
...
<vc:custom-activity-scripts/>
</body>
...If you only expect to have download links in certain parts of your site, you can improve performance by using Razor sections (opens in a new tab) to only include these scripts for views which you know will show downloads.
The coding is done, so the functionality is ready to be tested.
Run the TrainingGuides.Web project on your dev machine and visit the site in your browser.
Check your browser cookies in your browser's developer tools, and ensure that the CMSCookieLevel cookie is set to 1000 or above.
If you've completed the consent-related training guides, go to the /cookie-policy page and set your preferred cookie level to Marketing.
Visit the /policy-downloads page and click to download the privacy policy PDF.
Visit the /adminpath to sign in to the administration interface.
Navigate to the Activities tab of the Contact management application to see that the download activity has been logged.
The next custom activity scenario we will explore is a Page like widget demonstrating server-side logging with C# code. You will implement a controller action that logs a custom activity, and a widget that posts to the controller.
Create a strongly-typed class to represent the data that the widget will post to the controller, to make working with the data easier. In this case, you only need information to identify which page was liked, and to retrieve the correct item, so the Id of the web page content item, and the name of the content type should suffice.
namespace TrainingGuides.Web.Features.Activities.Widgets.PageLike;
public class PageLikeRequestModel
{
public string WebPageItemID { get; set; } = string.Empty;
}You may have noticed that the content item query api requires a strongly typed mapping function in order to select the results of the query.
However, since you're building a widget, you may not know the content type of the web page item that your widget is placed on.
In order to account for this, you need a way to retrieve a web page item by ID when you don't necessarily know its content type. For this, you can use the IWebPageFieldsSource interface that all generated web page content types implement.
ContentItemRetrieverService class in ContentItemRetrieverService.cs.RetrieveWebPageById, taking the Id of a web page and optional language name as parameters.RetrieveWebPages method.
...
/// <inheritdoc />
public async Task<IWebPageFieldsSource?> RetrieveWebPageById(
int webPageItemId,
int depth = 2,
string? languageName = null)
{
var pages = await RetrieveWebPages(parameters =>
{
parameters.Where(where => where.WhereEquals(nameof(WebPageFields.WebPageItemID), webPageItemId));
},
depth,
languageName ?? preferredLanguageRetriever.Get());
return pages.FirstOrDefault();
}
...We are using the Content item retrieval API instead of ContentRetriever API.
As an alternative approach you could use the ContentRetriever API, but because of its limitations, this would require listing all possible page content type code names, as the page types only share an interface, not a base class. See comment at the RetrieveWebPageByContentItemGuid method in the finished branch of our Training guides repo (opens in a new tab).
The controller is central to the functionality of the Page like widget. It is where you must log the custom activity and account for any errors.
ICustomActivityLogger, an IContentItemRetrieverService, and an ICookieConsentService through constructor injection.HttpPost attribute to register it to the route ~/pagelike for POST requests.CurrentContactCanBeTracked method from earlier in this series to return a message if the visitor has not consented to tracking.WebPageItemID from the provided PageLikeRequestModel.IContentItemRetrieverService to retrieve the web page item specified by the supplied Id.CustomActivityData object, including relevant information about the liked page in the ActivityTitle and ActivityValue, before logging the activity as described in the documentation.using CMS.Activities;
using Microsoft.AspNetCore.Mvc;
using TrainingGuides.Web.Features.DataProtection.Services;
using TrainingGuides.Web.Features.Shared.Services;
namespace TrainingGuides.Web.Features.Activities.Widgets.PageLike;
public class PageLikeController : Controller
{
private const string NO_TRACKING_MESSAGE = "<span>You have not consented to tracking, so we cannot save this page like.</span>";
private const string BAD_PAGE_DATA_MESSAGE = "<span>Error in page like data. Please try again later.</span>";
private const string THANK_YOU_MESSAGE = "<span>Thank you!</span>";
private readonly ICustomActivityLogger customActivityLogger;
private readonly IContentItemRetrieverService contentItemRetrieverService;
private readonly ICookieConsentService cookieConsentService;
public PageLikeController(
ICustomActivityLogger customActivityLogger,
IContentItemRetrieverService contentItemRetrieverService,
ICookieConsentService cookieConsentService)
{
this.customActivityLogger = customActivityLogger;
this.contentItemRetrieverService = contentItemRetrieverService;
this.cookieConsentService = cookieConsentService;
}
[HttpPost("/pagelike")]
public async Task<IActionResult> PageLike(PageLikeRequestModel requestModel)
{
if (!cookieConsentService.CurrentContactCanBeTracked())
return Content(NO_TRACKING_MESSAGE);
if (!int.TryParse(requestModel.WebPageItemID, out int webPageItemID))
return Content(BAD_PAGE_DATA_MESSAGE);
var webPage = await contentItemRetrieverService.RetrieveWebPageById(
webPageItemID);
if (webPage is null)
return Content(BAD_PAGE_DATA_MESSAGE);
string likedPageName = webPage.SystemFields.WebPageItemName;
string likedPageTreePath = webPage.SystemFields.WebPageItemTreePath;
string likedPageGuid = webPage.SystemFields.WebPageItemGUID.ToString();
var pageLikeActicityData = new CustomActivityData()
{
ActivityTitle = $"Page like - {likedPageTreePath} ({likedPageName})",
ActivityValue = likedPageGuid,
};
customActivityLogger.Log(PageLikeWidgetViewComponent.ACTIVITY_IDENTIFIER, pageLikeActicityData);
return Content(THANK_YOU_MESSAGE);
}
}The Page like widget will have a relatively simple view model, considering its basic requirements.
To meet both of these requirements, create a model with the Id and a boolean property to indicate whether or not the button should be displayed, as well as the base URL of the site, so the widget can construct the URL of the controller action.
namespace TrainingGuides.Web.Features.Activities.Widgets.PageLike;
public class PageLikeWidgetViewModel
{
public bool ShowLikeButton { get; set; }
public int WebPageItemID { get; set; }
public string BaseUrl { get; set; } = string.Empty;
}The widget's view component needs to populate the view model. It must retrieve the ID of the current web page item, and also determine whether or not the current visitor has already liked the page, in order to pass that information along to the widget.
Create a file called PageLikeWidgetViewComponent.cs in the TrainingGuides.Web/Features/Activities/Widgets/PageLike folder.
Use the RegisterWidget assembly attribute to register the widget, using a newly defined constant that holds the widget identifier.
Add another constant to hold the identifier of the page like activity.
Acquire IInfoProvider<ActivityInfo> and IContentItemRetrieverService objects with constructor injection.
Define the InvokeAsync method, using IInfoProvider<ActivityInfo> to query for existing page-like activities of the current web page item by the current contact.
Remember that in the controller, you stored the Guid of the current web page to the custom activity's ActivityValue. You can use this field to look up likes of the current page.
If no existing likes are found, set ShowLikeButton to true in a new PageLikeWidgetViewModel instance.
Use the Page property of the provided ComponentViewModel parameter to populate the remaining properties of the PageLikeWidgetViewModel.
Return the path to a view in the same folder, which will be added in the next section.
using CMS.Activities;
using CMS.ContactManagement;
using TrainingGuides.Web.Features.Activities.Widgets.PageLike;
using Kentico.PageBuilder.Web.Mvc;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewComponents;
using TrainingGuides.Web.Features.Shared.Services;
using CMS.DataEngine;
[assembly: RegisterWidget(
identifier: PageLikeWidgetViewComponent.IDENTIFIER,
viewComponentType: typeof(PageLikeWidgetViewComponent),
name: "Page like button",
Description = "Displays a page like button.",
IconClass = "icon-check-circle")]
namespace TrainingGuides.Web.Features.Activities.Widgets.PageLike;
public class PageLikeWidgetViewComponent : ViewComponent
{
private readonly IInfoProvider<ActivityInfo> activityInfoProvider;
private readonly IContentItemRetrieverService contentItemRetrieverService;
private readonly IHttpRequestService httpRequestService;
public const string IDENTIFIER = "TrainingGuides.PageLikeWidget";
public const string ACTIVITY_IDENTIFIER = "pagelike";
public PageLikeWidgetViewComponent(IInfoProvider<ActivityInfo> activityInfoProvider,
IContentItemRetrieverService contentItemRetrieverService,
IHttpRequestService httpRequestService)
{
this.activityInfoProvider = activityInfoProvider;
this.contentItemRetrieverService = contentItemRetrieverService;
this.httpRequestService = httpRequestService;
}
public async Task<ViewViewComponentResult> InvokeAsync(ComponentViewModel properties)
{
var currentContact = ContactManagementContext.GetCurrentContact(false);
var webPage = await contentItemRetrieverService.RetrieveWebPageById(
properties.Page.WebPageItemID);
var likesOfThisPage = currentContact != null
? await activityInfoProvider.Get()
.WhereEquals("ActivityContactID", currentContact.ContactID)
.And().WhereEquals("ActivityType", ACTIVITY_IDENTIFIER)
.And().WhereEquals("ActivityValue", webPage?.SystemFields.WebPageItemGUID.ToString())
.GetEnumerableTypedResultAsync()
: [];
bool showLikeButton = likesOfThisPage.Count() == 0;
var model = new PageLikeWidgetViewModel()
{
ShowLikeButton = showLikeButton,
WebPageItemID = properties.Page.WebPageItemID,
BaseUrl = httpRequestService.GetBaseUrl()
};
return View("~/Features/Activities/Widgets/PageLike/PageLikeWidget.cshtml", model);
}
}In the future, you may need to limit which widgets are available in different Page Builder sections and zones. To make this easier, add the page like widget's identifier to the ComponentIdentifiers class.
Widgets inside the ComponentIdentifiers class if it does not already exist.public static class ComponentIdentifiers
{
...
public static class Widgets
{
...
public const string PAGE_LIKE = PageLikeWidgetViewComponent.IDENTIFIER;
...
}
...
}The last piece you need to add is the view file referenced by the view component.
If you didn't follow along with the Data protection series yet, add a dependency on the AspNetCore.Unobtrusive.Ajax NuGet Package, and add the following line to the part of Program.cs where services are added to the application builder.
...
builder.Services.AddUnobtrusiveAjax();
...Add a view file called PageLikeWidget.cshtml to the TrainingGuides.Web/Features/Activities/Widgets/PageLike folder.
Create an AJAX form that posts to the path of the controller action from earlier. a. Pass the Id of a div for the AJAX form to write its response. a. Use a hidden input to pass the web page item's Id to the controller action when the widget submits the form.
@using TrainingGuides.Web.Features.Activities.Widgets.PageLike;
@model PageLikeWidgetViewModel
@{
var messageId = "pageLikeMessage";
}
@if(Model.ShowLikeButton || Context.Kentico().Preview().Enabled)
{
@using (Html.AjaxBeginForm("PageLike", "PageLike", new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = messageId
}, new { action = $"{Model.BaseUrl}/pagelike" }))
{
<div class="container">
<div class="cookie-preferences js-cookie-preferences">
<input id="WebPageItemID" name="WebPageItemID" type="hidden" value="@Model.WebPageItemID" />
<button class="btn btn-secondary text-uppercase mt-4 cookie-preferences__button" type="submit" name="button">
Like this page
</button>
<div id="@messageId" class="cookie-preferences__message"></div>
</div>
</div>
}
}The coding is done, so you can test your new widget.
The next guide in this series will cover the process of creating a page section that hides its contents from contacts who have not consented to tracking, preventing them from submitting data through any widgets in the section.