Loading...

How to Write and Understand a Dynamics CRM Plugin

How to Write and Understand a Dynamics CRM Plugin

 Here’s a sample plugin code in Dynamics CRM written in C#, along with a detailed explanation of each line. This plugin will update the "Description" field of an entity whenever a record is created.



Sample Plugin Code

using System;                           // For basic .NET types
using Microsoft.Xrm.Sdk;                // Provides key interfaces for CRM plugin development
using Microsoft.Xrm.Sdk.Query;          // For performing queries against CRM data

namespace SamplePluginNamespace           // Custom namespace for the plugin
{
    public class SamplePlugin : IPlugin  // Plugin class implementing the IPlugin interface
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            // STEP 1: Retrieve the context of the plugin
            IPluginExecutionContext context = 
                (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            if (context.MessageName != "Create" || context.Stage != 40) 
                return;  // Exit if the message is not 'Create' or it is not in the 'PostOperation' stage

            // STEP 2: Obtain the organization service
            IOrganizationServiceFactory serviceFactory = 
                (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

            // STEP 3: Retrieve the target entity from the input parameters
            Entity targetEntity = (Entity)context.InputParameters["Target"];

            try
            {
                // STEP 4: Update the 'Description' field with a custom message
                targetEntity["description"] = $"Record created on {DateTime.Now}";

                // STEP 5: Persist changes back to the database
                service.Update(targetEntity);
            }
            catch (Exception ex)
            {
                // STEP 6: Handle errors and rethrow as an InvalidPluginExecutionException
                throw new InvalidPluginExecutionException($"An error occurred in the SamplePlugin: {ex.Message}", ex);
            }
        }
    }
}

Line-by-Line Explanation

  1. using System;

    • Imports basic .NET library types such as DateTime and exceptions.
  2. using Microsoft.Xrm.Sdk;

    • Imports CRM SDK interfaces for plugins such as IPlugin, IPluginExecutionContext, and IOrganizationService.
  3. using Microsoft.Xrm.Sdk.Query;

    • Enables querying CRM entities when interacting with data.
  4. namespace SamplePluginNamespace

    • Defines a custom namespace to organize the code logically and avoid naming conflicts.
  5. public class SamplePlugin : IPlugin

    • Implements the IPlugin interface, making this class recognized by Dynamics CRM as a plugin.
  6. public void Execute(IServiceProvider serviceProvider)

    • The main method executed when the plugin is triggered, as required by the IPlugin interface.
  7. Retrieve plugin execution context:

    IPluginExecutionContext context = 
        (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
    
    • Retrieves the execution context, which contains all information about the triggered event.
  8. Validate event type and stage:

    if (context.MessageName != "Create" || context.Stage != 40) 
        return;
    
    • Ensures the plugin executes only for the Create message in the PostOperation stage.
  9. Create organization service:

    IOrganizationServiceFactory serviceFactory = 
        (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
    IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
    
    • Creates an organization service instance for interacting with CRM data.
  10. Retrieve the target entity:

    Entity targetEntity = (Entity)context.InputParameters["Target"];
    
    • Extracts the target record being created.
  11. Update the Description field:

    targetEntity["description"] = $"Record created on {DateTime.Now}";
    
    • Sets the Description field value dynamically based on the current date and time.
  12. Persist changes to CRM:

    service.Update(targetEntity);
    
    • Updates the record in the database with the new value in the Description field.
  13. Handle exceptions:

    catch (Exception ex)
    {
        throw new InvalidPluginExecutionException($"An error occurred in the SamplePlugin: {ex.Message}", ex);
    }
    
    • Catches runtime exceptions and throws them as InvalidPluginExecutionException for debugging or logging purposes.

Usage Details

  • Registration: Use the Plugin Registration Tool to register this plugin in CRM for the Create message.
  • Target Entity: Ensure the target entity has a field named description. Adjust the field name accordingly if different.

This plugin demonstrates essential patterns like validation, service access, and error handling, ensuring robust development in Dynamics CRM.

Published on:

Learn more
Power Platform , D365 CE & Cloud
Power Platform , D365 CE & Cloud

Dynamics 365 CE, Power Apps, Powerapps, Azure, Dataverse, D365,Power Platforms (Power Apps, Power Automate, Virtual Agent and AI Builder), Book Review

Share post:

Related posts

Avoiding Currency Mismatch Errors in Dynamics 365 CE

When working with Dynamics 365 Sales, it’s important to understand how currency behaves across related entities like Opportunity, Quote, Order...

3 days ago

Sales Collaboration: How Sales Teams Work in Dynamics 365 CE

A Sales Team in Microsoft Dynamics 365 Sales represents a group of users who collaborate to manage and close sales opportunities efficiently. ...

13 days ago

Environment Variables vs Configuration Tables vs Hardcoding in Dynamics 365 Customer Engagement (CE)

In Dynamics 365 Customer Engagement (CE), managing configuration values effectively is key to building scalable and maintainable solutions. En...

14 days ago

Ticket sales management with Dynamics CRM in the Sports Industry

Mohona Dutta By Mohona Dutta | Reading time 5 mins So, how do you prospect? Pulling names out of lists on your laptop? Repeatedly calling...

1 month ago

How to create an impactful fan experience in sports with Dynamics CRM?

Mohona Dutta By Mohona Dutta | Reading time 5 mins For a salesperson, every day is game day. Sports organizations are always looking to i...

1 month ago

Updating JavaScript code in Dynamics CRM Made Easy for Developers

Hema Shamala By Hema Shamala | Reading time 5 mins Why do we need JavaScript in D365 CRM? It allows us to implement custom logic by using...

1 month ago

How To Use Advanced Find in Dynamics CRM 365

Nikhil Rajendran By Nikhil Rajendran | Reading time 5 mins One of the most commonly used features in Dynamics 365 is Advanced Find. A d...

1 month ago

Security Model of Dynamics CRM

Business Unit – It is a way to group business activities.When an organization is created, a Root Business Unit is created by default. Thi...

1 month ago

I recreated Dynamics CRM with the Power Platform Plan designer

In January 2003 after many months of engineering and development, Microsoft released one of the first business solutions built-in house; Micro...

2 months ago
Stay up to date with latest Microsoft Dynamics 365 and Power Platform news!
* Yes, I agree to the privacy policy