Skip to content

Instantly share code, notes, and snippets.

@Shedal
Created November 11, 2017 20:01
Show Gist options
  • Select an option

  • Save Shedal/012cd2622e5c14bb6e2c3d4ce16b6a6d to your computer and use it in GitHub Desktop.

Select an option

Save Shedal/012cd2622e5c14bb6e2c3d4ce16b6a6d to your computer and use it in GitHub Desktop.
void UpdateContact(string identifier, Action<Contact> updateMethod)
{
var contactRepository = (ContactRepositoryBase)Factory.CreateObject("contactRepository", true);
var sharedSessionManager = (SharedSessionStateManager)Factory.CreateObject("tracking/sharedSessionState/manager", true)
if (Tracker.Current.Contact != null && identifier == Tracker.Current.Contact.Identifiers.Identifier)
{
// The current contact is the one we need to update.
updateMethod(Tracker.Current.Contact);
}
else
{
// Find out if a contact with the given identifier exists in the database.
Contact databaseContact = contactRepository.LoadContactReadOnly(identifier);
if (databaseContact != null)
{
Guid contactId = databaseContact.ContactId;
// Try to load the contact from the Shared Session.
Contact sessionContact = sharedSessionManager.LockAndLoadContact(contactId);
if (sessionContact != null)
{
// Update this contact and release it back to the Shared Session.
updateMethod(sessionContact);
sharedSessionManager.SaveAndReleaseContact(sessionContact);
}
else
{
// In this branch, we know that the contact we need exists in the database, but it's not locked by our cluster.
// We'll try to lock it and update its data.
LeaseOwner leaseOwner = new LeaseOwner("SOME_UNIQUE_WORKER_NAME", LeaseOwnerType.OutOfRequestWorker);
LockAttemptResult<Contact> lockResult = contactRepository.TryLoadContact(identifier, leaseOwner, TimeSpan.FromMinutes(1));
if (lockResult.Status == LockAttemptStatus.Success)
{
// Update the contact and release it to the Collection DB.
updateMethod(lockResult.Object);
var options = new ContactSaveOptions(release: true, owner: leaseOwner);
contactRepository.SaveContact(lockResult.Object, options);
}
else
{
Log.Warn("Cannot modify the contact with identifier '" + identifier + "' because it is locked by another process.", this);
// Decide what else you want to do in that case.
// One option is to schedule a Sitecore Job to update the contact later:
// https://briancaos.wordpress.com/2012/02/06/using-sitecore-jobs/
}
}
}
else
{
// In this branch, we know that the contact with the provided identifier does not exist yet.
// You will have to decide what to do in that case. Below is an example where you identify the current contact.
Tracker.Current.Session.Identify(identifier);
updateMethod(Tracker.Current.Contact);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment