Showing posts with label fetch xml. Show all posts
Showing posts with label fetch xml. Show all posts

Friday, April 27, 2012

How to update the parent record when children records are created or updated

Few months ago, I wrote a blog on “How to update the children records when parent record is updated”. Here is link to that blog. In this blog I am posting a code on “How to update the parent record when child record is created or updated”. The scenario is that I want to display the sum of total of "Estimated Revenue” of the opportunities on the parent account record. Here are the steps
  • Create a new attribute named “new_oppamount” on the account entity and place it on the account entity form.
  • Publish the account entity
  • Create the plugin
  • Register this plugin on postcreate, postupdate , postsetstate and postsetstatedynamic  events of opportunity entity.
Here is the code. The code is using the fetch xml to get the sum of “Estimated Revenue” field of the open opportunities. Follow the steps mentioned in here and replace the ExecutePostAccountUpdateContacts method with follwing method
protected void ExecutePostOpportunityCreate(LocalPluginContext localContext)
{
    if (localContext == null)
    {
        throw new ArgumentNullException("localContext");
    }
            

    IPluginExecutionContext context = localContext.PluginExecutionContext;

    //Get a IOrganizationService
    IOrganizationService service = localContext.OrganizationService;

    //create a service context
    var ServiceContext = new OrganizationServiceContext(service);
    //ITracingService tracingService = localContext.TracingService;

    // 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 parmameters.
        Entity entity = (Entity)context.InputParameters["Target"];

        //get the customerid
        EntityReference a = (EntityReference)entity.Attributes["customerid"];
                
        decimal totalAmount=0;
                
        try
        {   
            //fetchxml to get the sum total of estimatedvalue
            string estimatedvalue_sum = string.Format(@" 
            <fetch distinct='false' mapping='logical' aggregate='true'> 
                <entity name='opportunity'> 
                    <attribute name='estimatedvalue' alias='estimatedvalue_sum' aggregate='sum' /> 
                    <filter type='and'>
                        <condition attribute='statecode' operator='eq' value='Open' />
                            <condition attribute='customerid' operator='eq' value='{0}' uiname='' uitype='' />
                    </filter>
                </entity>
            </fetch>", a.Id);
            EntityCollection estimatedvalue_sum_result = service.RetrieveMultiple(new FetchExpression(estimatedvalue_sum));

            foreach (var c in estimatedvalue_sum_result.Entities)
            {
                totalAmount = ((Money)((AliasedValue)c["estimatedvalue_sum"]).Value).Value;
            }
                    
            //updating the field on the account
            Entity acc = new Entity("account");
            acc.Id = a.Id;
            acc.Attributes.Add("new_oppamount", new Money(totalAmount));
            service.Update(acc);
                    
                    
        }
        catch (FaultException ex)
        {
                throw new InvalidPluginExecutionException("An error occurred in the plug-in.", ex);
        }
    }

}
Good Luck…