Dynamically Add/Register Plugin steps and images to Dynamic MSCRM Plugins Using C#


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;

namespace Gapconsulting.MSCRM.Plugin
{

    public class AddSteps : IPlugin
    {
        //
        //Three harcoded plugin has been taken with the assemble name to show thw example.
        //
        public const string ASSEMBLY_NAME = "Gapconsulting.MSCRM.Plugin.SMS";
        public const string FIRST_PLUGIN_TYPE_NAME = "Gapconsulting.MSCRM.Plugin.SendSMS";
        public const string SECOND_PLUGIN_TYPE_NAME = "Gapconsulting.MSCRM.Plugin.SMSValidation";
        public const string THIRD_PLUGIN_TYPE_NAME = "Gapconsulting.MSCRM.Plugin.SMSInterfaceCreation";

        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.ToUpper() == "UPDATE")
            {
                if (context.InputParameters.Contains("Target") & amp; & context.InputParameters["Target"] is Entity)
         {
                    //Main function inside which other function has been called to add plugin step
                    //
                    Guid stepId = SdkMessageStep(ASSEMBLY_NAME, FIRST_PLUGIN_TYPE_NAME, service, "Update", "gap_sms", 1, 40);
                    //create image for the above step
                    CreateImage(stepId, service);
                    SdkMessageStep(ASSEMBLY_NAME, SECOND_PLUGIN_TYPE_NAME, service, "Create", "gap_sms", 0, 10);
                    SdkMessageStep(ASSEMBLY_NAME, THIRD_PLUGIN_TYPE_NAME, service, "Publish", "", 1, 40);
                    SdkMessageStep(ASSEMBLY_NAME, THIRD_PLUGIN_TYPE_NAME, service, "PublishAll", "", 1, 40);
                }
            }
        }
        public static Guid GetPluginTypeId(string AssemblyName, string PluginTypeName, IOrganizationService service)
        {
            try
            {
                //GET ASSEMBLY QUERY
                QueryExpression pluginAssemblyQueryExpression = new QueryExpression("pluginassembly");
                pluginAssemblyQueryExpression.ColumnSet = new ColumnSet("pluginassemblyid");
                pluginAssemblyQueryExpression.Criteria = new FilterExpression
                {
                    Conditions =
          {
            new ConditionExpression
            {
              AttributeName = "name",
              Operator = ConditionOperator.Equal,
              Values = { AssemblyName }
             },
            }
                };

                //RETRIEVE ASSEMBLY
                EntityCollection pluginAssemblies = service.RetrieveMultiple(pluginAssemblyQueryExpression);

                //IF ASSEMBLY IS FOUND
                if (pluginAssemblies.Entities.Count != 0)
                {
                    //ASSIGN ASSEMBLY ID TO VARIABLE
                    Guid assemblyId = pluginAssemblies.Entities.First().Id;

                    //GET PLUGIN TYPES WITHIN ASSEMBLY
                    QueryExpression pluginTypeQueryExpression = new QueryExpression("plugintype");
                    pluginTypeQueryExpression.ColumnSet = new ColumnSet("plugintypeid");
                    pluginTypeQueryExpression.Criteria = new FilterExpression
                    {
                        Conditions =
                                    {
                                        new ConditionExpression
                                        {
                                            AttributeName = "pluginassemblyid",
                                            Operator = ConditionOperator.Equal,
                                            Values = {assemblyId}
                                        },
                                        new ConditionExpression
                                        {
                                            AttributeName = "typename",
                                            Operator = ConditionOperator.Equal,
                                            Values = {PluginTypeName}
                                        },
                                    }
                                };

                    //RETRIEVE PLUGIN TYPES IN ASSEMBLY
                    EntityCollection pluginTypes = service.RetrieveMultiple(pluginTypeQueryExpression);

                    //RETURN PLUGIN TYPE ID
                    if (pluginTypes.Entities.Count != 0)
                    {

                        QueryExpression StepQueryExpression = new QueryExpression("sdkmessageprocessingstep");
                        StepQueryExpression.ColumnSet = new ColumnSet("name");
                        StepQueryExpression.Criteria = new FilterExpression
                        {
                            Conditions =
                                        {
                                            new ConditionExpression
                                            {
                                                AttributeName = "plugintypeid",
                                                Operator = ConditionOperator.Equal,
                                                Values = { pluginTypes.Entities.First().Id }
                                            }
                                        }
                                    };

                        //RETRIEVE PLUGIN TYPES IN ASSEMBLY
                        EntityCollection pluginSteps = service.RetrieveMultiple(StepQueryExpression);
                        //RETURN PLUGIN TYPE ID
                        if (pluginSteps.Entities.Count == 0)
                        {
                            return pluginTypes.Entities.First().Id;
                        }
                        else
                        {
                            return Guid.Empty;
                        }
                    }
                    else
                    {
                        return Guid.Empty;
                    }
                    throw new Exception(String.Format("Plugin Type {0} was not found in Assembly {1}", PluginTypeName, AssemblyName));
                }
                throw new Exception(String.Format("Assembly {0} not found", AssemblyName));
            }
            catch (InvalidPluginExecutionException invalidPluginExecutionException)
            {
                throw invalidPluginExecutionException;
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
        public static Guid GetSdkMessageId(string SdkMessageName, IOrganizationService service)
        {
            try
            {
                //GET SDK MESSAGE QUERY
                QueryExpression sdkMessageQueryExpression = new QueryExpression("sdkmessage");
                sdkMessageQueryExpression.ColumnSet = new ColumnSet("sdkmessageid");
                sdkMessageQueryExpression.Criteria = new FilterExpression
                {
                    Conditions =
                                {
                                    new ConditionExpression
                                    {
                                        AttributeName = "name",
                                        Operator = ConditionOperator.Equal,
                                        Values = {SdkMessageName}
                                    },
                                }
                         };

                //RETRIEVE SDK MESSAGE
                EntityCollection sdkMessages = service.RetrieveMultiple(sdkMessageQueryExpression);
                if (sdkMessages.Entities.Count != 0)
                {
                    return sdkMessages.Entities.First().Id;
                }
                throw new Exception(String.Format("SDK MessageName {0} was not found.", SdkMessageName));
            }
            catch (InvalidPluginExecutionException invalidPluginExecutionException)
            {
                throw invalidPluginExecutionException;
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }

        public static Guid GetSdkMessageFilterId(string EntityLogicalName, string SdkMessageName, IOrganizationService service)
        {
            try
            {
                //GET SDK MESSAGE FILTER QUERY
                QueryExpression sdkMessageFilterQueryExpression = new QueryExpression("sdkmessagefilter");
                sdkMessageFilterQueryExpression.ColumnSet = new ColumnSet("sdkmessagefilterid");
                sdkMessageFilterQueryExpression.Criteria = new FilterExpression
                {
                    Conditions =
                                {
                                    new ConditionExpression
                                    {
                                        AttributeName = "primaryobjecttypecode",
                                        Operator = ConditionOperator.Equal,
                                        Values = {EntityLogicalName}
                                    },
                                    new ConditionExpression
                                    {
                                        AttributeName = "sdkmessageid",
                                        Operator = ConditionOperator.Equal,
                                        Values = {GetSdkMessageId(SdkMessageName,service)}
                                    },
                                }
                };

                //RETRIEVE SDK MESSAGE FILTER
                EntityCollection sdkMessageFilters = service.RetrieveMultiple(sdkMessageFilterQueryExpression);

                if (sdkMessageFilters.Entities.Count != 0)
                {
                    return sdkMessageFilters.Entities.First().Id;
                }
                throw new Exception(String.Format("SDK Message Filter for {0} was not found.", EntityLogicalName));
            }
            catch (InvalidPluginExecutionException invalidPluginExecutionException)
            {
                throw invalidPluginExecutionException;
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
        public Guid SdkMessageStep(string assemblyName, string pluginTypeName, IOrganizationService service, string messageName, string entityName, int mode, int stage)
        {
            Guid pluginTypeId = GetPluginTypeId(assemblyName, pluginTypeName, service);
            Guid messageId = GetSdkMessageId(messageName, service);
            Guid messageFitlerId = Guid.Empty;
            if (entityName != "" & amp; & entityName != string.Empty)
            {
                messageFitlerId = GetSdkMessageFilterId(entityName, messageName, service);
            }
            else
            entityName = "any entity";

            if ((pluginTypeId != Guid.Empty & amp; & pluginTypeId != null) & & (messageId != null & amp; & messageId != Guid.Empty))
                {
                Entity step = new Entity("sdkmessageprocessingstep");
                step["name"] = pluginTypeName + ": " + messageName + " of " + entityName;
                step["configuration"] = "";

                step["invocationsource"] = new OptionSetValue(0);
                step["sdkmessageid"] = new EntityReference("sdkmessage", messageId);

                step["supporteddeployment"] = new OptionSetValue(0);
                step["plugintypeid"] = new EntityReference("plugintype", pluginTypeId);

                step["mode"] = new OptionSetValue(mode); //0=sync,1=async
                step["rank"] = 1;
                step["stage"] = new OptionSetValue(stage); //10-preValidation, 20-preOperation, 40-PostOperation
                if (messageFitlerId != null & amp; & messageFitlerId != Guid.Empty)
{
                    step["sdkmessagefilterid"] = new EntityReference("sdkmessagefilter", messageFitlerId);
                }
                Guid stepId = service.Create(step);
                return stepId;

            }
            return Guid.Empty;
        }
        public void CreateImage(Guid stepId, IOrganizationService service)
        {
            string[] myValues = new string[] { "statecode", "subject", "actualend", "gap_failurereason", "statuscode", "to", "gap_tonumber" };
            string csvString = string.Join(",", myValues);

            Entity image = new Entity("sdkmessageprocessingstepimage");
            image["messagepropertyname"] = "Target";
            image["imagetype"] = new OptionSetValue(1);
            image["entityalias"] = "Target";
            image["name"] = "Target";
            image["attributes"] = csvString;
            image["sdkmessageprocessingstepid"] = new EntityReference("sdkmessageprocessingstep", stepId);
            Guid imageId = service.Create(image);
        }
    }
}

 

One thought on “Dynamically Add/Register Plugin steps and images to Dynamic MSCRM Plugins Using C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s