Auto Calculate Roll up field In Dynamics 365

Recently we came across a scenario in which we need to force roll up field calculation. We did not wanted to wait for roll up calculation by CRM system.

More info on roll up fields : https://docs.microsoft.com/en-us/dynamics365/customer-engagement/customize/define-rollup-fields

This can be achieved by using CalculateRollupFieldRequest class.

https://docs.microsoft.com/en-us/dotnet/api
/microsoft.crm.sdk.messages
.calculaterollupfieldrequest?view=dynamics
-general-ce-9

using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sample Plugin
{
public class Update RollUp Field : Plugin
{
public void Execute(IServiceProvider
service Provider)
{
//Extract the tracing service for use in
debugging sandboxed plug-ins.
ITracingService tracingService =
(ITracingService)service Provider.GetService
(typeof(ITracingService));
// Obtain the execution context from the service provider.

IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
// To create organization service
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
// The InputParameters collection contains all the data passed in the message request.
#region On Create
if (context.MessageName == “Create” && context.InputParameters.Contains(“Target”) && context.InputParameters[“Target”] is Entity)
{
Entity Insured = (Entity)context.InputParameters[“Target”];
EntityReference Quote = (EntityReference)Insured[“zh_quote”]; //retrieving quote from custom entity
CalculateRollupFieldRequest crfr = new CalculateRollupFieldRequest
{
Target = new EntityReference(“quote”, Quote.Id), //Entity on which rollup is present
FieldName = “zh_totalpremium” // rollup field name
};
CalculateRollupFieldResponse response = (CalculateRollupFieldResponse)service.Execute(crfr);
Entity QuoteEntity = response.Entity; // this will contain the entity with updated rollup value
var totalPremium = ((Money)QuoteEntity.Attributes[“zh_totalpremium”]).Value;
Entity QuoteEntity = new Entity(“quote”);
QuoteEntity.Id = Quote.Id;
QuoteEntity[“zh_totalpremium”] = new Money((decimal)totalPremium);
service.Update(QuoteEntity); //Update the rollup field
}
#endregion

}

}

}