web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Custom Plugin to add members to marketing list

(0) ShareShare
ReportReport
Posted on by

I have created a plugin that will read a list of contacts from a csv file and add them to a marketing list.  Everything works fine until the actual Add code is executed.

I am calling the add like this:

// Create the request object.
AddMemberListRequest addMember = new AddMemberListRequest();

// Set the properties of the request object.
addMember.EntityId = entityId;
addMember.ListId = listId;

// Execute the request.
AddMemberListResponse addedMember = (AddMemberListResponse)service.Execute(addMember);

The error I am getting is the following:

Error in AddMemberList plugin, ExecuteWithRetry for SendAPIRequest exceeded the maximum number of retriesMessage:ExecuteWithRetry for SendAPIRequest exceeded the maximum number of retriesStack: at ClickDimensions.Crm.MsCrm2011Plugins.Common.ExecuteWithRetry[T](Func`1 action)
at ClickDimensions.Crm.MsCrm2011Plugins.AddMemberListPlugin.PostRecipients(IOrganizationService service, ITracingService tracer, String url, List`1 entities)
at ClickDimensions.Crm.MsCrm2011Plugins.AddMemberListPlugin.SendAddToListTriggerRequest(IOrganizationService service, ITracingService tracer, Guid listId, List`1 recipients)
at ClickDimensions.Crm.MsCrm2011Plugins.AddMemberListPlugin.Execute(IServiceProvider serviceProvider) at ClickDimensions.Crm.MsCrm2011Plugins.Common.ExecuteWithRetry[T](Func`1 action)
at ClickDimensions.Crm.MsCrm2011Plugins.AddMemberListPlugin.PostRecipients(IOrganizationService service, ITracingService tracer, String url, List`1 entities)
at ClickDimensions.Crm.MsCrm2011Plugins.AddMemberListPlugin.SendAddToListTriggerRequest(IOrganizationService service, ITracingService tracer, Guid listId, List`1 recipients)
at ClickDimensions.Crm.MsCrm2011Plugins.AddMemberListPlugin.Execute(IServiceProvider serviceProvider)CONTEXT INFORMATION: ----------
UserId: 2a9ce609-d1f8-e011-a539-0ee1388ccc3a
OrganizationId: 37092a56-8295-4f04-8735-e99679817dff
OrganizationName: StageDynamicsCRM
MessageName: AddMember
Stage: 40
Mode: 0
PrimaryEntityName: list
SecondaryEntityName: none
BusinessUnitId: 4e64f778-92f6-e011-a539-0ee1388ccc3a
CorrelationId: 84cdd479-45eb-4748-ada4-82b586e15ad7
Depth: 3
InitiatingUserId: 2a9ce609-d1f8-e011-a539-0ee1388ccc3a
IsExecutingOffline: False
IsInTransaction: True
IsolationMode: 1
Mode: 0
OperationCreatedOn: 10/21/2016 3:49:17 PM
OperationId: 00000000-0000-0000-0000-000000000000
PrimaryEntityId: 00000000-0000-0000-0000-000000000000
OwningExtension LogicalName: sdkmessageprocessingstep
OwningExtension Name: ClickDimensions.Crm.MsCrm2011Plugins.AddMemberListPlugin: AddMember of list
OwningExtension Id: 7abd2cab-7e60-e111-b398-1cc1dee8ea01
SharedVariables:
InputParameters: ListId: 6baba6d4-a597-e611-a759-005056873a53; EntityId: 47f2efd5-1774-e511-8b3b-005056ba1794;
OutputParameters: Id: 4897e5e5-a597-e611-b5c9-005056874077;
PreEntityImages:
PostEntityImages:

My plugin and the ClickDimensions.Crm.MsCrm2011Plugins assemblys are already set to use Isolation Mode = None.

If I disable the ClickDimensions.Crm.MsCrm2011Plugins.AddMemberListPlugin my plugin works just fine.  Is there a way to get this to work without having to disable the Click Dimensions plugin?

*This post is locked for comments

I have the same question (0)
  • Suggested answer
    Yadnyesh Kuvalekar Profile Picture
    4,102 on at

    Try changing Execution order of your plugin to run first. Set Execution order of your plugin step to 1 and ClickDimension's plugin to 2.

  • Community Member Profile Picture
    on at

    Hello Yadnyesh,

    Thank you for replying in response to my issue.

    I just tried setting the executing order of my plugin to 1 and Click Dimension's plugin to 2 and that did not resolve.

  • Suggested answer
    saadzag Profile Picture
    1,145 on at

    Here is the code to add members to a marketing list:

    List<Guid> listToAdd = new List<Guid>();

    // add members guids to the list

    //listToAdd.Add(member.Id);

    var addMemberListReq = new AddListMembersListRequest

                   {

                       MemberIds = listToAdd.ToArray(),

                       ListId = Guid.Parse(marketingListGUID)

                   };

                   _service.Execute(addMemberListReq);

  • Community Member Profile Picture
    on at

    Hello saadzag,

    Thank you for your response.

    I have setup my code like this:

    if (membersToAdd.Count > 0)

    {

             var addMemberListReq = new AddListMembersListRequest

             {

                        MemberIds = membersToAdd.ToArray(),

                        ListId = listId

             };

             service.Execute(addMemberListReq);

    }

    I am now getting the following error:

    2016-10-24 12:02:11,366 | [7] | DEBUG | Arise.CRM.Plugins.MarketingListMemberUpload| An error occurred while trying to add a Marketing List Member: Error in AddMemberList plugin, ExecuteWithRetry for SendAPIRequest exceeded the maximum number of retriesMessage:ExecuteWithRetry for SendAPIRequest exceeded the maximum number of retriesStack:   at ClickDimensions.Crm.MsCrm2011Plugins.Common.ExecuteWithRetry[T](Func`1 action)

      at ClickDimensions.Crm.MsCrm2011Plugins.AddMemberListPlugin.PostRecipients(IOrganizationService service, ITracingService tracer, String url, List`1 entities)

      at ClickDimensions.Crm.MsCrm2011Plugins.AddMemberListPlugin.SendAddToListTriggerRequest(IOrganizationService service, ITracingService tracer, Guid listId, List`1 recipients)

      at ClickDimensions.Crm.MsCrm2011Plugins.AddMemberListPlugin.Execute(IServiceProvider serviceProvider)   at ClickDimensions.Crm.MsCrm2011Plugins.Common.ExecuteWithRetry[T](Func`1 action)

      at ClickDimensions.Crm.MsCrm2011Plugins.AddMemberListPlugin.PostRecipients(IOrganizationService service, ITracingService tracer, String url, List`1 entities)

      at ClickDimensions.Crm.MsCrm2011Plugins.AddMemberListPlugin.SendAddToListTriggerRequest(IOrganizationService service, ITracingService tracer, Guid listId, List`1 recipients)

      at ClickDimensions.Crm.MsCrm2011Plugins.AddMemberListPlugin.Execute(IServiceProvider serviceProvider)CONTEXT INFORMATION: ----------

    UserId: 2a9ce609-d1f8-e011-a539-0ee1388ccc3a

    OrganizationId: 37092a56-8295-4f04-8735-e99679817dff

    OrganizationName: StageDynamicsCRM

    MessageName: AddListMembers

    Stage: 40

    Mode: 0

    PrimaryEntityName: list

    SecondaryEntityName: none

    BusinessUnitId: 4e64f778-92f6-e011-a539-0ee1388ccc3a

    CorrelationId: 3cdb3d36-3267-415d-a29b-133af96d71fb

    Depth: 3

    InitiatingUserId: 2a9ce609-d1f8-e011-a539-0ee1388ccc3a

    IsExecutingOffline: False

    IsInTransaction: True

    IsolationMode: 1

    Mode: 0

    OperationCreatedOn: 10/24/2016 4:01:05 PM

    OperationId: 00000000-0000-0000-0000-000000000000

    PrimaryEntityId: 00000000-0000-0000-0000-000000000000

    OwningExtension LogicalName: sdkmessageprocessingstep

    OwningExtension Name: ClickDimensions.Crm.MsCrm2011Plugins.AddMemberListPlugin: AddListMembers of list

    OwningExtension Id: 12b011b3-7e60-e111-b398-1cc1dee8ea01

    SharedVariables:

    InputParameters: ListId: 6baba6d4-a597-e611-a759-005056873a53; MemberIds: System.Guid[];

    OutputParameters:

    PreEntityImages:

    PostEntityImages:

    ----------

  • Morne Wolfaardt Profile Picture
    on at

    Have you tried to log a case with ClickDimentions? Maybe they can update their plugins

  • Community Member Profile Picture
    on at

    Hello Morne,

    I did that first before opening this forum.  Click Dimensions cannot help me since my plugin is a customization in CRM.

  • saadzag Profile Picture
    1,145 on at

    could you post the all code?

    in a downloadable file if possible.

  • Community Member Profile Picture
    on at

    Hi saadzag,

    I do not have the option to upload files through here.

    Below is all the code in my .cs file used in the plugin.

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    using Microsoft.Xrm.Sdk;

    using Microsoft.Xrm.Sdk.Query;

    using Microsoft.Xrm.Sdk.Metadata;

    using Microsoft.Xrm.Sdk.Messages;

    using Microsoft.Crm.Sdk.Messages;

    using Arise.CRM.Plugins.Helpers;

    using log4net;

    namespace Arise.CRM.Plugins

    {

       public class MarketingListMemberUpload : IPlugin

       {

           IOrganizationService crmService;

           string moduleName = System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.Name;

           private readonly ILog logger = LogManager.GetLogger(typeof(MarketingListMemberUpload));

           // Obtain the execution context from the service provider.

           IPluginExecutionContext context;

           // Obtain the organization service reference.

           IOrganizationServiceFactory serviceFactory;

           //retrieve user record

           IOrganizationService service;

           public void Execute(IServiceProvider serviceProvider)

           {

               context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

               serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

               crmService = serviceFactory.CreateOrganizationService(context.UserId);

               service = serviceFactory.CreateOrganizationService(context.UserId);

               CommonMethods.setLogger(logger, crmService);

               string uploadMessage = "";

               if (context.MessageName.ToLower() != "create")

               {

                   logger.Info("Plugin:" + moduleName + ": No Create MessageName: MessageName is " + context.MessageName);

                   return;

               }

               if (context.PrimaryEntityName.ToLower() != "arise_marketinglistupload")

               {

                   logger.Info("Plugin:" + moduleName + ": No list Primary Entity: Primary Entity is " + context.PrimaryEntityName);

                   return;

               }

               try

               {

                   uploadMessage = UploadMarketingListMembers();

                   if (uploadMessage.Length > 0)

                       throw new InvalidPluginExecutionException("An error occurred in the plug-in: " + uploadMessage);

               }

               catch (Exception e)

               {

                   logger.Error("An error occurred in the plug-in: " + e.Message + ". " + ". " + uploadMessage);

                   throw new InvalidPluginExecutionException("An error occurred in the plug-in: " + e.Message + ". " + uploadMessage);

               }

               logger.Debug("Plugin: " + moduleName + " (" + context.MessageName + ") - End Execution");

           }

           private string UploadMarketingListMembers()

           {

               StringBuilder errormsg = new StringBuilder(1024);

               Entity entityPost = (Entity)context.PostEntityImages["PostImage"];

               Guid listId = new Guid();

               if (entityPost == null)

               {

                   logger.Debug("Entity not found.");

                   return "Entity not found.";

               }

               if (entityPost.Attributes.Contains("arise_linkedlist"))

               {

                   listId = ((EntityReference)entityPost["arise_linkedlist"]).Id;

               }

               else

               {

                   logger.Debug("List Id not retrieved.");

                   appendErrorLog(entityPost, "List Id not retrieved.");

                   return "List Id not retrieved.";

               }

               if (ProcessUpload(listId))

               {

                   try

                   {

                       #region Upload

                       string fileDataBase64 = string.Empty;

                       string memberList = string.Empty;

                       string uploadFileName = String.Empty;

                       // check if notes are available

                       QueryExpression qe = new QueryExpression("annotation");

                       qe.ColumnSet = new ColumnSet("documentbody", "filename", "mimetype");

                       qe.Criteria.AddCondition("objectid", ConditionOperator.Equal, listId);

                       qe.Criteria.AddCondition("documentbody", ConditionOperator.NotNull);

                       DataCollection<Entity> notes = crmService.RetrieveMultiple(qe).Entities;

                       //Can upload members from multiple csv files

                       foreach (var note in notes)

                       {

                           //Get the most recent attachment

                           fileDataBase64 = note["documentbody"].ToString();

                           uploadFileName = note.Attributes["filename"].ToString();

                           logger.Info("Plugin:" + moduleName + "Uploaded File " + note.Attributes["filename"] + " with mime type " + note.Attributes["mimetype"]);

                           if (!string.IsNullOrEmpty(fileDataBase64))

                           {

                               //Make sure the file is a csv file, otherwise ignore

                               if (uploadFileName.Contains(".csv"))

                               {

                                   // decode base64 string

                                   byte[] fileContent = Convert.FromBase64String(fileDataBase64);

                                   memberList = Encoding.UTF8.GetString(fileContent);

                                   string[] memberString = memberList.Split('\n');

                                   List<Guid> membersToAdd = new List<Guid>();

                                   try

                                   {

                                       foreach (string member in memberString)

                                       {

                                           if (!string.IsNullOrEmpty(member))

                                           {

                                               // remove starting and ending double quotes.

                                               string tempMember = member.Trim();

                                               tempMember = tempMember.Trim('"');

                                               string[] memberAttributes = tempMember.Split(',');

                                               logger.Debug("Validating CSP " + memberAttributes[0].ToString());

                                               Entity csp = GetCSP(memberAttributes[0].ToString());

                                               if (csp != null)

                                               {

                                                   //Validate that the CSP is not already assigned to this marketing list (avoid duplicates)

                                                   if (!DuplicateMember(csp.Id, listId))

                                                   {

                                                       logger.Debug("Adding validated CSP " + memberAttributes[0].ToString());

                                                       membersToAdd.Add(csp.Id);

                                                   }

                                                   else

                                                   {

                                                       //Log duplicate CSP

                                                       errormsg.AppendFormat("CSP {0} was not uploaded. They are already linked to this Marketing List. \n", memberAttributes[0].ToString());

                                                   }

                                               }

                                               else

                                               {

                                                   //Log CSP not found in system

                                                   errormsg.AppendFormat("CSP {0} was not uploaded. A CSP record was not found for them. \n", memberAttributes[0].ToString());

                                               }

                                           }

                                       }

                                       // Create and Execute the request object to add the members.

                                       if (membersToAdd.Count > 0)

                                       {

                                           var addMemberListReq = new AddListMembersListRequest

                                                                               {

                                                                                   MemberIds = membersToAdd.ToArray(),

                                                                                   ListId = listId

                                                                               };

                                           service.Execute(addMemberListReq);

                                       }

                                   }

                                   catch (Exception ex)

                                   {

                                       logger.Debug("An error occurred while trying to add a Marketing List Member: " + ex.Message);

                                       appendErrorLog(entityPost, "An error occurred while trying to add a Marketing List Member: " + ex.Message);

                                       return "An error occurred while trying to add a Marketing List Member: " + ex.Message;

                                   }

                               }

                               else

                               {

                                   errormsg.AppendFormat("File {0} was not uploaded because it is not a csv type file. \n", uploadFileName);

                               }

                           }

                       }

                       //Update the marketing list to set the failures logged and the uploadcompleted flag

                       Entity uploadRecord = new Entity(entityPost.LogicalName);

                       uploadRecord["arise_marketinglistuploadid"] = uploadRecord.Id = entityPost.Id;

                       uploadRecord["arise_uploadfailurelog"] = CommonMethods.Truncate(errormsg.ToString(), 2000);

                       uploadRecord["arise_uploadcompleted"] = true;

                       crmService.Update(uploadRecord);

                       #endregion

                   }

                   catch (Exception ex)

                   {

                       logger.Debug("An error occurred during the upload process of Marketing List Members: " + ex.Message);

                       appendErrorLog(entityPost, "An error occurred during the upload process of Marketing List Members: " + ex.Message);

                       return "An error occurred during the upload process of Marketing List Members: " + ex.Message;

                   }

               }

               else

               {

                   logger.Debug("Upload did not process.  No async process found.");

                   appendErrorLog(entityPost, "Upload did not process.  No async process found.");

               }

               return "";

           }

           private bool ProcessUpload(Guid listid)

           {

               try

               {

                   string fetchXML = string.Format("<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'><entity name='arise_marketinglistupload'><attribute name='arise_marketinglistuploadid' /><filter type='and'><condition attribute='arise_uploadmembers' operator='eq' value='1' /></filter><filter type='and'><condition attribute='arise_uploadcompleted' operator='eq' value='0' /></filter><filter type='and'><condition attribute='arise_linkedlist' operator='eq' value='{0}' /></filter></entity></fetch>", listid);

                   EntityCollection results = crmService.RetrieveMultiple(new Microsoft.Xrm.Sdk.Query.FetchExpression(fetchXML));

                   if (results != null && results.Entities.Count > 0)

                       return true;

                   return false;

               }

               catch (Exception ex)

               {

                   logger.Debug("An error occurred while verifying if an upload can be done: " + ex.Message);

                   return false;

               }

           }

           private Entity GetCSP(string cspid)

           {

               string fetchXML = string.Format("<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'><entity name='contact'><attribute name='fullname' /><attribute name='new_acpidnocomma' /><attribute name='contactid' /><order attribute='fullname' descending='false' /><filter type='and'><condition attribute='new_acpidnocomma' operator='eq' value='{0}' /></filter></entity></fetch>", cspid);

               EntityCollection results = crmService.RetrieveMultiple(new Microsoft.Xrm.Sdk.Query.FetchExpression(fetchXML));

               if (results != null && results.Entities.Count > 0)

                   return results.Entities[0];

               else

                   return null;

           }

           private bool DuplicateMember(Guid contactid, Guid listid)

           {

               string fetchXML = string.Format("<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'><entity name='listmember'><attribute name='listid' /><attribute name='entityid' /><attribute name='listmemberid' /><filter type='and'><condition attribute='entityid' operator='eq' value='{0}' /></filter><filter type='and'><condition attribute='listid' operator='eq' value='{1}' /></filter></entity></fetch>", contactid, listid);

               EntityCollection results = crmService.RetrieveMultiple(new Microsoft.Xrm.Sdk.Query.FetchExpression(fetchXML));

               if (results != null && results.Entities.Count > 0)

                   return true;

               return false;

           }

           private void appendErrorLog(Entity entityPost, string ErrorMessage)

           {

               Entity selfEntity = new Entity(entityPost.LogicalName);

               selfEntity["arise_marketinglistuploadid"] = entityPost.Id;

               selfEntity["arise_uploadfailurelog"] = CommonMethods.Truncate(ErrorMessage, 2000);

               selfEntity["arise_uploadmembers"] = false;

               selfEntity["arise_uploadcompleted"] = false;

               crmService.Update(selfEntity);

           }

       }

    }

  • Verified answer
    Kumar Viju Profile Picture
    1,026 on at

    Can you add Contact From GUI to the Marketing List without any issue? What is the Plugin Execution Mode.  Try to make the Plugin Execution Mode as Asynchronous ( Post Operation ).

    As from the Error messageit seems multiple connections are throttling.  

  • Suggested answer
    Community Member Profile Picture
    on at

    Yes, I can add contacts from the GUI just fine with the Click Dimensions plugin enabled and with my plugin enabled.  It also works if I disable the Click Dimensions AddMemberListPlugin.

    My plugin execution mode is already set to Asynchronous execution mode and Post-Operation (CRM 2011 Only).  Click Dimension's plugin is Synchronous execution mode and Post-operation (CRM 2011 Only).

    I tested setting Click Dimension's plugin to Asynchronous and that worked.  My plugin ran successfully.  I am now verifying with Click Dimension's support to see if that change would affect anything on their side.

    Thanks so much!!

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans