Capture field changes in a Dynamics 365 CE plugin
Post by: syed hussain in All C# Dynamics 365
Summary
The following code captures record updates in a Dynamics 365 CE plugin, and stores this in the description field.
This code can be used to track record-level changes.
The plugin should be registered on the pre-operation stage on the UPDATE message.
C# Code
using Microsoft.Xrm.Sdk;
using System;
using System.Collections.Generic;
using System.ServiceModel;
namespace PreImage
{
public class FollowupPlugin : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
// Obtain the tracing service
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
Entity entity = (Entity)context.InputParameters["Target"];
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
try
{
List<string> keys = new List<string>();
foreach (var result in entity.Attributes.Keys)
{
keys.Add(result);
}
// Insert changes to the description field
entity["description"] = String.Join(",", keys);
}
catch (FaultException<OrganizationServiceFault> ex)
{
throw new InvalidPluginExecutionException("An error occurred in Plugin.", ex);
}
catch (Exception ex)
{
tracingService.Trace("Plugin: {0}", ex.ToString());
throw;
}
}
}
}
}
Source Code
https://dev.azure.com/eax360/Global%20Catalogue%20Public%20Projects/_git/PreImage
Tags: plugin pre-operation track changes