Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics CRM forum
Suggested answer

Recalculate Totals in Custom Entity with c# plugin

Posted on by 105

Hello, 

Can anyone help me how to proceed with my code. 

This is my code for calculating totals when creating a record in order product lines. 

if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)

            {

                if (context.MessageName == "Create")

                {

                    Entity salesorderdetail = context.InputParameters["Target"] as Entity;

 

                    if (salesorderdetail != null)

                    {

                        IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

                        IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

 

 

                        QueryExpression query = new QueryExpression()

                        {

                            Distinct = false,

                            EntityName = "crcd0_summaryorderproduct",

                            ColumnSet = new ColumnSet("crcd0_totalcost", "crcd0_totalmargin", "crcd0_roi", "crcd0_contractfromdate", "crcd0_contracttodate", "crcd0_totalamount"),

                            Criteria = new FilterExpression

                            {

                                Conditions =

                                {

                                    new ConditionExpression

                                    {

                                        AttributeName = "crcd0_existingproduct",

                                        Operator = ConditionOperator.Equal,

                                        Values =

                                        {

                                            salesorderdetail.GetAttributeValue<EntityReference>("productid").Id,

                                        }

                                    },

                                    new ConditionExpression

                                    {

                                        AttributeName = "crcd0_salesorder",

                                        Operator = ConditionOperator.Equal,

                                        Values =

                                        {

                                            salesorderdetail.GetAttributeValue<EntityReference>("salesorderid").Id,

                                        }

                                    }

                                }

                            }

                        };

                        EntityCollection summaryCollection = service.RetrieveMultiple(query);

                        Entity summary = summaryCollection[0];

 

                        QueryExpression salesOrderQuery = new QueryExpression()

                        {

                            Distinct = false,

                            EntityName = "salesorderdetail",

                            ColumnSet = new ColumnSet("crcd0_summarycost", "crcd0_margin", "priceperunit"),

                            Criteria = new FilterExpression

                            {

                               Conditions =

                                {

                                    new ConditionExpression

                                    {

                                        AttributeName = "productid",

                                        Operator = ConditionOperator.Equal,

                                        Values =

                                        {

                                            salesorderdetail.GetAttributeValue<EntityReference>("productid").Id,

                                        }

                                    },

 

                                    new ConditionExpression

                                   {

                                        AttributeName = "salesorderid",

                                        Operator = ConditionOperator.Equal,

                                        Values =

                                        {

                                            salesorderdetail.GetAttributeValue<EntityReference> ("salesorderid").Id,

                                        }

                                    }

                                }

                            }

                        };

 

                        QueryExpression salesorder = new QueryExpression()

                        {

                            Distinct = false,

                            EntityName = "salesorder",

                           ColumnSet = new ColumnSet("crcd0_totalcost", "crcd0_totalmargin"),

                            Criteria = new FilterExpression

                            {

                                Conditions =

                                {

                                    new ConditionExpression

                                    {

                                        AttributeName = "salesorderid",

                                        Operator = ConditionOperator.Equal,

                                        Values =

                                        {

                                            salesorderdetail.GetAttributeValue<EntityReference>("salesorderid").Id,

                                        }

                                    }

                                }

                            }

                        };

 

                        EntityCollection orderQuery = service.RetrieveMultiple(salesOrderQuery);

                        EntityCollection order = service.RetrieveMultiple(salesorder);

                        Entity salOrder = order[0];

                        var totalcost = (orderQuery.Entities.Sum(o => Convert.ToDecimal(o.GetAttributeValue<Money>("crcd0_summarycost").Value)));

                        var totalmargin = (orderQuery.Entities.Sum(o => Convert.ToDecimal(o.GetAttributeValue<Money>("crcd0_margin").Value)));

                        var roi = Convert.ToDecimal(0);

                        if (totalcost != 0)

                        {

                            roi = orderQuery.Entities.Sum(o => Convert.ToDecimal(o.GetAttributeValue<Money>("crcd0_summarycost").Value)) / orderQuery.Entities.Average(o => Convert.ToDecimal(o.GetAttributeValue<Money>("priceperunit").Value));

                        }

 

                        var totalamount = (orderQuery.Entities.Sum(o => Convert.ToDecimal(o.GetAttributeValue<Money>("priceperunit").Value)));

 

                        summary["crcd0_totalcost"] = new Money(totalcost);

                        summary["crcd0_totalmargin"] = new Money(totalmargin);

                        summary["crcd0_roi"] = roi;

                        summary["crcd0_totalamount"] = new Money(totalamount);

                        salOrder["crcd0_totalcost"] = new Money(totalcost);

                        salOrder["crcd0_totalmargin"] = new Money(totalmargin);

                        service.Update(summary);

                        service.Update(salOrder);

 

                    }

                   

                }

}else if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is EntityReference && context.MessageName == "Delete")

{

}

}

I need to add on delete step and recalculate thw totals when a record is deleted. I tried creating the step as post op and adding pre image, but pre image is null. 

  • Suggested answer
    Bipin D365 Profile Picture
    Bipin D365 28,962 Moderator on at
    RE: Recalculate Totals in Custom Entity with c# plugin

    Hi,

    You should register your delete plugin on prevalidation stage

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Anton Venter – Community Spotlight

Kudos to our October Community Star of the month!

Announcing Our 2024 Season 2 Super Users!

A new season of Super Users has arrived, and we are so grateful for the daily…

Dynamics 365 Community Newsletter - September 2024

Check out the latest community news

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 290,537 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 228,520 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,148

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans