dotcentric-samb
dotcentric-samb

Reputation: 129

Get Marketing list ID by name

I am trying to get the id of a marketing list created in Microsoft Dynamics based on the list's name. I will then use the id to add crm contacts to the list (this I can do fine using the id of the list)

I can't find any instructions in the documentation that explains how to do this. I have tried the following code but i get the error that no entity by that name exists:

    var request = new RetrieveRequest();
    request.Target = new EntityReference("new list 1", listId);
    RetrieveResponse response = _organizationService.Execute(request) as RetrieveResponse;

What I am ultimately trying to do is make it possible for an administrator of the crm to identify the marketing list that a user should be added to when they fill in a newsletter form on our website. I think it will be too much to ask them to find the guid of the marketing list (it took me a bit of work to find it myself)

can anyone share some code to either get the id of a list using the list name as the identifier or let me know if its possible to add a contact to a list using the list name instead of the id?

Upvotes: 0

Views: 444

Answers (2)

Dave Clark
Dave Clark

Reputation: 2311

The following code gets all lists in Dynamics with a name of "new list 1". It then stores the Id of the first list returned if one or more matches were found, or Guid.Empty if no matches were found. In your scenario there should be always be one and only one match.

var query = new QueryExpression
{
    EntityName = "list",
    ColumnSet = new ColumnSet(false)
};

query.Criteria.AddCondition("name", ConditionOperator.Equal, "new list 1";

var matchingLists = _organizationService.RetrieveMultiple(query);

var defaultListId = matchingLists?.Entities.FirstOrDefault()?.Id ?? Guid.Empty;

Upvotes: 2

To retrieve the entity record using RetrieveRequest, schema name of that entity (DB table) should be passed as first parameter and primary key (GUID) as second. For Marketing list it is list & listid. You should also mention ColumnSet.

request.Target = new EntityReference("list", listId);

But to achieve what you want, you have to use either querybyattribute or queryexpression, then RetrieveMultiple will help you to get the Id from name of list.

FilterExpression filter = new FilterExpression();
filter.FilterOperator = LogicalOperator.And;
filter.AddCondition(new ConditionExpression("name", ConditionOperator.Equal, "new list 1"));
QueryExpression query = new QueryExpression("list");
query.Criteria.AddFilter(filter);

var result = Context.SystemService.RetrieveMultiple(query);

After that use AddListMembersListRequest or AddMemberListRequest to add members to that list.

// Add a list of contacts to the marketing list.
var addMemberListReq = new AddListMembersListRequest
{
    MemberIds = new[] { _contactIdList[0], _contactIdList[2] },
    ListId = listId
};

_serviceProxy.Execute(addMemberListReq);

Upvotes: 1

Related Questions