Skip to content

Instantly share code, notes, and snippets.

@islaytitans

islaytitans/ContactFactory.cs Secret

Last active Apr 11, 2017
Embed
What would you like to do?
How to get identified contacts from xDB taking into account if one already exists
private ContactRepository contactRepository = Sitecore.Configuration.Factory.CreateObject("tracking/contactRepository", true) as ContactRepository;
private ContactManager contactManager = Sitecore.Configuration.Factory.CreateObject("tracking/contactManager", true) as ContactManager;
public Contact GetContact(string emailAddress)
{
if (IsContactInSession(emailAddress))
{
return Tracker.Current.Session.Contact;
}
var existingContact = ContactRepository.LoadContactReadOnly(emailAddress);
Contact contact;
if (contact != null)
{
LockAttemptResult<Contact> lockResult = ContactManager.TryLoadContact(existingContact.ContactId);
switch (lockResult.Status)
{
case LockAttemptStatus.Success:
Contact lockedContact = lockResult.Object;
lockedContact.ContactSaveMode = ContactSaveMode.AlwaysSave;
contact = lockedContact;
break;
case LockAttemptStatus.NotFound:
contact = Tracker.Current.Session.Contact;
break;
default:
throw new Exception(this.GetType() + " Contact could not be locked - " + emailAddress);
}
}
// if Contact in session's identifier is set and not equal to email address create new Contact
else if (Tracker.Current.Session.Contact.Identifiers.Identifier != null
&& !Tracker.Current.Session.Contact.Identifiers.Identifier.Equals(emailAddress, StringComparison.InvariantCultureIgnoreCase))
{
contact = contactRepository.CreateContact(ID.NewID);
contact.System.Value = 0;
contact.System.VisitCount = 0;
contact.ContactSaveMode = ContactSaveMode.AlwaysSave;
}
// Contact in session's identifier is null use that Contact
else
{
contact = Tracker.Current.Session.Contact;
}
// If the matched Contact is not as the same as the Contact Sitecore loaded into session
// or the Contact in session is not identified
// then we need to call .Identify() - more on this later
if (!contact.ContactId.Equals(Tracker.Current.Session.Contact.ContactId)
|| (contact.ContactId.Equals(Tracker.Current.Session.Contact.ContactId) && Tracker.Current.Session.Contact.Identifiers.Identifier == null))
{
Tracker.Current.Session.Identify(emailAddress);
// Contact has been updated via Identify so update the reference
contact = Tracker.Current.Session.Contact;
}
return matchedContact;
}
private bool IsContactInSession(string emailAddress)
{
var tracker = Tracker.Current;
if (tracker != null &&
tracker.IsActive &&
tracker.Session != null &&
tracker.Session.Contact != null &&
tracker.Session.Contact.Identifiers != null &&
tracker.Session.Contact.Identifiers.Identifier != null &&
tracker.Session.Contact.Identifiers.Identifier.Equals(emailAddress, StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment