Plugin Development: Retrieve data using images

Images are useful for data comparison before and after core operation. We can register plugins on two type of images:

  • Pre-Image
  • Post-Image

Pre-Image can be used for retrieving the value of an entity attribute before core operation takes place.
Post-Image can be used for retrieving the value of an entity attribute after the core operation has taken place.

Scenario: On contact entity we have email address field. Let’s stop users from updating the email address field by showing them the old and new values.

using System;
using Microsoft.Xrm.Sdk;

namespace HelloPlugin
{
public class PreImagePlugin: IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

// Get a reference to the Organization service.
IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = factory.CreateOrganizationService(context.UserId);

if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
Entity entity = (Entity)context.InputParameters["Target"];

try
{
//Implement Plugin Business Logic here
string newemailaddress = string.Empty;

if (entity.Attributes.Contains("emailaddress1"))
{
newemailaddress = entity.Attributes["emailaddress1"].ToString();
}

Entity preImageContact = (Entity)context.PreEntityImages["PreImage"]; //PreImage is user defined name you can name anything.

string oldemailaddr = preImageContact.Attributes["emailaddress1"].ToString(); //preImageContact will provide us the value which was saved before the update event.

throw new InvalidPluginExecutionException("The email address is modified from " + oldemailaddr + " to " + newemailaddress);
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(ex.Message);
}
}
}
}
}

Below is the screenshot of the exception message thrown by our plugin:

Figure 1: Populating email address using pre-image

Design a site like this with WordPress.com
Get started