Code Snippets

  • Dynamics 365 C# Plugin Template
    C#
    A C# plugin template for Dynamics 365 is a reusable code structure that simplifies custom plugin development while following best practices.
A C# plugin template for Dynamics 365 is a reusable code structure that simplifies custom plugin development while following best practices. It includes components like context retrieval, validation, and error handling, allowing developers to focus on specific business logic efficiently.

using System; using Microsoft.Xrm.Sdk; namespace MyDynamicsPlugins { public class CreateContactPlugin : IPlugin { public void Execute(IServiceProvider serviceProvider) { // Obtain the tracing service ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); // Obtain the plugin execution context IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); // Obtain the organization service reference IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService orgService = serviceFactory.CreateOrganizationService(context.UserId); try { tracingService.Trace("CreateContactPlugin: Execution started..."); // Check if the plugin is triggered by 'Create' message if (context.MessageName == "Create" && context.InputParameters.Contains("Target")) { // 'Target' is the entity to be created Entity entity = (Entity)context.InputParameters["Target"]; // Make sure it's a Contact entity if (entity.LogicalName == "contact") { // Implement your custom logic here tracingService.Trace("CreateContactPlugin: Processing contact creation."); // Example: Check if 'description' field is empty if (!entity.Contains("description") || string.IsNullOrWhiteSpace(entity["description"].ToString())) { entity["description"] = "Auto-filled description by plugin"; tracingService.Trace("CreateContactPlugin: Description field auto-filled."); } } } tracingService.Trace("CreateContactPlugin: Execution completed successfully."); } catch (Exception ex) { // Trace the error tracingService.Trace("CreateContactPlugin: {0}", ex.ToString()); // Raise an exception so it appears in the user interface or logs throw new InvalidPluginExecutionException("An error occurred in the CreateContactPlugin.", ex); } } } }