Thursday, March 16, 2017

Sitecore registering a goal or event on any page programatically

Registering a page event/goal in Sitecore is simple enough when you have the page/site context, such as a call on the code behind of a web control. There are cases where this is not available, for example via a service or generic MVC route and in these cases the goal will not register against the correct page.

In the following code example, it shows how the page context can be modified before the page event/goal is registered. That way it appears against the correct page in analytics. The origianl source for these methods was Brian Pedersen.
public static void RegisterAjaxEvent(string eventName, ID itemId, string text, string data, string dataKey)
{
    if (!Tracker.Enabled)
        return;

    if (!Tracker.IsActive)
        Tracker.StartTracking();

    IPageContext currentPage = Tracker.Current.CurrentPage;
    if (currentPage == null)
        return;

    RegisterEventOnCurrentPage(eventName, text, data, dataKey, currentPage, itemId);
}

private static void RegisterEventOnCurrentPage(string eventName, string text, string data, string dataKey, IPageContext currentPage, ID itemId)
{
    PageEventData pageEvent = new PageEventData(eventName)
    {
        Text = text,
        Data = data ?? string.Empty,
        DataKey = string.IsNullOrEmpty(dataKey) ? string.Empty : dataKey
    };
    try
    {
        // Register the event on the correct page
        if (!ID.IsNullOrEmpty(itemId))
        {
            var db = global::Sitecore.Data.Database.GetDatabase("web");
            var item = db.Items.GetItem(itemId);

            if (item != null)
            {
                var relativePath = item.Paths.Path.Replace("/sitecore/content/Home", "");
                if (string.IsNullOrEmpty(relativePath))
                {
                    relativePath = "/";
                }

                currentPage.SetUrl(relativePath);
                currentPage.SetItemProperties(itemId.ToGuid(), item.Language.Name, item.Version.Number);
            }
        }

        var result = currentPage.Register(pageEvent);
    }
    catch (Exception exception)
    {
        Log.Error(string.Format("{0} pageevent not created in current Sitecore Instance: {1}", eventName, exception), "");
    }
}
The difference with this version of  method is an additional itemId parameter, which is the ID of the page that the event/goal should be registered to. Then, before the event/goal is registered, the currentPage variable is updated to use the correct item id and URL (path).

In Sitecore analytics the URLs for these events/goals appear as relative paths, which is why the string replace is taking out the root path for the site.

No comments:

Post a Comment