Sunday, November 10, 2019

Plugin Pre and PostImage Example 1


DYNAMICS 365 PLUGINS – PRE AND POST IMAGES

 Leave a comment
When using Dynamics 365 Plugins, we have the ability to view the record data before and after changes have been made. Here we will go through an example.
First, create a new class library in Visual Studio:
Add code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
 
namespace Carl.Crm.PrePostImage
{
    public class CheckAccount : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)
            serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));
 
            ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
 
            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                Entity entity = (Entity)context.InputParameters["Target"];
 
                if (entity.LogicalName == "account")
                {
                    Entity account = (Entity)context.InputParameters["Target"];
                    Entity preImageAccount = (Entity)context.PreEntityImages["Image"];
                    Entity postImageAccount = (Entity)context.PostEntityImages["Image"];
 
                    string preImagePhoneNumber = preImageAccount.GetAttributeValue<string>("telephone1");
                    string postImagePhoneNumber = postImageAccount.GetAttributeValue<string>("telephone1");
 
                    tracingService.Trace("Pre-image phone number: {0}, Post-image phone number: {1}", preImagePhoneNumber, postImagePhoneNumber);
                }
            }
        }
    }
}

Now, register a step:
Register on Post Operation:
We will filter this to run on the telephone1 change:
Now, register an image. Select the Update step we created above:
We will register this on Pre Image and Post Image:
First ensure tracing is enabled in System Settings:
Now we can run the code.
Go to an account and note the phone number:
Change the phone number:
Go to the Plugin Trace Log:
Open the record:
You will see the line we added in the message block:
“Pre-image phone number: 425-488-7759, Post-image phone number: 425-488-7758”

No comments:

Post a Comment