Search code examples
dynamics-crmcrm

CRM Plugin for Publish and Publish All messages


I was wondering if we can write plugins that get executed for messages like "publish" and "publish all" in Dynamics CRM (any version). if so can you share any sample references for the same or code snippets.


Solution

  • This is a plugin that works for Publish and PublishAll messages and it will log the event using an entity that I created for this purpose (you can change to do whatever you want).

    When the event is Publish, the plugin uses the ParameterXml parameter (MSDN) to log which components are being published. In the case of the PublishAll message, this parameter is not present so there's no detail (which makes sense because you're publishing all).

    public class PublishPlugin : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
    
            if (context.MessageName != "Publish" && context.MessageName != "PublishAll")
                return;
    
            string parameterXml = string.Empty;
            if (context.MessageName == "Publish")
            {
                if (context.InputParameters.Contains("ParameterXml"))
                {
                    parameterXml = (string)context.InputParameters["ParameterXml"];
                }
            }
    
            CreatePublishAuditRecord(service, context.MessageName, context.InitiatingUserId, parameterXml);
        }
    
        private void CreatePublishAuditRecord(IOrganizationService service, string messageName, Guid userId, string parameterXml)
        {
            Entity auditRecord = new Entity("fjo_publishaudit");
            auditRecord["fjo_message"] = messageName;
            auditRecord["fjo_publishbyid"] = new EntityReference("systemuser", userId);
            auditRecord["fjo_publishon"] = DateTime.Now;
            auditRecord["fjo_parameterxml"] = parameterXml;
    
            service.Create(auditRecord);
        }
    }
    

    This is how it looks in CRM:

    enter image description here

    You can download the plugin project and CRM solution from my GitHub.