Writing a sample plugin

Let's say we want to write a plugin for the logic that we previously implemented using JavaScript, where we auto-populated the Email field in an account entity record from a selected contact. Let's use the following steps to write our plugin:

  1. Navigate to Visual Studio | New and select Class Library (.NET Framework).
While creating the solution, keep in mind that we can use .NET Framework version 4.6.2 or later for Dynamics 365 CE.
  1. Once the project has been created, we can rename the class based on our requirements; for example, we have renamed it SetEmailFrmContactOnAccountPreCreate.
  2. Let's add Dynamics 365 CE assemblies to our project. Right-click on our project and select the Manage NuGet Packages option.
  3. Add some Dynamics 365 CE assemblies, as shown in the following screenshot. You need to follow the numbered steps indicated in the following screenshot to do this:

  1. Accept the license prompt. This will add all the required assemblies to our project.
  2. We need to add the following two namespace references to our class:
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;

The Microsoft.Xrm.Sdk namespace is the core namespace for working with Dynamics 365 CE entities. This namespace also has an IPlugin interface, which we need to implement to write a plugin. The Microsoft.Xrm.Sdk.Query namespace contains classes that we will be using to query Dynamics 365 CE data.

  1. After that, we need to inherit the IPlugin interface and implement its Execute method. We can do this by following the numbered steps shown in the following screenshot:

The Execute method is the entry function for our plugin logic. Our custom logic starts executing from this method. It can be considered the main method. This method takes a single parameter of the IServiceProvider type, which has a GetService method that we will be using to get a different service object.

  1. Next, we need to add the following line, which will help us get the service object:
IPluginExecutionContext pluginContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

We use the preceding line to get the plugin context from the serviceProvider parameter that we get in the Execute method of the plugin. It helps us get contextual information about the environment that our plugin is executing in. Using pluginContext, we can get different properties, such as business units and parameter collection.

While working with the plugin, we can handle exceptions and create tracing logs. All the tracing-related methods are available in the ITracingService class:

ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
  1. Next, we need to use the following two lines to get the IOrganization service object. The IOrganization service provides us with different methods that we can use to work with entity data and metadata:
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService orgService = serviceFactory.CreateOrganizationService(pluginContext.UserId);

In the preceding code, we are creating an Organization service object using pluginContext.UserId, which means it will use the user that's been configured in the plugin registration tool in the Run in User's Context field. By default, calling the user is configured in this field, which means it will create an Organization service object based on the initiating user.

  1. Next, we need to get an entity from the input parameters. The input parameters are a collection of parameters that we can get from the plugin context that we collected earlier. What parameter we get in the input parameter collection depends on the plugin event that we used to register our plugin. For example, in the case of the Create message, we will always get a Target parameter. We can get it and validate whether it is an entity class type as follows:
if (pluginContext.InputParameters.Contains("Target") && pluginContext.InputParameters["Target"] is Entity)
  1. Once we have checked the Target parameter, we can get the entity and look for the fields that we want to validate. In our case, we want to check whether the user filled in Primary Contact in the account form or not. If Primary Contact is available, we can fetch it and query the contact entity based on the primary contact, as follows:
try {
Entity account = (Entity) pluginContext.InputParameters["Target"];
if (account.LogicalName != "account") {
return;
}
if (account.Contains("primarycontactid")) {
Entity contact = orgService.Retrieve("contact", account.GetAttributeValue < EntityReference > ("primarycontactid").Id, new ColumnSet(new string[] {
"emailaddress1"
}));
if (contact.Contains("emailaddress1"))
account.Attributes.Add("emailaddress1", contact.GetAttributeValue < string > ("emailaddress1"));
}}
catch (FaultException < OrganizationServiceFault > ex) {
tracingService.Trace(ex.Message + " : " + ex.StackTrace);
throw ex;
} catch (Exception e) {
tracingService.Trace(e.Message + " : " + e.StackTrace);
throw e;
}
}

In the preceding code, after fetching the primary contact entity, we added the emailaddress1 field under the account entity attributes collection. We are going to register our plugin on PreCreate so that it will pass the emailaddress1 field in the account object with input parameter collection and be saved with the main database operation:

account.Attributes.Add("emailaddress1", contact.GetAttributeValue<string>("emailaddress1"));
  1. If we want to change an entity after it has been created, we need to use the Update method specifically. We also need to handle the exception in our code. As you can see, we have written our code under a try-catch block. After catching the exception, we can add an exception under the trace log for better troubleshooting.
  2. Now, we need to sign our assembly to provide a strong name. Right-click on the project and select Properties. This will open some property windows where we can select the signing option to give our assembly a strong key name, as follows:

Once you've built your project to generate an assembly file, you can register the plugin.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.238.159