Support Portal ContactGet in touch

Plugin to Track Marketing List Movements

   Words by CRM Consultancy

   on 16/04/2018 08:00:00

imageRecently we encountered a client requirement to track the Contacts being added or removed to a Marketing List so that a weekly report could be produced on the movements of the list.

For Contacts being added to a Marketing List, this is relatively simple as we can produce our report based from the ‘createdon’ of the Marketing List Members entity in CRM.

However to report on Contacts being removed from the Marketing List this is more tricky, as the Marketing List Member is removed from the CRM Database when the Contact is removed from the List – which means that there is no record for us to report from.

We could use the CRM Audit Trail to track the Associate and Disassociate Messages for the Marketing List, however this would require a pretty detailed report capable of reading and reporting on the CRM Audit Trail.

This would work but would push the technical complexity into the Report, whereas we have a common Email-Report framework that we were looking to use for this weekly report so the requirement could be implemented within a common framework with other Daily, Weekly or Monthly Reports we produce from Dynamics CRM.

Instead we looked at a CRM Plugin that would track when a Contact was added or removed from a Marketing List – and then save a record to a Custom Entity that would track List Movements. (a kind of a mini custom Audit Trail that we can more easily report on)

To do this, we must add a Plugin to ‘lesser spotted’ Messages in the Dynamics CRM Pipeline – AddMember and RemoveMember.

As the name suggests, these Messages trigger when an Add Member or Remove Message is processed by Dynamics and allow us to capture the event and take action as a result.

These Messages do not take in the traditional ‘TargetMessage’ Entity being passed into the Plugin Execution and instead favour two Input Parameters for the GUID Id of the List and the GUID Id of the Contact. (or other record being added to the List, such as a Lead or Account)

So our Plugin must look at handling these InputParameters and take action on the basis of these Parameters:

listId = (Guid)context.InputParameters["ListId"];

recordId = (Guid)context.InputParameters["EntityId"];

This can then be used to build a history of movements for different Marketing Lists.


Figure 1 – Adding a Contact to a Marketing List


Figure 2 – The Resulting List Movements History

This can then be used to produce regular List Movement Reports to track the quantity of Contacts being added or removed from Lists.

Online there is a wealth of resources for Plugin Development with Dynamics, but not much information on these events for AddMember and RemoveMember – and so the full source code of this Plugin can be found below as a practical example of using these Messages and Events:

/// <summary>
/// Tracks when a Contact is added to or removed from a Marketing List
/// </summary>
public class MarketingListMovement : BasePlugin
     /// <summary>
    /// Execute the plug-in
    /// </summary>
    /// <param name="serviceProvider">Service provider</param>
     /// <param name="context">Plugin exeution context</param>
    /// <param name="organizationServiceFactory">Organization service factory</param>
    protected override void ExecutePlugin(IServiceProvider serviceProvider,
                                             IPluginExecutionContext context,
                                             IOrganizationServiceFactory organizationServiceFactory)
        #region Get references to CRM Webservices

        if (context == null)
            throw new ArgumentNullException("context");

        if (organizationServiceFactory == null)
            throw new ArgumentNullException("organizationServiceFactory");

        IOrganizationService service = organizationServiceFactory.CreateOrganizationService(context.UserId);
        OrganizationServiceContext organizationServiceContext = new OrganizationServiceContext(service);


             Guid userId = Guid.Empty;
            Guid listId = Guid.Empty;
            Guid recordId = Guid.Empty;
            string action = string.Empty;

            if ( context.MessageName == "AddMember")
                userId = context.InitiatingUserId;
                listId = (Guid) context.InputParameters["ListId"];
                recordId = (Guid)context.InputParameters["EntityId"];
                action = "Add to Marketing List";
            else if (context.MessageName == "RemoveMember")
                userId = context.InitiatingUserId;
                listId = (Guid)context.InputParameters["ListId"];
                recordId = (Guid)context.InputParameters["EntityId"];
                action = "Remove from Marketing List";

            if ( action != string.Empty && listId != Guid.Empty && recordId != Guid.Empty )
                // before we do anything else, we should check
                // that the 'EntityId' is a reference to the Contact Entity
                // instead of to a Company or Lead
                QueryExpression checkContact = new QueryExpression("contact");
                checkContact.Criteria.AddCondition("contactid", ConditionOperator.Equal, recordId);

                EntityCollection resultContacts = service.RetrieveMultiple(checkContact);
                if (resultContacts.Entities.Count > 0)
                    // Contact exists in CRM that matches the RecordId, proceed
                     Entity newMovement = new Entity("crmcs_listmovement");
                     newMovement.SetValue("crmcs_name", action);
                     newMovement.SetLookupValue("crmcs_listid", "list", listId);
                    newMovement.SetLookupValue("crmcs_contactid", "contact", recordId);

                    // No Contact exists, do nothing
        catch (Exception ex)
            throw new InvalidPluginExecutionException("CRMCS.Xrm.Email.MarketingListMovement --> Execute :: ERROR " + ex.Message + "");

Further Reading

Microsoft Dynamics CRM 2013 – Plugin Messages – AddMember – deep dive

Share this Article

Search Articles

Filter Articles

CRM Tech DocMan

Recent Articles

CRMCS Quick Start Guide: How To Produce a Microsoft Teams Live Event Dynamics 365 Marketing: Lead Scoring and Sales Acceptance Designing and Developing Microsoft Power Apps Portals Thank You for Attending CRMCS’ Webinar - Achieving B2B sales excellence with Dynamics 365 & Microsoft Teams Thank You for Attending Our Webinar - Achieving B2B sales excellence with Dynamics 365 & Microsoft Teams Webinar: Discover How CRMCS Have United Dynamics 365, SharePoint and Microsoft Teams To Create Sales Excellence Ignite your workflow by adding DocDrive365 to Office 365 The CRMCS guide to everything you need to know about integrating Teams with Dynamics 365 Saving Time By Keeping Documents In One Place TDE Database Encryption with On Premise Dynamics The Key to Successful Compliance in 2020 Part 2: Let’s get GDPR Compliant with Microsoft Power Automate Top 3 Essential Tips for Remote Working Dynamics 365 Marketing: Top 5 Best Features Dynamics Day in the Life - Puma Investments Can you use Teams to amplify collaboration in Dynamics? Part 1: Using a Scheduled Power Automate to Trigger Expiry Date Reminders The secrets of successful document collaboration in Dynamics CRMCS launches new AppSource approved DocDrive365 Dynamics Day in the Life - Moneypenny Release Management Add the App to Dynamics DocDrive365 Security: Day One - Getting Started with Dynamics to SharePoint Permissions Building a New Scheduled Process using Flow
  • "Paul has made a real difference to how my team of 24 people record and store valuable customer data and sales opportunities. Highly recommended."

    James, Operations Director

  • "Understanding your business allows us to advise when to implement aspects of CRM and, likewise, when not to."

    Paul McQuillan, Managing Director

  • "Dynamics 365 and CRMCS have made a real lasting difference to our business, allowing us to replace older systems that were holding back our performance."

    Grahame, Chief Operating Officer

  • "James worked well with us to help connect CRM with Outlook and relate how this might benefit our team using CRM for Property Care."

    Natalie, Property Care Supervisor

  • "Matt was really good with helping us run User Testing on the new Compliance Module of our CRM System."

    Tom, Compliance Administrator

Prefer to go old-school?

Write to us using the below addresses.

Head Office
CRM Consultancy
61 Oxford Street
M1 6EQ

London Office
CRM Consultancy London
Grosvenor Avenue

Content © CRM Consultancy.