How to update the parent record when child record is created/updated/Delete
The scenario is that I want to display the sum of total of “Service Cost” of the opportunity Product on the parent opportunity record.
#region References
using System;
using System.ServiceModel;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm;
using Microsoft.Xrm.Sdk.Query;
#endregion
namespace OpportunityCost
{
public class OpportunityCost : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
Entity preImageEntity = new Entity();
Guid OpportunityID = Guid.Empty;
//The InputParameters collection contains all the data passed in the message request.
try
{
if (context.Depth == 1)
{
string messageName = context.MessageName.ToUpper();
if (messageName == "CREATE")
{
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
Entity entity = (Entity)context.InputParameters["Target"];
if (entity.LogicalName != "opportunityproduct")
return;
if (entity.Attributes.Contains("opportunityid"))
{
OpportunityID = ((EntityReference)entity.Attributes["opportunityid"]).Id;
}
}
}
if (messageName == "UPDATE")
{
if (context.PreEntityImages.Contains("Image") && context.PreEntityImages["Image"] is Entity)
{
preImageEntity = context.PreEntityImages["Image"];
if (preImageEntity.Attributes.Contains("opportunityid"))
{
OpportunityID = preImageEntity.GetAttributeValue<EntityReference>("opportunityid").Id;
}
}
}
if (messageName == "DELETE")
{
if (context.PreEntityImages.Contains("Image") && context.PreEntityImages["Image"] is Entity)
{
preImageEntity = context.PreEntityImages["Image"];
if (preImageEntity.Attributes.Contains("opportunityid"))
{
OpportunityID = preImageEntity.GetAttributeValue<EntityReference>("opportunityid").Id;
}
}
}
}
//if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
//{
// Obtain the target entity from the input parmameters
//Entity entity = (Entity)context.InputParameters["Target"];
//if (entity.Attributes.Contains("opportunityid"))
//{
// OpportunityID = ((EntityReference)entity.Attributes["opportunityid"]).Id;
//}
//else
//{
// if (context.PreEntityImages.Contains("Image") && context.PreEntityImages["Image"] is Entity)
// {
// preImageEntity = context.PreEntityImages["Image"];
// OpportunityID = preImageEntity.GetAttributeValue<EntityReference>("opportunityid").Id;
// }
//}
decimal TotalServiceCost = 0;
TotalServiceCost = FetchResult(OpportunityID, service);
// Updating Parent Entity
Entity opportunityobj = new Entity("opportunity");
opportunityobj.Id = OpportunityID;
opportunityobj["new_totalservicecost"] = new Money(TotalServiceCost);
service.Update(opportunityobj);
//}
}
catch (Exception ex)
{
tracingService.Trace(ex.Message);
}
}
private static decimal FetchResult(Guid OpportunityID, IOrganizationService service)
{
string FetchOpportunityProduct = @" <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' aggregate='true'>
<entity name='opportunityproduct'>
<attribute name='new_servicecost' alias='totalservicecostamount_sum' aggregate='sum' />
<link-entity name='opportunity' from='opportunityid' to='opportunityid' alias='ab'>
<filter type='and'>
<condition attribute='opportunityid' operator='eq' value='{0}' />
</filter>
</link-entity>
</entity>
</fetch>";
decimal TotalValue = 0;
FetchOpportunityProduct = string.Format(FetchOpportunityProduct, OpportunityID);
EntityCollection result = (EntityCollection)service.RetrieveMultiple(new FetchExpression(FetchOpportunityProduct));
if (result.Entities.Count > 0)
{
foreach (var c in result.Entities)
{
decimal aggregate2 = ((Money)((AliasedValue)c.Attributes["totalservicecostamount_sum"]).Value).Value;
TotalValue = aggregate2;
}
}
return TotalValue;
}
}
}
The scenario is that I want to display the sum of total of “Service Cost” of the opportunity Product on the parent opportunity record.
#region References
using System;
using System.ServiceModel;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm;
using Microsoft.Xrm.Sdk.Query;
#endregion
namespace OpportunityCost
{
public class OpportunityCost : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
Entity preImageEntity = new Entity();
Guid OpportunityID = Guid.Empty;
//The InputParameters collection contains all the data passed in the message request.
try
{
if (context.Depth == 1)
{
string messageName = context.MessageName.ToUpper();
if (messageName == "CREATE")
{
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
Entity entity = (Entity)context.InputParameters["Target"];
if (entity.LogicalName != "opportunityproduct")
return;
if (entity.Attributes.Contains("opportunityid"))
{
OpportunityID = ((EntityReference)entity.Attributes["opportunityid"]).Id;
}
}
}
if (messageName == "UPDATE")
{
if (context.PreEntityImages.Contains("Image") && context.PreEntityImages["Image"] is Entity)
{
preImageEntity = context.PreEntityImages["Image"];
if (preImageEntity.Attributes.Contains("opportunityid"))
{
OpportunityID = preImageEntity.GetAttributeValue<EntityReference>("opportunityid").Id;
}
}
}
if (messageName == "DELETE")
{
if (context.PreEntityImages.Contains("Image") && context.PreEntityImages["Image"] is Entity)
{
preImageEntity = context.PreEntityImages["Image"];
if (preImageEntity.Attributes.Contains("opportunityid"))
{
OpportunityID = preImageEntity.GetAttributeValue<EntityReference>("opportunityid").Id;
}
}
}
}
//if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
//{
// Obtain the target entity from the input parmameters
//Entity entity = (Entity)context.InputParameters["Target"];
//if (entity.Attributes.Contains("opportunityid"))
//{
// OpportunityID = ((EntityReference)entity.Attributes["opportunityid"]).Id;
//}
//else
//{
// if (context.PreEntityImages.Contains("Image") && context.PreEntityImages["Image"] is Entity)
// {
// preImageEntity = context.PreEntityImages["Image"];
// OpportunityID = preImageEntity.GetAttributeValue<EntityReference>("opportunityid").Id;
// }
//}
decimal TotalServiceCost = 0;
TotalServiceCost = FetchResult(OpportunityID, service);
// Updating Parent Entity
Entity opportunityobj = new Entity("opportunity");
opportunityobj.Id = OpportunityID;
opportunityobj["new_totalservicecost"] = new Money(TotalServiceCost);
service.Update(opportunityobj);
//}
}
catch (Exception ex)
{
tracingService.Trace(ex.Message);
}
}
private static decimal FetchResult(Guid OpportunityID, IOrganizationService service)
{
string FetchOpportunityProduct = @" <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' aggregate='true'>
<entity name='opportunityproduct'>
<attribute name='new_servicecost' alias='totalservicecostamount_sum' aggregate='sum' />
<link-entity name='opportunity' from='opportunityid' to='opportunityid' alias='ab'>
<filter type='and'>
<condition attribute='opportunityid' operator='eq' value='{0}' />
</filter>
</link-entity>
</entity>
</fetch>";
decimal TotalValue = 0;
FetchOpportunityProduct = string.Format(FetchOpportunityProduct, OpportunityID);
EntityCollection result = (EntityCollection)service.RetrieveMultiple(new FetchExpression(FetchOpportunityProduct));
if (result.Entities.Count > 0)
{
foreach (var c in result.Entities)
{
decimal aggregate2 = ((Money)((AliasedValue)c.Attributes["totalservicecostamount_sum"]).Value).Value;
TotalValue = aggregate2;
}
}
return TotalValue;
}
}
}
Register this plugin on postcreate, postupdate , postDelete events of opportunity Product entity.
No comments:
Post a Comment