I'm trying to sum a custom field in quote entity the custom field is called new_itemweight. I have tried the below code but can't seem to get my head round it. Any guidance or help would be greatly appreciated
I have added the steps in the plugin reg for Post-create, Postupdate
My fields and entities are as follows
Parent Ent -quotes
Child - quotedetailsgrid
Column with in gris is - new_Itemweight
Field on parent for where i want the data is - new_totalweight
This is the code i'm trying to use
public class SumWeight : 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);
if (Context.PostEntityImages.Contains("PostImage") && Context.PostEntityImages["PostImage"] is Entity)
{
Entity Weight = (Entity)Context.InputParameters["Target"];
var WeightTot = (EntityReference)Weight.Attributes["quotedetailsGrid"];
decimal Total = FetchResult(WeightTot.Id, Service);
// Updating Parent Entity
Entity Quote = new Entity("quote");
Quote.Id = Weight.Id;
Quote["TestWeight"] = 10;
Service.Update(Quote);
}
}
private static decimal FetchResult(Guid quantity, IOrganizationService service)
{
string value_sum = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' aggregate='true'>
<entity name='quotedetailsGrid'>
<attribute name='ItemWeight' alias='ItemWeight_sum' aggregate='sum'/>
<filter type='and'>
<condition attribute='ItemWeight' operator='eq' value='{0}' />
</filter>
</entity>
</fetch>";
decimal TotalValue = 0;
value_sum = string.Format(value_sum, quantity);
EntityCollection value_sum_result = (EntityCollection)service.RetrieveMultiple(new FetchExpression(value_sum));
foreach (var c in value_sum_result.Entities)
{
decimal aggregate2 = ((int)((AliasedValue)c.Attributes["ItemWeight_sum"]).Value);
TotalValue = aggregate2;
}
return TotalValue;
}
}
}
may thanks for your help
Cheers
Dan