How to update a Sitecore contact identifier

In some cases you might want to update the identifier of a Sitecore contact. To accomplish this you can do one of two things: write some Mongo queries or use the Sitecore API. For this blog I will explain how to use the Sitecore API.

Sitecore contact identifier

The implementation
When you want to change the identifier using the Sitecore API, you need to create an instance of the ContactManager. This manager is configured in the Sitecore.Analytics.Tracking.config file. You can use the Factory class to create an instance of this manager:

var contactManager = Sitecore.Configuration.Factory.CreateObject("tracking/contactManager", true) as Sitecore.Analytics.Tracking.ContactManager;

You are able to load a contact from the Experience database when the contact manager is created.

var lockedContact = this.ContactManager.TryLoadContact(contactId);

Before you can perform any updates, you have to be sure the contact is locked successfully. To be able to do this, you have to check the Status property on the lockedContact object. If the status is Success than you can apply the new identifier.

lockedContact.Object.Identifiers.Identifier = "MyNewIdentifier";

Save the contact after you have applied your update. This update first needs to be saved to the shared session state and the Experience database. You can do this by calling to different SaveAndRelease methods.

contactManager.SaveAndReleaseContact(lockedContact.Object);
contactManager.SaveAndReleaseContactToXdb(lockedContact.Object);

Call the release method on the contact manager when you don’t want to change your updates and unlock your contact.

this.ContactManager.ReleaseContact(ic.UserData.Identifiers.XDbContactId);

After you have updated your contact, there are two collections in the analytics database where the identifier should be updated:

In the contact collection: the contact’s identifier is updated to the new identifier
In the identifiers collection: the identifier is updated to the new identifier
Conclusion
It is not very hard to change the identifier of your contact. All you need to know is how to gain access to the contact manager and how to use it.

Related blog

Onze technische blogs zijn in het Engels. Dit doen wij omdat wij menen dat technische kennis van Sitecore en Sitefinity grensoverschrijdend moet zijn. Wij leren veel van buitenlandse developers, wij delen onze kennis ook graag met hen. Mochten er in de code fouten zitten of punten ter verbetering, dan gaan we graag het gesprek aan.