Recently i had requirement where i had to update header fields of parent and child account. The header field values in the parent and child account should have same values .
If we have Asia HQ as a parent account which has two child accounts China and India . Then header field in child and parent should be sum of all the child account values.
Here sum of all local potential Annual child account field should be updated in HQ Top line Potential field in the header . Local Existing Business -> HQ Existing business and Local Active Opportunity to HQ Active opportunity.
I have written a plugin that uses execute multiple as described below.
You cannot use execute multiple to update all related accounts in one plugin. Another plugin will update the current record. Below is the plugin to update related records .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;
// Microsoft Dynamics CRM namespace(s)
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System.Collections;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
namespace ACES_OTHER_BRAND_UPDATE_HEADER
{
public class UPDATEOTHERBRANDHEADER : IPlugin
{
EntityCollection update = new EntityCollection()
{
EntityName = "account"
};
ExecuteMultipleRequest requestWithResults;
/// <summary>
/// A plug-in that creates a follow-up task activity when a new account is created.
/// </summary>
/// <remarks>Register this plug-in on the update message, account entity,
/// and asynchronous mode.
/// </remarks>
public void Execute(IServiceProvider serviceProvider)
{
//Extract the tracing service for use in debugging sandboxed plug-ins.
ITracingService tracingService =
(ITracingService)serviceProvider.GetService(typeof(ITracingService));
//<snippetFollowupPlugin1>
// Obtain the execution context from the service provider.
IPluginExecutionContext context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));
//</snippetFollowupPlugin1>
//<snippetFollowupPlugin2>
// 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 parameters.
Entity entity = (Entity)context.InputParameters["Target"];
//</snippetFollowupPlugin2>
Guid primaryEntityId = context.PrimaryEntityId;
// Verify that the target entity represents an account.
// If not, this plug-in was not registered correctly.
if (entity.LogicalName != "account")
return;
try
{
// Entity postentityimage = (Entity)context.PostEntityImages["Image"];
Entity postentityimage = (Entity)context.PostEntityImages["Image"];
EntityReference parentId = null;
if (postentityimage.Attributes.Contains("parentaccountid") && postentityimage.GetAttributeValue<EntityReference>("parentaccountid")!=null)
{
parentId = postentityimage.GetAttributeValue<EntityReference>("parentaccountid");
}
// if (preImageEntity.GetAttributeValue<Money>("hpcrm_Value") != postImageEntity.GetAttributeValue<Money>("hpcrm_value"))
//<snippetFollowupPlugin4>
// Obtain the organization service reference.
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
//</snippetFollowupPlugin4>
// if (context.Depth > 1) { return; }
// Create the task in Microsoft Dynamics CRM.
tracingService.Trace("FollowupPlugin: Creating the task activity.");
EntityCollection accountCollection = null;
if (parentId != null)
{
accountCollection = RetrieveChildAccount(tracingService, parentId.Id, service);
decimal localmarketactiveopportunitypotential = 0;
decimal localmarketexistingbusiness = 0;
decimal localmarketpotential = 0;
decimal sumlocalmarketactiveopportunitypotential = 0;
decimal sumlocalmarketpotential = 0;
decimal sumlocalmarketexistingbusiness = 0;
Guid accountid = Guid.Empty;
// string straccountid = string.Empty;
// ArrayList list = new ArrayList();
foreach (var childaccount in accountCollection.Entities)
{
// accountid = childaccount.GetAttributeValue<Guid>("accountid");
//straccountid = accountid.ToString();
// list.Add(straccountid);
if (childaccount.Attributes.Contains("aces_marketpotential"))
{
localmarketpotential = Convert.ToDecimal(childaccount.GetAttributeValue<Money>("aces_marketpotential").Value);
sumlocalmarketpotential = sumlocalmarketpotential + localmarketpotential;
//entity.Attributes.Add("hpcrm_aum", new Money(AumPercentile));
}
if (childaccount.Attributes.Contains("aces_localmarketactiveopportunitypotential"))
{
localmarketactiveopportunitypotential = Convert.ToDecimal(childaccount.GetAttributeValue<Money>("aces_localmarketactiveopportunitypotential").Value); ;
// entity.Attributes.Add("hpcrm_revenue", new Money(Revenue));
sumlocalmarketactiveopportunitypotential = sumlocalmarketactiveopportunitypotential + localmarketactiveopportunitypotential;
}
if (childaccount.Attributes.Contains("aces_annualfeeincomeassumption"))
{
localmarketexistingbusiness = Convert.ToDecimal(childaccount.GetAttributeValue<Money>("aces_annualfeeincomeassumption").Value); ;
// entity.Attributes.Add("hpcrm_revenue", new Money(Revenue));
sumlocalmarketexistingbusiness = sumlocalmarketexistingbusiness + localmarketexistingbusiness;
}
}
// Entity accountentity = new Entity("account");
foreach (var childaccount in accountCollection.Entities)
{
accountid = childaccount.GetAttributeValue<Guid>("accountid");
if (accountid != primaryEntityId)
{
Entity accountentity = new Entity("account");
accountentity["accountid"] = accountid;
accountentity["aces_hqactiveopportunitiesusdinmillions"] = new Money(sumlocalmarketactiveopportunitypotential);
accountentity["aces_hqpotentialannual"] = new Money(sumlocalmarketpotential);
accountentity["aces_hqexisitingbusss"] = new Money(sumlocalmarketexistingbusiness);
update.Entities.Add(accountentity);
}
}
if (parentId != null)
{
Entity accountentity = new Entity("account");
accountentity["accountid"] = parentId.Id;
accountentity["aces_hqactiveopportunitiesusdinmillions"] = new Money(sumlocalmarketactiveopportunitypotential);
accountentity["aces_hqpotentialannual"] = new Money(sumlocalmarketpotential);
accountentity["aces_hqexisitingbusss"] = new Money(sumlocalmarketexistingbusiness);
update.Entities.Add(accountentity);
}
// Create an ExecuteMultipleRequest object.
requestWithResults = new ExecuteMultipleRequest()
{
// and to not return responses.
Settings = new ExecuteMultipleSettings()
{
ContinueOnError = false,
ReturnResponses = false
},
Requests = new OrganizationRequestCollection()
};
// EntityCollection update = GetCollectionOfEntitiesToUpdate();
foreach (var entitytoUpdate in update.Entities)
{
UpdateRequest updateRequest = new UpdateRequest { Target = entitytoUpdate };
requestWithResults.Requests.Add(updateRequest);
}
// Execute all the requests in the request collection using a single web method call.
ExecuteMultipleResponse responseWithResults =
(ExecuteMultipleResponse)service.Execute(requestWithResults);
// Display the results returned in the responses.
foreach (var responseItem in responseWithResults.Responses)
{
// A valid response.
if (responseItem.Response != null)
DisplayResponse(requestWithResults.Requests[responseItem.RequestIndex], responseItem.Response);
// An error has occurred.
else if (responseItem.Fault != null)
DisplayFault(requestWithResults.Requests[responseItem.RequestIndex],
responseItem.RequestIndex, responseItem.Fault);
}
}
}
//<snippetFollowupPlugin3>
catch (FaultException<OrganizationServiceFault> ex)
{
throw new InvalidPluginExecutionException("An error occurred in the FollupupPlugin plug-in.", ex);
}
//</snippetFollowupPlugin3>
catch (Exception ex)
{
tracingService.Trace("FollowupPlugin: {0}", ex.ToString());
throw;
}
}
}
public EntityCollection RetrieveChildAccount(ITracingService trace, Guid parentAccountId, IOrganizationService service)
{
try
{
trace.Trace("to retrieve RetrieveAllRelatedHouseHold");
QueryExpression queryExp = new QueryExpression();
queryExp.EntityName = "account";
queryExp.ColumnSet = new ColumnSet();
queryExp.ColumnSet.AddColumns("accountid", "parentaccountid", "aces_localmarketactiveopportunitypotential" , "aces_annualfeeincomeassumption", "aces_marketpotential" );
ConditionExpression condition1 = new ConditionExpression();
condition1.AttributeName = "parentaccountid";
condition1.Operator = ConditionOperator.Equal;
condition1.Values.Add(parentAccountId);//condition to retrieve cases associated with Master Case
FilterExpression filterExpression = new FilterExpression();
filterExpression.AddCondition(condition1);
filterExpression.FilterOperator = LogicalOperator.And;
queryExp.Criteria = filterExpression;
var accountCollection = service.RetrieveMultiple(queryExp);
trace.Trace("Associated RetrieveAllRelatedHouseHold retrieved");
return accountCollection;
}
catch (FaultException<OrganizationServiceFault> exception)
{
trace.Trace("Exception: {0}", exception.ToString());
throw new FaultException("RetrieveAllClient");
}
}
/// <summary>
/// Display the response of an organization message request.
/// </summary>
/// <param name="organizationRequest">The organization message request.</param>
/// <param name="organizationResponse">The organization message response.</param>
private void DisplayResponse(OrganizationRequest organizationRequest, OrganizationResponse organizationResponse)
{
//Console.WriteLine("Created " + ((Account)organizationRequest.Parameters["Target"]).Name
// + " with account id as " + organizationResponse.Results["id"].ToString());
//_newAccountIds.Add(new Guid(organizationResponse.Results["id"].ToString()));
}
/// <summary>
/// Display the fault that resulted from processing an organization message request.
/// </summary>
/// <param name="organizationRequest">The organization message request.</param>
/// <param name="count">nth request number from ExecuteMultiple request</param>
/// <param name="organizationServiceFault">A WCF fault.</param>
private void DisplayFault(OrganizationRequest organizationRequest, int count,
OrganizationServiceFault organizationServiceFault)
{
//Console.WriteLine("A fault occurred when processing {1} request, at index {0} in the request collection with a fault message: {2}", count + 1,
// organizationRequest.RequestName,
// organizationServiceFault.Message);
}
}
}