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.

image

Figure 1 – Adding a Contact to a Marketing List

image

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);

        #endregion

        try
        {
             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);

                    service.Create(newMovement);
                }
                else
                 {
                    // 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

https://community.dynamics.com/crm/b/sohodynamicscrmworld/archive/2013/10/08/microsoft-dynamics-crm-2013-plugin-messages-addmember-deep-dive

Prefer to go old-school?

Write to us using the below addresses.

Head Office
CRM Consultancy
61 Oxford Street
Manchester
M1 6EQ

London Office
CRM Consultancy London
Grosvenor Avenue
London

Content © CRM Consultancy.