Create a personalization rule in Sitecore 9 to display the xConnect Contact Facet in xDB

In this post we will look at how to create a custom personalization rule to run based on the current user’s points. Based on the previous blog posts, we already update a user with their points on a scheduled basis.

I made a few more changes to display the points for the user by modifying the TopBarLinksRenderingModel.

In order to setup the custom rule which will compare the users points, use the following code in your project which will evaluate the points:

    1. using System.Linq;
    2. using Konabos.XConnect.Loyalty.Model.Facets;
    3. using Sitecore.Analytics;
    4. using Sitecore.Diagnostics;
    5. using Sitecore.Rules;
    6. using Sitecore.Rules.Conditions;
    8. namespace Feature.Konabos.Loyalty.Website.Sitecore_Customizations.Conditions
    9. {
    10. public class LoyaltyPointsCondition<T> : IntegerComparisonCondition<T> where T : RuleContext
    11. {
    12. public int Points { get; set; }
    14. protected override bool Execute(T ruleContext)
    15. {
    16. Assert.ArgumentNotNull(ruleContext, "ruleContext");
    17. Assert.IsNotNull(Tracker.Current, "Tracker.Current is not initialized");
    18. Assert.IsNotNull(Tracker.Current.Session, "Tracker.Current.Session is not initialized");
    19. Assert.IsNotNull(Tracker.Current.Session.Interaction, "Tracker.Current.Session.Interaction is not initialized");
    21. Value = Points;
    23. //get value from xDB
    24. int userPoints = 0;
    25. var xConnectFacets = Tracker.Current.Contact.GetFacet<Sitecore.Analytics.XConnect.Facets.IXConnectFacets>("XConnectFacets");
    26. if (xConnectFacets.Facets != null)
    27. {
    28. if (xConnectFacets.Facets.Where(f => f.Key == LoyaltyPointsFacet.DefaultFacetKey).FirstOrDefault().Value is LoyaltyPointsFacet loyaltyFacet)
    29. {
    30. userPoints = loyaltyFacet.PointsEarned;
    31. }
    32. }
    33. return Compare(userPoints);
    34. }
    35. }
    36. }

Next, go to /sitecore/system/Settings/Rules/Definitions/Tags and create a new Tag: Loyalty Points

Create a new element: Loyalty Points in /sitecore/system/Settings/Rules/Definitions/Elements

Add the Loyalty Points Tag to the Selected in /sitecore/system/Settings/Rules/Conditional Renderings/Tags/Default

Once all of this is setup, get to one of your components in the Experience Editor and add a condition which first your need.

If you have any questions or concerns, please get in touch with me. (@akshaysura13 on twitter or on Slack).