0

We have migrated from Sitecore 8.2 to Sitecore 10.2, We are facing issue with Personalization set in our login page.

1.User logins using their credential and gets redirected to another application. When this happens we set a custom value. We are using custom facet to store this data. 2.When user logs off he is able to see the expected personalization message. 3.When the same user closes the browser and logins after a day or two, we expect to see the personalization message in our login screen, this is not working as expected.

Following code, we are using to save the facet data,

private static void UpdateContactFacet(UserInfo userInfo)
    {
        using (XConnectClient client = SitecoreXConnectClientConfiguration.GetClient())
        {
            try
            {
                Sitecore.XConnect.Contact contact = null;
                ContactManager contactManager = (ContactManager)Factory.CreateObject("tracking/contactManager", true);
                if (contactManager != null)
                {
                    string customUserFacetKey = CustomUserInformation.DefaultFacetKey;
                    if (Tracker.Current.Contact.IsNew)
                    {
                       

                        // Save contact to xConnect; at this point, a contact has an anonymous
                        // TRACKER IDENTIFIER, which follows a specific format. Do not use the contactId overload
                        // and make sure you set the ContactSaveMode as demonstrated
                        Tracker.Current.Contact.ContactSaveMode = ContactSaveMode.AlwaysSave;
                        contactManager.SaveContactToCollectionDb(Tracker.Current.Contact);
                        // Now that the contact is saved, you can retrieve it using the tracker identifier
                        // NOTE: Sitecore.Analytics.XConnect.DataAccess.Constants.IdentifierSource is marked internal in 9.0 Initial and cannot be used. If you are using 9.0 Initial, pass "xDB.Tracker" in as a string.
                        var trackerIdentifier = new Sitecore.XConnect.IdentifiedContactReference(Sitecore.Analytics.XConnect.DataAccess.Constants.IdentifierSource, Sitecore.Analytics.Tracker.Current.Contact.ContactId.ToString("N"));
                        contact = client.Get(trackerIdentifier, new Sitecore.XConnect.ContactExecutionOptions(new Sitecore.XConnect.ContactExpandOptions()));
                    }
                    else
                    {
                        
                        var anyIdentifier = Tracker.Current?.Contact?.Identifiers?.FirstOrDefault();
                                                    contact = client.Get(new IdentifiedContactReference(anyIdentifier?.Source, anyIdentifier?.Identifier),
                        new ContactExecutionOptions(new Sitecore.XConnect.ContactExpandOptions(customUserFacetKey)));
                    }
                    if (contact != null)
                    {
                       
                        var userInfoFacet = contact.GetFacet<CustomUserInformation>(CustomUserInformation.DefaultFacetKey);
                        if (userInfoFacet == null)
                        {
                            
                            userInfoFacet = new userInfo()
                            {
                                CustomValues = userInfo?.CustomValues != null ? JsonConvert.SerializeObject(userInfo?.CustomValues) : string.Empty,
                                UserId = userInfo?.UserId
                            };
                           
                        }
                        else
                        {
                            
                            userInfoFacet.CustomValues = userInfo?.CustomValues != null ? JsonConvert.SerializeObject(userInfo?.CustomValues) : string.Empty;
                            userInfoFacet.UserId = userInfo?.UserId;
                           

                        }
                        client.SetFacet(contact, CustomUserInformation.DefaultFacetKey, userInfoFacet);
                        client.Submit();
                        // Remove contact data from shared session state - contact will be re-loaded
                        // during subsequent request with updated facets
                        contactManager.RemoveFromSession(Tracker.Current.Contact.ContactId);
                        Tracker.Current.Session.Contact = contactManager.LoadContact(Tracker.Current.Contact.ContactId);

                    }
                }
            }

Code used to retrieve the Custom Value:

private IList<UserData> GetCustomValues(Sitecore.Analytics.Tracking.Contact contact)
    {
        IList<UserData> customValues = null;
        try
        {
           
            var xConnectFacet = contact?.GetFacet<Sitecore.Analytics.XConnect.Facets.IXConnectFacets>("XConnectFacets");
            if (xConnectFacet != null && xConnectFacet.Facets != null && xConnectFacet.Facets.ContainsKey(CustomUserInformation.DefaultFacetKey))
            {
               
                CustomUserInformation userData = xConnectFacet.Facets[CustomUserInformation.DefaultFacetKey] as CustomUserInformation;
                if (userData != null)
                {
                    customValues = JsonConvert.DeserializeObject<IList<CustomValues>>(userData?.CustomValues);
                return customValues;
            }
        }
        catch (Exception ex)
        {
            
        }
        return customValues;
    }



enter code here

How to get the personalization working if user logins later after a day or so? How to retrieve the contact data from the xDB?

Note: I can see the Custom Facet Data getting stored in ContactFacet table. I have added the config to load the value into the session.

1 Answer 1

1

You need to call the IdentifyAs method as below once the users logs into the website, for identification of contacts.

  using Sitecore.Mvc.Pipelines.Request.RequestBegin;
  using System;
  using System.Linq;
  using Sitecore.Analytics;
  using Microsoft.Extensions.DependencyInjection;
  public class IdentifyContactOnLoad : RequestBeginProcessor
  {
    public override void Process(RequestBeginArgs args)
    {
      try
      {
        string source = "{{Website_Source}}";
        string identifier = "{{User_Unique_Identifier}}";
        if (Tracker.Current.Session.Contact.Identifiers.Any(x => x.Source == source && x.Identifier == identifier))
        {
          return;
        }
        var identificationManager = Sitecore.DependencyInjection.ServiceLocator.ServiceProvider.GetRequiredService<Sitecore.Analytics.Tracking.Identification.IContactIdentificationManager>();
        identificationManager.IdentifyAs(new Sitecore.Analytics.Tracking.Identification.KnownContactIdentifier(source, identifier));
       }
       catch (Exception ex)
       {
         Sitecore.Diagnostics.Log.Error("Exception occurred during tracking.", ex, this);
       }
    }
  }

You can call this code under the *mvc.requestBegin* pipeline using below configuration.

<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <mvc.requestBegin>
        <processor type="CustomExtensions.IdentifyContactOnLoad,CustomExtensions" patch:after="processor[@type='Sitecore.Mvc.Analytics.Pipelines.MvcEvents.RequestBegin.StartTracking, Sitecore.Mvc.Analytics']" />
        </mvc.requestBegin>
    </pipelines>
  </sitecore>
</configuration>

Above code make sure, when the users logs into the website a known identifer is added, so that when the same user logs back to the website, its contact data and related facets gets automatically loaded to the session.

You can find more details on identifying contacts through the below link:

https://doc.sitecore.com/xp/en/developers/102/sitecore-experience-platform/tracking-contacts.html

Hope this helps!!!

8
  • Can we use Tracker.Current.Contact.ContactId.ToString("N") as identifier Commented Apr 24 at 8:20
  • @VisvaKiruthikaMuthuraj It's better if you can use some details of user information such as email as an identifier, since a new contact id will be created when the analytics cookie is expired or cleared.
    – ckhanna
    Commented Apr 24 at 13:19
  • I tried to use user id as identifier, but when the user closes the browser and visits the site again, I am unable to fetch the identifier back. so Contact is returning null in this case. In our case I will not be able to use this source and identifier in begin request pipeline as we will not be getting the user id . Commented Apr 24 at 14:49
  • @VisvaKiruthikaMuthuraj Then in that case you can use Tracker.Current.Contact.ContactId.ToString("N") as an identifier. This will solve your issue.
    – ckhanna
    Commented Apr 24 at 14:58
  • update as you mentioned. But looks like each time user closes the SC_ANALYTICS_GLOBAL_COOKIE value gets updated. As per sitecore documention,SC_ANALYTICS_GLOBAL_COOKIE value should be same on second visit until the cache is cleared. But this is not working Commented Apr 24 at 20:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.