Skip to main content

Notifications

Announcements

No record found.

Customer experience | Sales, Customer Insights,...
Answered

Plugin to update parent on creation of child records

Posted on by 7,316

Hi,

I am trying to write a plugin where everytime a child record gets created.updated/deleted, the associated parent record should be updated with sum of all child record's amount value.

Here is my plugin(below) which works fine updating the parent record with sum of all the existing child record's amount value except the newly created(about to be) child record's amount value.

Also, child record won't get created and I just get a business process error(no useful information of error).

So, updates the parent record but fails to create child record. What am I doing wrong here? Can anybody please suggest? Thanks for any help!

IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); 
// Get a reference to the Organization service.
IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); 
IOrganizationService service = factory.CreateOrganizationService(context.UserId);
if (context.InputParameters != null) {
Entity entity = (Entity)context.InputParameters["Target"];

//get the associated parent id 
EntityReference a = (EntityReference)entity.Attributes["new_xxx"];
decimal totalAmount = 0; 
try { 
//fetchxml to get the sum total of expense amount 
string estimatedvalue_sum = string.Format(@"   
     ",
a.Id);
EntityCollection estimatedvalue_sum_result = service.RetrieveMultiple(new FetchExpression(estimatedvalue_sum));
foreach (var c in estimatedvalue_sum_result.Entities)
{ totalAmount = ((Money)((AliasedValue)c["amount_sum"]).Value).Value; }

//updating the field on the aaa 
Entity aaa = new Entity("new_xxx"); 
aaa.Id = a.Id;
aaa.Attributes.Add("new_amount", new Money(totalAmount));
service.Update(aaa);

  • meenoo Profile Picture
    meenoo 7,316 on at
    RE: Plugin to update parent on creation of child records

    I have unregistered the plugin and registered it again. Now everything works fine.

    Thanks for guiding me through this. All good suggestions.

  • Suggested answer
    Charles Abi Khirs Profile Picture
    Charles Abi Khirs 3,569 on at
    RE: Plugin to update parent on creation of child records

    It looks everything is Ok in your code, even after refresh the form it is not updated?

    Here s similar thread about setting Money field in C# for moore verification: community.dynamics.com/.../how-to-set-currency-field

  • meenoo Profile Picture
    meenoo 7,316 on at
    RE: Plugin to update parent on creation of child records

    Ok, I tried making changes suggested by Andrew.

    I have made plugin async and plugin was already in post operation.

    This time the child record gets saved without any error but update on parent record won't happen.

    I did debug and everything executes normally, no errors or anything at service.update() line either.

    I do get the aggregate value of all child records including the latest one but it won't get updated on parent form.

    what could be the reason? any suggestions? Thanks for all the suggestions so far.

  • Charles Abi Khirs Profile Picture
    Charles Abi Khirs 3,569 on at
    RE: Plugin to update parent on creation of child records

    Then I suggest to go with Andrew solution.

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Plugin to update parent on creation of child records

    if you choose to go the rollup route, here's how you can force recalculate within a plugin (oda is a salesorder EntityRefernce) :

               Microsoft.Crm.Sdk.Messages.CalculateRollupFieldRequest req = new Microsoft.Crm.Sdk.Messages.CalculateRollupFieldRequest {

                   Target = oda, FieldName = "new_detailcount"

               };

               Microsoft.Crm.Sdk.Messages.CalculateRollupFieldResponse res = (Microsoft.Crm.Sdk.Messages.CalculateRollupFieldResponse)service.Execute(req);

  • Suggested answer
    a33ik Profile Picture
    a33ik 84,323 Most Valuable Professional on at
    RE: Plugin to update parent on creation of child records

    I mentioned what should be changed in my first reply.

  • meenoo Profile Picture
    meenoo 7,316 on at
    RE: Plugin to update parent on creation of child records

    Nope.. I am not sure what to modify!

    My doubt is on the fetchxml query. It is only retrieving the ones that are already created and in the database and not the one about to be created! You see what I mean? Thanks.

  • Suggested answer
    a33ik Profile Picture
    a33ik 84,323 Most Valuable Professional on at
    RE: Plugin to update parent on creation of child records

    Hello,

    Did you modify your code comparing to initial version?

  • meenoo Profile Picture
    meenoo 7,316 on at
    RE: Plugin to update parent on creation of child records

    I am getting a generic error when creating the child record. So, the plugin is set to trigger on create of child record(Post Operation) and update the parent record with sum of all the amounts on child records(multiple records associated to parent record).

    It does update the parent record with sum of all the child records amounts except the one I am about to create. So, the total amount on parent record is wrong. And the child record won't get saved. It throws this error.

      at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.CreateInternal(Entity entity, InvocationContext invocationContext, CallerOriginToken callerOriginToken, WebServiceType serviceType, Boolean checkAdminMode, Dictionary`2 optionalParameters)

      at Microsoft.Crm.Extensibility.OData.CrmODataExecutionContext.CreateOrganizationResponse(Entity entity)

      at Microsoft.Crm.Extensibility.OData.CrmODataServiceDataProvider.CreateEdmEntity(CrmODataExecutionContext context, String edmEntityName, EdmEntityObject entityObject, Boolean isUpsert)

      at Microsoft.Crm.Extensibility.OData.EntityController.PostEntitySetImplementation(String& entitySetName, EdmEntityObject entityObject)

      at Microsoft.PowerApps.CoreFramework.ActivityLoggerExtensions.Execute[TResult](ILogger logger, EventId eventId, ActivityType activityType, Func`1 func, IEnumerable`1 additionalCustomProperties)

      at Microsoft.Xrm.Telemetry.XrmTelemetryExtensions.Execute[TResult](ILogger logger, XrmTelemetryActivityType activityType, Func`1 func)

      at lambda_method(Closure , Object , Object[] )

      at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)

      at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)

    --- End of stack trace from previous location where exception was thrown ---

      at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

      at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

      at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()

    --- End of stack trace from previous location where exception was thrown ---

      at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

      at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

      at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()

    --- End of stack trace from previous location where exception was thrown ---

      at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

      at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

      at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()

    Activity Id: 31b11e91-0240-4e25-af95-22419d1e08a1

    I did debug and everything goes through fine without any errors! Makes sense? what is going wrong here?

    Thanks.

  • Charles Abi Khirs Profile Picture
    Charles Abi Khirs 3,569 on at
    RE: Plugin to update parent on creation of child records

    In that case, writing plugins is the best option to go with.

    What is the error you are facing?

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

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,253 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,188 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans