5

I am trying to remove a contact from a contact list using next code:

using (var client = SitecoreXConnectClientConfiguration.GetClient())
{
    var reference = new IdentifiedContactReference(source, email);
    var contact = client.Get(reference, new ContactExpandOptions(new string[]
    {
        "ListSubscriptions"
    }));
    if (contact == null) return;

    Guid contactListId = new Guid(ListId);

    IDefinitionManager<IContactListDefinition> manager = ServiceLocator.ServiceProvider.GetDefinitionManagerFactory().GetDefinitionManager<IContactListDefinition>();


    var contactList = manager.Get(contactListId, new CultureInfo("en"), true);


    contact.RemoveListSubscriptions(client, true, new Guid[]
    {
        contactListId
    });
    client.Submit();
}    

I can see the list in the ListSubscriptions facet but is not removed. Am I doing something wrong?

2 Answers 2

8

We use code like this and it works fine. It is similar to yours however there are some differences:

using (var client = SitecoreXConnectClientConfiguration.GetClient())
{
    try
    {
        var identifier = new IdentifiedContactReference(IdentifierSources.Email, email);
        var contact = client.Get(identifier, new ContactExpandOptions(ListSubscriptions.DefaultFacetKey));
        var contactList = contact.ListSubscriptions()?.Subscriptions?.FirstOrDefault(x => x.ListDefinitionId.Equals(contactListId));

        if (contactList == null)
        {
            return ContactListOperationResultEnum.ContactNotOnTheList;
        }

        var subscriptions = contact.ListSubscriptions();
        subscriptions.Subscriptions.Remove(contactList);
        client.SetListSubscriptions(contact, subscriptions);
        client.Submit();

        return ContactListOperationResultEnum.Success;
    }
    catch (XdbExecutionException ex)
    {
        _logger.Error($"Exception during removing contact from list {contactListId}", ex, this);
        return ContactListOperationResultEnum.Error;
    }
}
0

Updating in case anyone finds this in the future. I was able to use the subscription service as detailed here: https://doc.sitecore.com/en/developers/93/sitecore-experience-manager/the-list-manager-api.html#add-and-remove-contacts

var subscriptionService = ServiceLocator.ServiceProvider.GetService<ISubscriptionService>();
subscriptionService.Unsubscribe(contactListId, contactId);
subscriptionService.Unsubscribe(contactListId, contacts);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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