Here is the code:
using Microsoft.Xrm.Sdk;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ContactCalculator
{
public class ContactCalculatorPlugin : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
// Extract the tracing service for use in debugging sandboxed plug-ins.
ITracingService tracingService =
(ITracingService)serviceProvider.GetService(typeof(ITracingService));
// Obtain the execution context from the service provider.
IPluginExecutionContext context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));
// Obtain the organization service reference.
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parameters.
Entity contact = (Entity)context.InputParameters["Target"];
Entity contactimage = context.PreEntityImages["Target"];
string ourdescription = string.Empty;
string total = string.Empty;
string custom_field_A = string.Empty;
string custom_field_B = string.Empty;
string custom_field_C = string.Empty;
string custom_field_D = string.Empty;
if (context.MessageName.ToUpper() == "CREATE")
{
if (contact.Attributes.Contains("custom_field_A"))
{
custom_field_A = contact["custom_field_A"].ToString();
}
if (contact.Attributes.Contains("custom_field_B"))
{
custom_field_B = contact["custom_field_B"].ToString();
}
if (contact.Attributes.Contains("custom_field_C"))
{
custom_field_C = contact["custom_field_C"].ToString();
}
// Do ur calculation as per ur requirement and store it in custom_field_D variable
custom_field_D = custom_field_A + custom_field_B + custom_field_C;
contact["custom_field_D"] = custom_field_D;
}
if (context.MessageName.ToUpper() == "UPDATE")
{
if (contactimage.Attributes.Contains("crmn_ourcandidaterating"))
{
ourdescription = contactimage["crmn_ourcandidaterating"].ToString();
}
if (contactimage.Attributes.Contains("custom_field_A"))
{
custom_field_A = contactimage["custom_field_A"].ToString();
}
if (contactimage.Attributes.Contains("custom_field_B"))
{
custom_field_B = contactimage["custom_field_B"].ToString();
}
if (contactimage.Attributes.Contains("custom_field_C"))
{
custom_field_C = contactimage["custom_field_C"].ToString();
}
// Do ur calculation as per ur requirement and store it in custom_field_D variable
total = ourdescription;
contactimage["description"] = "testing 123";
}
// Write this plugin on Pre-Operations Stage to avoid one additional transaction to update the value in DB
// can write this plugin on Create as well as on Update
// Can avoid below line by reg plug-in in Pre Operation Stage
// Service.update(contact);
}
}
}
}