Below is an simple example to write plugin:
Step 1:
Create your own project of the type Class library in which you want to add your plugin class. So here in this example we have added one class “KeyPlugin.cs”.
Step 2:
Very important step is, you need to add plugin required DLL(s) references and reference names into your project, as they won’t be automatically added.
using System;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using System.ServiceModel;
using Microsoft.Crm.Sdk.Messages;
You will find the DLL’s in the Bin folder of CRM SDK
Step 3:
Once you added all references, implement the interface “IPlugin” to the class, and then add “Execute” method in which pass the “IServiceProvider” interface. See below code to get better idea.
namespace PluginUsingClass
{
public class KeyPlugin : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext pluginExecutionContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory organizationServiceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService organizationService = organizationServiceFactory.CreateOrganizationService(new Guid?(pluginExecutionContext.UserId));
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
Entity preImage = null;
Entity postImage = null;
Entity targetEntity = null;
try
{
//check if target found
if (pluginExecutionContext.InputParameters.Contains("Target") && pluginExecutionContext.InputParameters["Target"] is Entity)
{
//read target entity
targetEntity = (pluginExecutionContext.InputParameters["Target"] as Entity);
}
//check if pre image found
if (pluginExecutionContext.PreEntityImages.Contains("PreImage"))
{
//read pre image entity
preImage = (pluginExecutionContext.PreEntityImages["PreImage"] as Entity);
}
//check if post image found
if (pluginExecutionContext.PostEntityImages.Contains("PostImage"))
{
//read post image entity
postImage = (pluginExecutionContext.PostEntityImages["PostImage"] as Entity);
}
//Write your logic here
}
catch (FaultException<OrganizationServiceFault> fault)
{
throw new FaultException(fault.Message);
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(ex.Message);
}
}
}
}
This is how you can create your plugin code.
Note : Method name “Execute” is very important as this is the entry point to the plugin.
Step 4:
Now we need to Sign the assembly. For that go to Properties of the Plugin Project in Visual Studio and click on Signing then click on sign the assembly and create a new sign key.
After that build the solution.
Step 5:
Now we will see how to deploy this plugin using plugin registration tool provided in the SDK.
- Go to your “Plugin Registration Tool” and connect with your environment.
- Then register with new assembly and add your step and images as per requirement.
Thanks!