List Manager: Creating a Contact List from an external source programmatically

Version

Sitecore 8 Update 2 (150223)

    EXM 3 rev 150223

Task

Create a list manager contact list programmatically from an external data source which can be used as a recipient list for an EXM email message.

Details

First we’ll create a recipient list.

The using statements needed:

[sourcecode language=”text”]
using Sitecore.Analytics.Data;
using Sitecore.Analytics.DataAccess;
using Sitecore.Analytics.Model;
using Sitecore.Analytics.Model.Entities;
using Sitecore.Analytics.Tracking;
using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.ListManagement.ContentSearch;
using Sitecore.ListManagement.ContentSearch.Model;
using ContactData = Sitecore.ListManagement.ContentSearch.Model.ContactData;
[/sourcecode]

Create the list and associate contacts with the list

[sourcecode language=”text”]
var listManager = Sitecore.Configuration.Factory.CreateObject("contactListManager", false) as ContactListManager;
var list = new ContactList(ListName);
try {
//Create list if necessary
listManager.Create(list);
var listId = list.Id; //is assigned after creation.
listManager.AssociateContacts(list, GetContactDatas());
}

[/sourcecode]

Get the contacts for the list

[sourcecode language=”text”]
protected List<ContactData> GetContactDatas()
{
List<ContactData> returnList = new List<ContactData>();

// … Read the external datasource into Identifier, FirstName,LastName,EmailAddress …
// … Loop through each contact read
// Add or update the contact
ContactData contact = CreateContact(Identifier, FirstName,LastName,EmailAddress);
if (contact != null) returnList.Add(contact);

return returnList;
}
[/sourcecode]

Create or update the contact to associate with the list

[sourcecode language=”text”]
// Add contact if the Identifier is not found, otherwise, update the existing contact
protected ContactData CreateContact(string identifier, string firstName, string lastName, string emailAddress)
{
if (String.IsNullOrEmpty(identifier)) return null;
var contactRepo = Factory.CreateObject("contactRepository", true) as ContactRepository;
LeaseOwner leaseOwner = new LeaseOwner(identifier, LeaseOwnerType.OutOfRequestWorker);

Contact newContact = null;

LockAttemptResult<Contact> result = contactRepo.TryLoadContact(identifier, leaseOwner, TimeSpan.FromMinutes(1.0));
switch (result.Status)
{
case LockAttemptStatus.Success:
// Existing Contact
newContact = result.Object as Contact;

// Email Facet
var emailFacet = newContact.GetFacet&lt;IContactEmailAddresses&gt;(_facetEmails); //_facetEmails = "Emails";
if (!string.IsNullOrEmpty(emailFacet.Preferred))
{
IEmailAddress address = emailFacet.Entries[emailFacet.Preferred];
address.SmtpAddress = emailAddress;
}
emailFacet.Preferred = _facetEmailPreferred; //_facetEmailPreferred = "Preferred";
break;
case LockAttemptStatus.NotFound:
// New Contact
ID guid = Sitecore.Data.ID.NewID;
newContact = contactRepo.CreateContact(guid);
newContact.Identifiers.Identifier = identifier;

// Email Facet
var emailFacetNew = newContact.GetFacet&lt;IContactEmailAddresses&gt;(_facetEmails); //_facetEmails = "Emails";
emailFacetNew.Entries.Create(_facetEmailPreferred).SmtpAddress = emailAddress;
emailFacetNew.Preferred = _facetEmailPreferred;

break;
default:
throw new NotImplementedException("Handling of collection database locking failures is not yet implemented.");
}

if (newContact != null)
{
// Create and Update same once we have the contact
var personalInfoNew = newContact.GetFacet&lt;IContactPersonalInfo&gt;("Personal");
personalInfoNew.FirstName = firstName;
personalInfoNew.Surname = lastName;
}
newContact.ContactSaveMode = ContactSaveMode.AlwaysSave;
try
{
contactRepo.SaveContact(newContact,new ContactSaveOptions(true, leaseOwner));
}
catch (Exception ExContactNotSaved)
{
//if (ExContactNotSaved Error is exists and not testing for existence)
string message = ExContactNotSaved.Message.ToString();
}

return new ContactData()
{
Identifier = identifier
};
}</pre>
<pre>[/sourcecode]

Here’s an example of an imported contact in Mongo Db with the Contact List associated as a Tag:

SitecoreContactInMongoDbWithContactListTag

The list in Sitecore List Manager:

ListManagerContactListImportFromODS