Skip to content

Instantly share code, notes, and snippets.

@ltwlf
Last active February 20, 2020 08:36
Show Gist options
  • Save ltwlf/afdef778fcfcf1974841b634780d59ec to your computer and use it in GitHub Desktop.
Save ltwlf/afdef778fcfcf1974841b634780d59ec to your computer and use it in GitHub Desktop.
CDS Calculate Rollup
using System;
using System.ServiceModel;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
namespace QuotationCalculateSum
{
public class CalculatorPlugin : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
// Obtain the tracing service
ITracingService tracingService =
(ITracingService)serviceProvider.GetService(typeof(ITracingService));
// Obtain the execution context from the service provider.
IPluginExecutionContext context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));
tracingService.Trace("test");
// The InputParameters collection contains all the data passed in the message request.
if (context.InputParameters.Contains("Target") &&
context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parameters.
Entity entity = (Entity)context.InputParameters["Target"];
// Obtain the organization service reference which you will need for
// web service calls.
IOrganizationServiceFactory serviceFactory =
(IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
entity = service.Retrieve(entity.LogicalName, entity.Id, new ColumnSet("hx_parent_quote"));
try
{
var quoteRef = entity.GetAttributeValue<EntityReference>("hx_parent_quote");
// Entity quote = null;
if (quoteRef != null)
{
// quote = service.Retrieve(quoteRef.LogicalName, quoteRef.Id, new ColumnSet("hx_quote_total"));
var crfrRequested = new CalculateRollupFieldRequest
{
Target = new EntityReference(quoteRef.LogicalName, quoteRef.Id),
FieldName = "hx_quote_total"
};
var responseRequested = (CalculateRollupFieldResponse)service.Execute(crfrRequested);
tracingService.Trace("New Rollupfield Value = " + responseRequested.Entity.GetAttributeValue<decimal>("hx_parent_quote"));
}
}
catch (FaultException<OrganizationServiceFault> ex)
{
throw new InvalidPluginExecutionException("An error occurred in FollowUpPlugin.", ex);
}
catch (Exception ex)
{
tracingService.Trace("FollowUpPlugin: {0}", ex.ToString());
throw;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment