Share This Post

MSD CRM Updates

Dynamics CRM Plugins and its Registration

Dynamics CRM Plugins is the custom business logic that integrates to modify or expand the standard behavior of the platform. Plugins act as the event handlers and are registered to execute on a particular event in the CRM.

MS Dynamics Customer Relationship Management Plugins are written in either C# or VB and can run either in synchronous or asynchronous mode.

Some scenarios where you would write the Dynamics CRM plugins are −

  • You want to execute a few business logic such as updating certain fields of the record or updating related records, etc. when you create or update a CRM record.
  • You want to call the external web service on certain events such as saving or updating the record.
  • You wish to dynamically calculate the field values when any record is not closed.
  • You want to automate processes such as sending e-mails to your customers on certain events in CRM.

Event Framework

The Event Processing Framework in Customer Relationship Management processes the synchronous and asynchronous plugin requests by passing it to the event execution pipeline.

Whenever the event triggers a plugin logic, the message is sent to the CRM Organization Web Service where it can be read or modified by other plugins or any core operations of the platform.

Dynamics CRM Plugins Pipeline Stages

The entire plugin pipeline is divided into multiple stages on which you can register your custom business logic. The pipeline stage mentioned indicates at which stage of the plugin execution cycle, your plugin code runs.

Out of all the mentioned pipeline stages in the following table, you can register your custom plugins only on Pre- and Post-events. You can’t register the plugins on a Platform Core Main Operations.

Event Stage Name Description
Pre-Event Pre-validation Stage in the pipeline for the plugins that are to execute before the main system operation. Plug-ins which is registered in this stage may execute outside the database transaction.
Pre-Event Pre-operation Stage in the pipeline for plugins that are to execute before the main system operation. Plugins registered in this stage are executed with the database transaction.
Platform Core Operation MainOperation In transactions, the main operation of the system, such as create, update, delete, and so on. No custom plug-ins can be registered in the stage. For internal use only.
Post-Event Post-operation Stage in the pipeline for the plug-ins which is to execute after the main operation. Plug-ins registered in the stage are executed with the database transaction.

Whenever the CRM app invokes an event, the following sequence of actions takes place −

  • The event triggers the Web service call and the execution is passed through the event pipeline stages.
  • The information is internally packaged as an OrganizationRequest message and finally sent to the internal CRM Web service methods and platform core operations.
  • The OrganizationRequest message is first received by pre-event plugins, which can modify the information before passing it to platform core operations.
  • After the platform core operations, the message is packaged as OrganizationResponse and passed to the post-operation plugins. The postoperation Dynamics CRM Plugins can optionally modify this information before passing it to the async plugin.
  • The MS Dynamics CRM Plugins receive this data in the form of context object that is passed in the Execute method after which further processing happens.
  • After all the plugin processing completes, execution is passed back to the app which triggered the event.

Plugin Messages

Messages are events on which the plugin is registered. For example, you can register the  Dynamics CRM Plugins on Create Message of the Contact entity. This would fire the business logic whenever the new Contact record is made.

For custom entities, below are the supported messages based on whether the entity is user-owned or organization-owned.

Message Name Ownership Type
Assign User-owned entities only
Create User-owned and organization-owned entities
Delete User-owned and organization-owned entities
GrantAccess User-owned entities only
ModifyAccess User-owned entities only
Retrieve User-owned and organization-owned entities
RetrieveMultiple User-owned and organization-owned entities
RetrievePrincipalAccess User-owned entities only
RetrieveSharedPrincipalsAndAccess User-owned entities only
RevokeAccess User-owned entities only
SetState User-owned and organization-owned entities
SetStateDynamicEntity User-owned and organization-owned entities
Update User-owned and organization-owned entities

For the default out-of-the-box entities, there are more than 100 helped messages. Some of these messages are applicable for all the entities while some of them are particular to certain entities.

You can find the complete list of helped message in the excel file inside the SDK: SDK\Message-entity support for plug-ins.xlsx

Writing Plugin

In this section, we will learn about the basics of writing the plugin. We will be creating a simple plugin that creates a Task activity to follow-up with the customer whenever a new customer is added to the system, i.e. whenever a new Contact record is created in CRM.

First of all, you would need to include references to Microsoft.Xrm.SDK namespace. The Customer Relationship Management SDK contains all the required SDK assemblies.

Assuming that you have already downloaded and installed the SDK, then open the Visual Studio. Create a new project of type Class Library. You can name the project as SamplePlugins and click OK.

Dynamics CRM Plugins

CRM Create Plugins

Include the reference of Microsoft.Xrm.Sdk assembly to your project. The assembly is present in SDK/Bin.

Now, create a class named PostCreateContact.cs and extend the class from IPlugin. Till now, your code will look something like the below.

You will also need to add the reference to System.Runtime.Serialization. Once you have added the required references, copy the following code inside the PostCreateContact class.

namespace SamplePlugins {
   public class PostCreateContact:IPlugin {
      public void Execute(IServiceProviderserviceProvider) {
         IPluginExecutionContext context =(IPluginExecutionContext)
            serviceProvider.GetService(typeof(IPluginExecutionContext));

          if(context.InputParameters.Contains("Target")&&
            context.InputParameters["Target"]isEntity) {
        
           Entity entity = (Entity)context.InputParameters["Target"];
            try {
             Entity followup = new Entity("task");
               followup["subject"] = "Send e-mail to the new customer.";
               followup["description"] =
                  "Follow up with the customer. Check if there are any new issues
                  that need resolution.";
               
               followup["scheduledstart"] = DateTime.Now;
               followup["scheduledend"] = DateTime.Now.AddDays(2);
               followup["category"] = context.PrimaryEntityName;

               if(context.OutputParameters.Contains("id")) {
                  Guid regardingobjectid = new Guid(context.OutputParameter
                     s["id"].ToString());
                  string regardingobjectidType = "contact";
                  followup["regardingobjectid"] = 
                     new EntityReference(rega rdingobjectidType,regardingobjectid);
               }
        
               IOrganizationServiceFactory serviceFactory =
                  (IOrganizationSer viceFactory)serviceProvider.GetService
                  (typeof(IOrganizationServiceFactory));
               IOrganizationService service = 
                  serviceFactory.CreateOrganizationService(context.UserId);
               service.Create(followup);
            } catch(Exception ex) {
               throw new InvalidPluginExecutionException(ex.Message);
            }
         }
      }
   }
}

Below is the step-by-step explanation of what this code does −

Step 1 − Implements the Execute way by taking IServiceProvider object as its parameter. The service provider contains references to many useful objects that you are going to use within the plugin.

Step 2 − Obtains the IPluginExecutionContext object using the GetService method of IServiceProvider.

Step 3 − Gets the target entity’s object from the context object’s InputParameters collection. This Entity class object tells about the Contact entity record on which our plugin would be registered.

Step 4 − It then makes the object of the Task entity and sets the proper subject, description, dates, category, and regardingobjectid. The regardingobjectid specify for which contact record this activity record is being created.

You can view the code gets the id of the parent Contact record using the context.OutputParameters and associates it with the Task entity record which you have created.

Step 5 − Creates the object of IOrganizationServiceFactory using the IServiceProvider object.

Step 6 − Creates the object of IOrganizationService using the IOrganizationServiceFactory object.

Step 7 − Finally, using the Create process of this service object. It creates a follow-up activity which gets saved in CRM.

Signing the Plugin Assembly

This section is relevant only if you are registering your plugin assembly for the first time. You need to sign in the assembly with the key to be able to deploy the plugin. Rightclick the solution and click Properties.

Choose the Signing tab from the left options and check the Sign the assembly option. Then, choose New from select a strong name key file option.

Enter the Key file name as sample plugins. Uncheck, Protect my key file with a password option and click to OK. Click Save.

Finally, build the solution. Right Click → Build.

Exception Handling in Plugin

More often than not, your plugin logic will need to handle run-time exceptions. For synchronous plugins, you can return the InvalidPluginExecutionException exception, which will display the error dialog box to the user.

The error dialog will contain a custom error message that you pass to the Message object of an exception object.

If you look at our code, we are giving the InvalidPluginExecutionException exception in our catch block.

throw new InvalidPluginExecutionException(ex.Message); 

Plugin Registration

In this chapter, we will see how to register this plugin in CRM using the Plugin Registration Tool. You can notice the tool at this location: SDK/Tools/PluginRegistration/PluginRegistration.exe.

For convenience, the plugin registration process is separated into three sections −

  • Connecting to the Server
  • Registering the Assembly
  • Registering the Plugin

Connecting to the Server

Step 1 − Run the PluginRegistration.exe from the location mentioned earlier. Click the Create New Connection button.

Step 2 − In the Login window, select Office 365 since we are using the online version of CRM. Enter your credentials and click Login.

Step 3 − The tool will open and look like the below screenshot.

Registering the Assembly

Step 1 − Go to Register → in that go to Register New Assembly.

Step 2 − This will open to the Register New Assembly. Click to Navigate the icon and locate the Plugin DLL that you created in the last chapter.

Step 3 − After navigating the DLL, click to the Load Assembly. This will populate the SamplePlugins assembly and all its plugin classes.

You can see the PostCreateContact plugin class highlighted below. If your plugin assembly had three plugin classes, it would have displayed three plugins listed there.

Step 4 − Choose the Isolation Mode as Sandbox, Location as Database and click Register Selected Plugins. It will display you a success message if the registration is successful.

Registering the Plugin

Now we will be registering the particular steps on which the individual plugins will be called.

Step 1 − Select the PostCreateContact plugin.

Step 2 − Click to the Register → then click to the Register New Step.

Step 3 − We are registering this plugin on the creation of the Contact entity, on post-operation stage and in the synchronous mode.

Message − Create

Primary Entity − Contact

Event Pipeline Stage of Execution − Post-operation

Execution Mode − Synchronous

Keep the rest of the options by default and click to the Register New Step.

You can see a new step included to the plugin.

Now we will go to the CRM and test if our plugin is working properly or not. Note that these test steps are particular to our example plugin.

Testing the Plugin

Go to the Contacts tab and create the new record. Once you save the record, you can view a new activity created and associated with this record.

You can click to the activity to view the details that we had set in the code.

This confirms that our plugin ran successfully. Similarly, you can expand your Dynamics CRM Plugins to achieve highly difficult functionalities.

Conclusion

Dynamics CRM Plugins are definitely difficult for any custom implementation. In this Article, we focused on understanding the event framework model, pipeline stages, messages, and writing the sample plugin and we will register this plugin in Customer Relationship Management and it will be working from the end-to-end scenario.

Share This Post

Leave a Reply

avatar
  Subscribe  
Notify of
Skip to toolbar