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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
And the usage of the method is like the following.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.