Skip to main content

Most Commonly Used Functions in C# Plugins for Dynamics 365

Welcome to my blog! In this post, we will explore some of the most commonly used functions when developing C# plugins for Dynamics 365. These functions are vital tools for interacting with data, handling errors, and customizing the behavior of your Dynamics 365 application. If you're working with plugins, these are the functions you'll most likely encounter and use.


If you find this post useful, please feel free to follow and support me on my LinkedIn profile. Let’s get started!


1. IOrganizationService


The IOrganizationService interface is the primary service for interacting with Dynamics 365 records. It allows you to create, retrieve, update, and delete records in the system. Most plugin operations rely on this service for performing CRUD (Create, Read, Update, Delete) actions.


Commonly used methods:


Create: Used to create a new record in Dynamics 365.


Retrieve: Used to fetch a record from Dynamics 365 based on the entity's ID.


Update: Used to update an existing record.


Delete: Deletes a record.


Execute: Executes a custom action or message.




Example of using IOrganizationService to retrieve a record:


IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

Entity contact = service.Retrieve("contact", contactId, new ColumnSet("firstname", "lastname"));


2. IPluginExecutionContext


The IPluginExecutionContext provides the context of the operation being executed, such as the entity, the type of message (create, update, delete), and input parameters. It also includes critical information like the user ID and the organization ID.


Commonly used properties:


MessageName: The name of the message being executed (e.g., Create, Update).


InputParameters: A collection of parameters passed to the plugin, typically containing the target entity.


UserId: The ID of the user who triggered the plugin.




Example of retrieving the message name from the context:


string message = context.MessageName;


3. Entity


The Entity class is used to represent a record in Dynamics 365. It contains properties that correspond to the fields of the record and can be used to retrieve or modify data.


Commonly used methods:


Contains: Checks if a particular attribute exists in the entity.


GetAttributeValue: Retrieves the value of an attribute from the entity.


AddAttribute: Adds a new attribute to the entity.




Example of using the Entity class to check if an attribute exists:


if (entity.Contains("email"))

{

    string email = entity.GetAttributeValue<string>("email");

}


4. EntityReference


The EntityReference class is used to store references to other records in Dynamics 365, typically through lookup fields. It contains the ID, entity name, and name of the related entity.


Commonly used properties:


Id: The GUID of the related record.


LogicalName: The logical name of the related entity (e.g., contact, account).




Example of creating an EntityReference to a related Account record:


EntityReference accountRef = new EntityReference("account", accountId);


5. IPluginExecutionContext.PostEntityImages


The PostEntityImages collection contains a snapshot of the record after the operation is executed, useful for comparing pre- and post-update states of a record. This is particularly useful in scenarios where you need to compare the changes made during an update.


Commonly used methods:


GetEntity: Retrieves the entity snapshot after the operation.




Example of using a post-image to retrieve the updated value:


if (context.PostEntityImages.Contains("PostImage"))

{

    Entity postImage = context.PostEntityImages["PostImage"];

    string updatedFieldValue = postImage.GetAttributeValue<string>("fieldname");

}


6. ITracingService


The ITracingService is an essential tool for debugging your plugins. It allows you to log messages that can be viewed in the plugin trace log. It’s useful for tracking the flow of your plugin and understanding what’s happening during execution.


Commonly used methods:


Trace: Logs a trace message for debugging purposes.




Example of using ITracingService to trace a message:


ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

tracingService.Trace("This is a trace message");


7. Throwing Exceptions


In your plugins, you may need to throw exceptions to stop further execution or indicate errors. The InvalidPluginExecutionException is the most commonly used exception for stopping plugin execution with a custom error message.


Example of throwing an exception:


throw new InvalidPluginExecutionException("An error occurred while processing the plugin.");


8. PreImage and PostImage


These are snapshots of the entity before and after the operation is executed. You can define which fields you want to retrieve in the pre- and post-images when registering the plugin step.


PreImage: Contains data before the operation.


PostImage: Contains data after the operation.



Example of retrieving a pre-image:


if (context.PreEntityImages.Contains("PreImage"))

{

    Entity preImage = context.PreEntityImages["PreImage"];

    string fieldValueBeforeUpdate = preImage.GetAttributeValue<string>("fieldname");

}


Conclusion: 


These functions and methods form the core of most C# plugins in Dynamics 365. They allow you to interact with records, handle execution context, trace debugging information, and manipulate data effectively. Whether you're creating, updating, or deleting records, understanding how and when to use these tools will make your plugin development much more efficient.


I hope this post helped you understand the most comm

only used functions in Dynamics 365 C# plugins. If you found this helpful, please feel free to follow me on LinkedIn for more updates and insights.

https://in.linkedin.com/in/pavan-kumar-vuyyuru

Comments

Popular posts from this blog

Powerapps: Collections in Canvas Apps | Collect, ClearCollect, Clear in Powerapps

Collections : Collections are special types of variables or data storage mechanism which can be used to manipulate the data within Power Apps.  Collections are usually a group of similar items which acts like a table of values with columns and rows.  We can create, update, delete, use it as the data source for a gallery to view the items within Power App.  Collect, Clear, and ClearCollect functions:   Collect : In Power Apps, the Collect function is used to create or update a collection in your app.  Collections are temporary data sources that allow you to store and work with data within your app.  The Collect function is versatile and can be used in various scenarios to add, modify, or remove records from a collection.  Syntax : Collect( IceCream, { Flavor: "Pistachio", Quantity: 40 }, { Flavor: "Orange", Quantity: 200 } )   Adds two records to the IceCream collection that includes a quantity of pistachio and orange ice cream.  Clear : In Po...

Understanding the Basics of C# Plugins in Dynamics 365: A Simple Account Update Example

Welcome to my blog! Today, we’ll dive into the world of C# plugins in Dynamics 365. If you're working with Dynamics 365, you’ve likely heard of plugins, which allow you to extend the platform's functionality and automate various processes. In this post, I’ll walk you through the parts of a plugin, using a simple example of updating an account record. What Is a C# Plugin? A plugin in Dynamics 365 is a custom business logic component that responds to specific events in the system. Plugins are executed in response to a trigger event, like creating or updating a record, and can be used to modify data or integrate with other systems. Written in C#, they are powerful tools for customizing and extending the functionality of Dynamics 365. The Structure of a C# Plugin A plugin typically consists of several parts: Plugin Registration – You register the plugin in Dynamics 365 to define what event triggers the plugin (create, update, delete) and which entity it will affect (e.g., A...

Essential Dynamics 365 Plugins for Sales & Customer Service

Introduction In Dynamics 365, plugins automate business processes, enforce rules, and ensure data integrity. Whether in Sales or Customer Service , plugins help streamline workflows by executing logic at the right time in the pipeline. This post covers key plugin scenarios , detailing: ✅ Execution pipeline stage (Pre-Validation, Pre-Operation, Post-Operation) ✅ Synchronous or Asynchronous execution ✅ Pre-Image / Post-Image usage ✅ Rollback handling Rollback Handling in Plugins When Does a Plugin Rollback? A plugin automatically rolls back if: An exception is thrown in a synchronous plugin. A transaction fails in a Pre-Validation or Pre-Operation stage. How to Handle Rollbacks? Use Try-Catch Blocks : Prevent unwanted failures by catching errors and logging details. Throw an Exception When Needed : Stop invalid data changes (e.g., prevent closing an Opportunity without a Quote). Compensating Logic in Async Plugins : Since Post-Operation Async plugins do not par...