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.

using MyProject.Foundation.Xdb.Utils;
using System.Web.Mvc;
namespace MyProject.Feature.Demo.Controllers
{
public class DemoController : Controller
{
public ActionResult Demo()
{
XdbHelper.TriggerProfileKey("Activity", "tennis", 10);
return View("~/Views/Demo.cshtml");
}
}
}

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

Capture

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s