Develop D365 Contact Creation Plugin with Unit Test Case

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

This line retrieves the tracing service, which is used for logging and debugging information during plugin execution.

IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

This line retrieves the execution context of the plugin, providing information about the current execution.

IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

This line retrieves the service factory, which is used to create an instance of the organization service.

IOrganizationService service = serviceFactory.CreateOrganizationService(new Guid?(context.UserId));

This line creates an instance of the organization service using the user ID from the plugin execution context.

if (context.Depth > 1) return;

This condition checks if the depth of the current plugin execution is greater than 1. If it is, the plugin returns without further processing. This check is often used to prevent infinite loops caused by plugins triggering other plugins.

Open Visual Studio Code.

Create a new file with a .cs extension, for example, ManageContact.cs.

Paste the provided code into the file.

Make sure to replace Plugin and ManageContact with appropriate names.

using System;
using Common.ExtensionClasses;
using Microsoft.Xrm.Sdk;

namespace Plugins
{
    public class ManageContact:IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService tracer = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = factory.CreateOrganizationService(null);
            if (context.MessageName == "Create" && context.StageType() == ExecutionContextExtensions.StageTypeValues.PreExecution)
            {
                Entity contactTarget = (Entity)context.InputParameters["Target"];
                if (contactTarget.LogicalName != "contact")
                {
                    return;
                }
                contactTarget.Attributes.Add("lookup", Guid.NewGuid().ToString());
                contactTarget.Attributes.Add("string", "test");
                contactTarget.Attributes.Add("datetime", new DateTime());
                contactTarget.Attributes.Add("Optionset", Guid.NewGuid().ToString());
                contactTarget.Attributes.Add("twooptionset", true);
                contactTarget.Attributes.Add("Wholenumber", 1234567890);
            }
        }
    }
}

Unit Test Code For Plugin on Create of Contact with PreOperation

[TestMethod]
public void OnCreateContact_UpdateContact_PreOperation()
{
    var targetEntity = new Entity("contact")
    {
        Id = Guid.NewGuid(),
    };

    var inputParameters = new ParameterCollection
        {
             { "Target", targetEntity },
        };

    var preOperationContext = new XrmFakedPluginExecutionContext
    {
        MessageName = "Create",
        InputParameters = inputParameters,
        Stage = 20
    };

    _context.ExecutePluginWith<Inspire.Plugins.Integration.ManageContact>(preOperationContext);
    // Assert
    // Verify that the attributes are set as expected

    var contactTarget = (Entity)preOperationContext.InputParameters["Target"];
    Assert.AreEqual("contact", contactTarget.LogicalName, "LogicalName should be 'contact'");
    Assert.IsTrue(contactTarget.Attributes.ContainsKey("lookup"), "Attribute 'lookup' should be added");
    Assert.AreEqual("test", contactTarget.Attributes["string"], "Attribute 'string' should be set to 'test'");
    Assert.IsNotNull(contactTarget.Attributes["datetime"], "Attribute 'datetime' should not be null");
    Assert.IsTrue(contactTarget.Attributes.ContainsKey("Optionset"), "Attribute 'Optionset' should be added");
    Assert.AreEqual(true, contactTarget.Attributes["twooptionset"], "Attribute 'twooptionset' should be set to true");
    Assert.AreEqual(1234567890, contactTarget.Attributes["Wholenumber"], "Attribute 'Wholenumber' should be set to 1234567890");
}

Register a Plugin in the Plugin Registration Tool

Connect to trail CRM

Create new connection

Select the Environment of the CRM

Asia pacific area

Register new Assembly

Register new Assembly

Choose an Assembly

Choose assembly

Register new Step

Register new step

On Create of Contact Preoperation

Create contact


Similar Articles