Marketing List Basics
This particular code snippet will show how to add Contacts to a Marketing List. Remember, Marketing lists in Dynamics CRM 2011 can be created using Accounts, Contacts and Leads.
Setup CrmConnection & OrganizationService
// Setup the CrmConnection and OrganizationService instances CrmConnectionInstance = new CrmConnection(ConfigurationConstants.CrmConnectionName); OrgServiceInstance = new OrganizationService(CrmConnectionInstance);
// Create the marketing list Guid NewMarketingListId = Guid.Empty; Microsoft.Xrm.Sdk.Entity CurrentList = new Microsoft.Xrm.Sdk.Entity(MarketingListConstants.MarketingListEntityName); CurrentList[MarketingListConstants.MarketingListTypeAttribute] = false; CurrentList[MarketingListConstants.ListNameAttribute] = "NameOfList"; // For contacts, a value of 2 should be used. CurrentList[MarketingListConstants.CreatedFromCodeAttribute] = new OptionSetValue(2); // Actually create the list NewMarketingListId = OrgServiceInstance.Create(CurrentList); // Use the AddListMembersListRequest to add the members to the list List<Guid> MemberListIds = new List<Guid>(); // Now you'll need to add the Guids for each member to the list // I'm leaving that part out as adding values to a list is very // basic. AddListMembersListRequest AddMemberRequest = new AddListMembersListRequest(); AddMemberRequest.ListId = NewMarketingListId; AddMemberRequest.MemberIds = memberIds.ToArray(); // Use AddListMembersListReponse to get information about the request execution AddListMembersListResponse AddMemberResponse = OrgServiceInstance.Execute(AddMemberRequest) as AddListMembersListResponse;
The comments indicate what’s going on but it’s pretty easy. First, we create an instance of the CrmConnection and OrganizationService . Next, we create an Microsoft.Xrm.Sdk.Entity and specify that it’s a MarketingList. I used a class called MarketingListConstants to hold the attribute names so I can reuse them throughout the project and to reduce the likelihood of typos. The OrganizationService.Create method of the OrganizationService returns a Guid value of the newly created entity. That value is stored in the NewMarketingListId variable. Once the list is created and we have the Guid reference for it, I use the AddListMembersListRequest to add the members to the list. In order to do this I need the ListId and the MemberIds of the contacts I want to add. While not absolutely necessary, you’ll typically want to use the AddListMembersListReponse object to get the information back.
Leave any questions in the Comments section, or write me directly: email@example.com (leave out the obvious part) – /b/ill
KeyWords: Dynamics4, Dynamics4.com, Microsoft.Xrm.Sdk.Entity, KeyValuePair, Crm 2011, Dynamics CRM 2011, Extension Method, CultureInfo.CurrentCulture, StringBuilder, William Ryan, AddListMembersListRequest , AddListMembersListResponse, CrmConnection, OrganizationService, OrganizationService.Execute, OrganizationService.Create, Guid, OptionSetValue