Skip to content

Instantly share code, notes, and snippets.

@lowedown
Last active May 2, 2022 22:13
Show Gist options
  • Save lowedown/9fc61ac8999f6440ef6b006dc58f4c5e to your computer and use it in GitHub Desktop.
Save lowedown/9fc61ac8999f6440ef6b006dc58f4c5e to your computer and use it in GitHub Desktop.
XConnect Contact Repository and service for use in Sitecore components (Tracker must be active)
// Important: Get consent from user first before identifying. Make sure all applicable rules and regulations are followed correctly.
var service = new TrackingService();
service.IdentifyAs("e-mail", "[email protected]");
service.SetContactName("John", "Doe");
service.SetContactEmail("[email protected]");
using System.Linq;
using Sitecore.Analytics;
using Sitecore.XConnect.Collection.Model;
namespace XConnectExample
{
public class TrackingService
{
private readonly XConnectContactRepository _contactRepository = new XConnectContactRepository();
public bool IdentifyAs(string source, string identifier)
{
if (Tracker.Current == null)
{
return false;
}
// Contact already has the identifier
if (Tracker.Current.Session.Contact.Identifiers.Any(x => x.Source == source && x.Identifier == identifier))
{
return true;
}
Tracker.Current.Session.IdentifyAs(source, identifier);
return true;
}
public void SetContactName(string firstname, string lastname)
{
if (string.IsNullOrEmpty(firstname) || string.IsNullOrEmpty(lastname))
{
return;
}
Sitecore.XConnect.Contact contact = _contactRepository.GetCurrentContact(PersonalInformation.DefaultFacetKey);
PersonalInformation personalInfo = contact.Personal() ?? new PersonalInformation();
personalInfo.FirstName = firstname;
personalInfo.LastName = lastname;
_contactRepository.SaveFacet(contact, PersonalInformation.DefaultFacetKey, personalInfo);
_contactRepository.ReloadCurrentContact();
}
public void SetContactEmail(string email)
{
if (string.IsNullOrEmpty(email))
{
return;
}
Sitecore.XConnect.Contact contact = _contactRepository.GetCurrentContact(EmailAddressList.DefaultFacetKey);
EmailAddressList emails = contact.Emails() ?? new EmailAddressList(new EmailAddress(email, true), "default");
emails.PreferredEmail = new EmailAddress(email, true);
_contactRepository.SaveFacet(contact, EmailAddressList.DefaultFacetKey, emails);
_contactRepository.ReloadCurrentContact();
}
}
}
using System;
using System.Linq;
using Sitecore.Analytics;
using Sitecore.Analytics.Model;
using Sitecore.Analytics.XConnect.Facets;
using Sitecore.Diagnostics;
using Sitecore.XConnect;
using Sitecore.XConnect.Client;
using Sitecore.XConnect.Client.Configuration;
using ContactIdentifier = Sitecore.Analytics.Model.Entities.ContactIdentifier;
namespace XConnectExample
{
public class XConnectContactRepository
{
public Sitecore.XConnect.Contact GetContact(string source, string identifier, params string[] facetKey)
{
if (facetKey == null)
{
facetKey = new string[0];
}
Log.Debug($"XConnectContactService: GetContact() Source:{source} Identifier:{identifier} FacetKeys:{string.Join(",", facetKey)}", this);
using (XConnectClient client = SitecoreXConnectClientConfiguration.GetClient())
{
try
{
if (facetKey == null || facetKey.Length == 0 ||
(facetKey.Length == 1 && string.IsNullOrEmpty(facetKey[0])))
{
return client.Get<Sitecore.XConnect.Contact>(new IdentifiedContactReference(source, identifier),
new ContactExpandOptions());
}
return client.Get<Sitecore.XConnect.Contact>(new IdentifiedContactReference(source, identifier),
new ContactExpandOptions(facetKey));
}
catch (XdbExecutionException ex)
{
Log.Error(
$"XConnectContactService: Unable to get contact for Identifier '{identifier}', Source: '{source}', FacetKey(s): '{string.Join(",", facetKey)}'",
ex, this);
return null;
}
catch (Exception ex)
{
Log.Error("XConnectContactService: Error communication with the xConnect colllection service",
ex, this);
return null;
}
}
}
public Sitecore.XConnect.Contact GetContact(Guid id, params string[] facetKey)
{
if (facetKey == null)
{
facetKey = new string[0];
}
Log.Debug($"XConnectContactService: GetContact() Id:{id} FacetKeys:{string.Join(",", facetKey)}", this);
using (XConnectClient client = SitecoreXConnectClientConfiguration.GetClient())
{
try
{
if (facetKey.Length == 0 || (facetKey.Length == 1 && string.IsNullOrEmpty(facetKey[0])))
{
return client.Get<Sitecore.XConnect.Contact>(new ContactReference(id),
new ContactExpandOptions());
}
return client.Get<Sitecore.XConnect.Contact>(new ContactReference(id),
new ContactExpandOptions(facetKey));
}
catch (XdbExecutionException ex)
{
Log.Error(
$"XConnectContactService: Unable to get contact for Contact ID '{id}', FacetKey(s): '{string.Join(",", facetKey)}'",
ex, this);
return null;
}
catch (Exception ex)
{
Log.Error("XConnectContactService: Error communication with the xConnect colllection service",
ex, this);
return null;
}
}
}
public bool SaveFacet<T>(Sitecore.XConnect.Contact contact, string FacetKey, T Facet) where T : Facet
{
Log.Debug($"XConnectContactService: SaveFacet() Contact ID:{contact?.Id} FacetKey:{FacetKey}", this);
using (XConnectClient client = SitecoreXConnectClientConfiguration.GetClient())
{
try
{
client.SetFacet(contact, FacetKey, Facet);
client.Submit();
return true;
}
catch (XdbExecutionException ex)
{
Log.Error(
$"XConnectContactService: Error saving contact data to xConnect. Facet: '{Facet}' Contact: '{contact.Id}'",
ex, this);
return false;
}
catch (Exception ex)
{
Log.Error("XConnectContactService: Error communication with the xConnect colllection service",
ex, this);
return false;
}
}
}
public bool ReloadCurrentContact()
{
Log.Debug($"XConnectContactService: ReloadCurrentContact()", this);
try
{
Sitecore.Analytics.Tracking.ContactManager manager =
Sitecore.Configuration.Factory.CreateObject("tracking/contactManager", true) as
Sitecore.Analytics.Tracking.ContactManager;
if (manager == null)
{
Log.Error("XConnectContactService:ReloadCurrentContact(): Unable to instantiate ContactManager",
this);
return false;
}
Guid contactId = Tracker.Current.Contact.ContactId;
manager.RemoveFromSession(contactId);
Tracker.Current.Session.Contact = manager.LoadContact(contactId);
if (Tracker.Current.Contact == null)
{
Log.Info("XConnectContactService: Tracker.Current.Contact is null after reloading.", this);
return false;
}
}
catch (XdbExecutionException ex)
{
Log.Error(
$"XConnectContactService: Error reloading current contact with ID '{Tracker.Current.Contact.ContactId}'",
ex, this);
return false;
}
catch (Exception ex)
{
Log.Error("XConnectContactService: Error communication with the xConnect colllection service", ex,
this);
return false;
}
return true;
}
public Sitecore.XConnect.Contact GetCurrentContact(string facetKey)
{
Log.Debug($"XConnectContactService: GetCurrentContact() FacetKey {facetKey}", this);
if (Tracker.Current == null)
{
Log.Error($"XConnectContactService: GetCurrentContact() Tracker is not active. Cannot read contact.", this);
return null;
}
Sitecore.Analytics.Tracking.ContactManager manager =
Sitecore.Configuration.Factory.CreateObject("tracking/contactManager", true) as
Sitecore.Analytics.Tracking.ContactManager;
if (manager == null)
{
Log.Error("XConnectContactService: Unable to instantiate ContactManager", this);
return null;
}
if (!IsContactIdentified(Tracker.Current.Contact))
{
Log.Info("XConnectContactService: GetCurrentContact() Contact is not identified yet. Saving first.", this);
// Save contact first
Tracker.Current.Contact.ContactSaveMode = ContactSaveMode.AlwaysSave;
manager.SaveContactToCollectionDb(Tracker.Current.Contact);
if (ReloadCurrentContact())
{
return GetContact(Sitecore.Analytics.XConnect.DataAccess.Constants.IdentifierSource,
Tracker.Current.Contact.ContactId.ToString("N"), facetKey);
}
}
ContactIdentifier id = Tracker.Current.Contact?.Identifiers.FirstOrDefault();
return id != null ? GetContact(id.Source, id.Identifier, facetKey) : null;
}
private bool IsContactIdentified(Sitecore.Analytics.Tracking.Contact trackingContact)
{
return !trackingContact.IsNew && trackingContact.Identifiers.Any();
}
public T GetFacet<T>(Sitecore.XConnect.Contact contact, string FacetKey) where T : Facet
{
Log.Debug($"XConnectContactService: GetFacet() Contact ID:{contact?.Id} FacetKey:{FacetKey}", this);
using (XConnectClient client = SitecoreXConnectClientConfiguration.GetClient())
{
try
{
return contact.GetFacet<T>(FacetKey);
}
catch (XdbExecutionException ex)
{
Log.Error(
$"XConnectContactService: Error reading facet '{FacetKey}' from contact '{contact.Id}'", ex,
this);
return null;
}
catch (Exception ex)
{
Log.Error("XConnectContactService: Error communication with the xConnect colllection service",
ex, this);
return null;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment