3

I am using Sitecore 8.2 - Update 2 and EXM 3.4 - Update 1. I have a list, which I want to use for sending e-mail campaigns. I have a custom form, which I want to use for subscription. I found this article https://himynameistim.wordpress.com/2016/03/01/sitecore-programmatically-adding-contacts-to-a-list/ and I used this part of code:

public void AddContactToList(ContactData contact, ContactList list)
{
    ContactListManager listManager = Sitecore.Configuration.Factory.CreateObject("contactListManager", false) as ContactListManager;

    List<ContactData> contactList = new List<ContactData>();
    contactList.Add(contact);

    listManager.AssociateContacts(list, contactList);
}

Problem is, that list is locked after this, so no one else can be added to a list at the time list is locked.

I also tried this code:

var contactRepository = new ContactRepository();
var listManager = Factory.CreateObject("contactListManager", false) as ListManager<ContactList, ContactData>;
var contact = Tracker.Current.Contact;
foreach (var listId in listIds)
{
    var contactList = listManager.FindById(listId);
    if (contact.Tags.Find("ContactLists") != null && contact.Tags.Find("ContactLists").Values.Select(x => x.Value).Contains(listId))
    {
        continue;
    }
    contact.Tags.Set("ContactLists", contactList.Id);
}
var options = new ContactSaveOptions(true, null);
contact.ContactSaveMode = ContactSaveMode.AlwaysSave;
contactRepository.SaveContact(contact, options);

Problem is that a list write warning:

Please note that contacts in the list are currently being indexed, so not all contacts are available to view at this time. 1 out of 0 contacts are currently indexed.

Does anyone have functional method how to add a contact to a list?

5

If you are using EXM, then you can take advantage of Sitecore.Modules.EmailCampaign.ClientApi. Have a look at the the EXM ClientApi documentation for version 3.4 of EXM

listManager.AssociateContacts is fairly low-level code, and contact.Tags.Set even more so. As the post you link to points out, it is risky to use these APIs directly and manipulating the ContactLists on 'contact.Tags' should be avoided at all costs as it will lead to inconsistencies between the expected number of contacts on a List Manager list, and the actual number of contacts.

If you use ClientApi.Instance.UpdateSubscriptions, then EXM takes care of a lot of things on your behalf, including handling list/contact locking, and sending the request over a webservice to your Content Management server if you are using a scaled environment.

  • Yes, it works. Thanks a lot.I Used Sitecore.Modules.EmailCampaign.ClientApi.UpdateSubscriptions() method and it worked. – Matyas Feb 20 '17 at 16:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.