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
-
using System;- Imports basic .NET library types such as
DateTimeand exceptions.
- Imports basic .NET library types such as
-
using Microsoft.Xrm.Sdk;- Imports CRM SDK interfaces for plugins such as
IPlugin,IPluginExecutionContext, andIOrganizationService.
- Imports CRM SDK interfaces for plugins such as
-
using Microsoft.Xrm.Sdk.Query;- Enables querying CRM entities when interacting with data.
-
namespace SamplePluginNamespace- Defines a custom namespace to organize the code logically and avoid naming conflicts.
-
public class SamplePlugin : IPlugin- Implements the
IPlugininterface, making this class recognized by Dynamics CRM as a plugin.
- Implements the
-
public void Execute(IServiceProvider serviceProvider)- The main method executed when the plugin is triggered, as required by the
IPlugininterface.
- The main method executed when the plugin is triggered, as required by the
-
Retrieve plugin execution context:
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));- Retrieves the execution context, which contains all information about the triggered event.
-
Validate event type and stage:
if (context.MessageName != "Create" || context.Stage != 40) return;- Ensures the plugin executes only for the
Createmessage in thePostOperationstage.
- Ensures the plugin executes only for the
-
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.
-
Retrieve the target entity:
Entity targetEntity = (Entity)context.InputParameters["Target"];- Extracts the target record being created.
-
Update the
Descriptionfield:targetEntity["description"] = $"Record created on {DateTime.Now}";- Sets the
Descriptionfield value dynamically based on the current date and time.
- Sets the
-
Persist changes to CRM:
service.Update(targetEntity);- Updates the record in the database with the new value in the
Descriptionfield.
- Updates the record in the database with the new value in the
-
Handle exceptions:
catch (Exception ex) { throw new InvalidPluginExecutionException($"An error occurred in the SamplePlugin: {ex.Message}", ex); }- Catches runtime exceptions and throws them as
InvalidPluginExecutionExceptionfor debugging or logging purposes.
- Catches runtime exceptions and throws them as
Usage Details
- Registration: Use the Plugin Registration Tool to register this plugin in CRM for the
Createmessage. - 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 moreWe can help you with How to Write and Understand a Dynamics CRM Plugin
If you want help implementing, troubleshooting, or improving this product, contact us and we’ll point you in the right direction.
Related posts
Copilot Studio: Agent Integration Approaches — Tools, Knowledge, and Agents
In Copilot Studio, agent integration employs the same fundamental integration concepts and patterns used in traditional enterprise integration...
Copilot Studio: How to Plan Integration with Enterprise Systems
Integrating Microsoft Copilot Studio agents with enterprise systems transforms a basic chatbot into a secure, intelligent digital teammate tha...
Book Review : The Manager 's Path : A Guide for Tech Leaders Navigating Growth and Change by Camille Fournier
After a long time, I came across a book that is truly valuable for engineering students and professionals, especially those working in t...
Power Platform Environment Deep Dive (Part 2)
In Microsoft Power Platform, choosing the right environment type is important because each environment is designed for a different business pu...
Power Platform Environment Deep Dive (Part 1)
Today, in the business enterpriese world, Power Platform enables organization to build application, automate workflow, analyze data crea...
Book Review : Life 3.0 by Max Tegmark
This is the third book I’ve read this year, and even though I’m still in the early chapters, it already feels like my favorite read of the yea...
Dataverse Views Demystified: Making Data Work for You
In Microsoft Dataverse, users do not always see all the data stored in a table. What they can view depends on their security permissions, role...
Decode & Fix : Shared App host initialization has timed out in Microsoft Power Apps
Issue :While working with apps in the Microsoft Power Platform, we encountered a critical issue where the application failed to load pro...
