Wednesday 16 August 2017

Sitecore Tracking Field Parsing - the Native Way

When we assign profile cards, goals or attributes (outcomes, events, etc) to a page content item, Sitecore stores the information in the Tracking (actual name __tracking) field under the Advanced section, as XML which looks like below (I am using the Sitecore Helix Utilities demo site for example):


Now if we switch to the raw value, we will see it is stored in XML, which I have formatted it for ease of viewing:
  
<tracking>
   <profile id="{D016ADEF-7737-4289-A85F-FE0055F49C8E}" name="Utilities Persona" presets="evan the eco-owner|100||">
      <key name="Sign-up for service" value="1" />
      <key name="Solar_Enviro Programs" value="5" />
      <key name="Budget_Savings Offers" value="4" />
      <key name="H of H_Community" value="3" />
   </profile>
</tracking>

There might be some cases where you want to parse this and get the information out of it and I have seen many developers parsing it by loading the value into XmlDocument and then read its nodes. This works fine however we would imagine Sitecore should have already had something doing this?

Answer is yes of course :) So, we can use the following code to get a strongly-typed object that represents this information.

// using Sitecore.Analytics.Data;

var pageItem = Sitecore.Context.Item;
var trackingField = new TrackingField(pageItem.Fields["__Tracking"]);

// Loop through all profiles (if multiple profile cards are assigned)
foreach (var profile in trackingField.Profiles)
{
    // Loop through all profile keys for current profile.
    // Here we want only the ones that has value greater than 0, for example.
    foreach (var k in profile.Keys.Where(o=> o.Value > 0))
    {
        // Do something
    }
}

The above example shows how to read profiles. If you have stuff like campaigns, goals, events that you need, in the TrackingField class there are collections for them as well:


Note that goals are same as events so you will find it under the Events IEnumerable.

Hope this helps!

No comments:

Post a Comment