How to add profile key value programmatically

During my investigation of Sitecore xDB I tried several things and I found out that I want to increase a the value of a profile key programmatically. This question was helpful but it did not provide the whole solution. In some cases maybe you need this. It has been tested on Sitecore 8.2 update 3.

using Sitecore.Analytics;
using Sitecore.Analytics.Tracking;
using System.Collections.Generic;
namespace MyProject.Foundation.Xdb.Utils
{
public static class XdbHelper
{
public static void TriggerProfileKey(string profileName, string profileKey, int value)
{
if (!Tracker.Enabled)
{
return;
}
if (!Tracker.IsActive)
{
Tracker.StartTracking();
}
Profile profile;
if (Tracker.Current.Interaction.Profiles.ContainsProfile(profileName))
{
profile = Tracker.Current.Interaction.Profiles[profileName];
}
else
{
var profiles = new List<Sitecore.Analytics.Model.ProfileData>
{
new Sitecore.Analytics.Model.ProfileData(profileName)
};
Tracker.Current.Interaction.Profiles.Initialize(profiles);
profile = Tracker.Current.Interaction.Profiles[profileName];
}
var scores = new Dictionary<string, float> { { profileKey, value } };
profile.Score(scores);
profile.UpdatePattern();
}
}
}
view raw XdbHelper.cs hosted with ❤ by GitHub

And the usage of the method is like the following.

After I hit the page I have the following entry in mongoDB, Interactions table.

Capture

Leave a comment