Dynamics 365 CRM [Dataverse] – How to cancel the merge cascade for a given relationship ?

In the previous blog, we saw the possibility to force the merge of two accounts if the subordinate account is attached to an active offer. Today we will see how to cancel the merge cascade for a given relationship.

Before going further, we will see the standard behavior of the merge. Indeed, after the merge, all child records that are linked to the subordinate record are attached to the master record.

This behavior is standard in the platform and cannot be changed. If you try to change this, you will find that the merge cascade option is grayed out and it is therefore impossible to change this behavior.

Generally, this behavior meets the business needs. But sometimes you want the records to remain attached to the subordinate account. After some investigation, I was able to implement a logic that implements this. In other words, the logic will cancel the transfer of child records from the subordinate account to the master account.

Proposed solution:

The trick is to attach the subordinate account’s child records to a temporary account before the main merge operation. After the merge performs all the necessary operations. The child records from the temporary account will be attached to the subordinate account, and then the temporary account will be deleted.

This involves the use of two plugins:

  • The first plugin will run at the PreOperation. This plugin will create a temporary account, retrieve the child records attached to the subordinate record according to a given relationship and then attach them to the temporary account.
  • The second plugin will run at the PostOperation. This plugin will attach the child records from the temporary account to the subordinate account and delete the temporary account.

All these operations will be executed in one transaction. The temporary account will exist only during the merge operation.

The implementation I propose requires a configuration table. The records in this table will help the two plugins to know which relations to look at. For example, the following configration allows to cancel the transfer of orders from the subordinate account to the Master account.

Below, the configuration table definition:

Pre-Operation plugin:

using System;
using System.ServiceModel;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Query;
namespace MergePoc.Plugins
{
/// <summary>
/// CancelMergeForChilds_PreOperation Plugin.
/// </summary>
public class CancelMergeForChilds_PreOperation : PluginBase
{
/// <summary>
/// Initializes a new instance of the <see cref="CancelMergeForChilds_PreOperation"/> class.
/// </summary>
/// <param name="unsecure">Contains public (unsecured) configuration information.</param>
/// <param name="secure">Contains non-public (secured) configuration information.
/// When using Microsoft Dynamics 365 for Outlook with Offline Access,
/// the secure string is not passed to a plug-in that executes while the client is offline.</param>
public CancelMergeForChilds_PreOperation(string unsecure, string secure)
: base(typeof(CancelMergeForChilds_PreOperation))
{
// TODO: Implement your custom configuration handling.
}
/// <summary>
/// Main entry point for he business logic that the plug-in is to execute.
/// </summary>
/// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the
/// <see cref="IPluginExecutionContext"/>,
/// <see cref="IOrganizationService"/>
/// and <see cref="ITracingService"/>
/// </param>
/// <remarks>
/// For improved performance, Microsoft Dynamics 365 caches plug-in instances.
/// The plug-in's Execute method should be written to be stateless as the constructor
/// is not called for every invocation of the plug-in. Also, multiple system threads
/// could execute the plug-in at the same time. All per invocation state information
/// is stored in the context. This means that you should not use global variables in plug-ins.
/// </remarks>
protected override void ExecuteCdsPlugin(ILocalPluginContext localContext)
{
if (localContext == null)
{
throw new InvalidPluginExecutionException(nameof(localContext));
}
// Obtain the tracing service
ITracingService tracingService = localContext.TracingService;
try
{
// Obtain the execution context from the service provider.
IPluginExecutionContext context = (IPluginExecutionContext)localContext.PluginExecutionContext;
// Obtain the organization service reference for web service calls.
IOrganizationService currentUserService = localContext.CurrentUserService;
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is EntityReference)
{
EntityReference master = (EntityReference)context.InputParameters["Target"];
EntityReference sub = new EntityReference(master.LogicalName, (Guid)context.InputParameters["SubordinateId"]);
EntityCollection configs = getConfigs(currentUserService, master.LogicalName);
if (configs.Entities.Count > 0)
{
var tmpId = currentUserService.Create(new Entity(master.LogicalName));
var tmp = new Entity(master.LogicalName, tmpId);
foreach (var config in configs.Entities)
{
var childLogicalName = config.GetAttributeValue<string>("uma_childentity");
var relationshipLogicalName = config.GetAttributeValue<string>("uma_relationship");
RetrieveRelationshipRequest retrieveRelationShipRequest = new RetrieveRelationshipRequest { Name = relationshipLogicalName };
RetrieveRelationshipResponse retrieveRelationShipResponse = (RetrieveRelationshipResponse)currentUserService.Execute(retrieveRelationShipRequest);
OneToManyRelationshipMetadata meta = (OneToManyRelationshipMetadata)retrieveRelationShipResponse.RelationshipMetadata;
var from = meta.ReferencedAttribute;
var to = meta.ReferencingAttribute;
var query_parentid = sub.Id;
var query = new QueryExpression(meta.ReferencingEntity);
query.ColumnSet = new ColumnSet(to);
query.Criteria.AddCondition(to, ConditionOperator.Equal, query_parentid);
EntityCollection childs = currentUserService.RetrieveMultiple(query);
foreach (var child in childs.Entities)
{
child[to] = new EntityReference(tmp.LogicalName, tmp.Id);
currentUserService.Update(child);
}
}
context.SharedVariables.Add("tmp", tmp);
context.SharedVariables.Add("configs", configs);
}
}
}
// Only throw an InvalidPluginExecutionException. Please Refer https://go.microsoft.com/fwlink/?linkid=2153829.
catch (Exception ex)
{
tracingService?.Trace("An error occurred executing Plugin MergePoc.Plugins.CancelMergeForChilds_PreOperation : {0}", ex.ToString());
throw new InvalidPluginExecutionException("An error occurred executing Plugin MergePoc.Plugins.CancelMergeForChilds_PreOperation .", ex);
}
}
private EntityCollection getConfigs(IOrganizationService currentUserService, string MasterLogicalName)
{
var query_uma_parententity = MasterLogicalName;
var query = new QueryExpression("uma_mergecascadeconfiguration");
query.ColumnSet.AllColumns = true;
query.Criteria.AddCondition("uma_parententity", ConditionOperator.Equal, query_uma_parententity);
return currentUserService.RetrieveMultiple(query);
}
}
}

Post-Operation plugin:

using System;
using System.ServiceModel;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Query;
namespace MergePoc.Plugins
{
/// <summary>
/// CancelMergeForChilds_PostOperation Plugin.
/// </summary>
public class CancelMergeForChilds_PostOperation: PluginBase
{
/// <summary>
/// Initializes a new instance of the <see cref="CancelMergeForChilds_PostOperation"/> class.
/// </summary>
/// <param name="unsecure">Contains public (unsecured) configuration information.</param>
/// <param name="secure">Contains non-public (secured) configuration information.
/// When using Microsoft Dynamics 365 for Outlook with Offline Access,
/// the secure string is not passed to a plug-in that executes while the client is offline.</param>
public CancelMergeForChilds_PostOperation(string unsecure, string secure)
: base(typeof(CancelMergeForChilds_PostOperation))
{
// TODO: Implement your custom configuration handling.
}
/// <summary>
/// Main entry point for he business logic that the plug-in is to execute.
/// </summary>
/// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the
/// <see cref="IPluginExecutionContext"/>,
/// <see cref="IOrganizationService"/>
/// and <see cref="ITracingService"/>
/// </param>
/// <remarks>
/// For improved performance, Microsoft Dynamics 365 caches plug-in instances.
/// The plug-in's Execute method should be written to be stateless as the constructor
/// is not called for every invocation of the plug-in. Also, multiple system threads
/// could execute the plug-in at the same time. All per invocation state information
/// is stored in the context. This means that you should not use global variables in plug-ins.
/// </remarks>
protected override void ExecuteCdsPlugin(ILocalPluginContext localContext)
{
if (localContext == null)
{
throw new InvalidPluginExecutionException(nameof(localContext));
}
// Obtain the tracing service
ITracingService tracingService = localContext.TracingService;
try
{
// Obtain the execution context from the service provider.
IPluginExecutionContext context = (IPluginExecutionContext)localContext.PluginExecutionContext;
// Obtain the organization service reference for web service calls.
IOrganizationService currentUserService = localContext.CurrentUserService;
if (context.SharedVariables.Contains("tmp"))
{
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is EntityReference)
{
EntityReference master = (EntityReference)context.InputParameters["Target"];
EntityReference sub = new EntityReference(master.LogicalName, (Guid)context.InputParameters["SubordinateId"]);
EntityCollection configs = getConfigs(currentUserService, master.LogicalName);
if (configs.Entities.Count > 0)
{
Entity tmp = (Entity)context.SharedVariables["tmp"];
foreach (var config in configs.Entities)
{
var childLogicalName = config.GetAttributeValue<string>("uma_childentity");
var relationshipLogicalName = config.GetAttributeValue<string>("uma_relationship");
RetrieveRelationshipRequest retrieveRelationShipRequest = new RetrieveRelationshipRequest { Name = relationshipLogicalName };
RetrieveRelationshipResponse retrieveRelationShipResponse = (RetrieveRelationshipResponse)currentUserService.Execute(retrieveRelationShipRequest);
OneToManyRelationshipMetadata meta = (OneToManyRelationshipMetadata)retrieveRelationShipResponse.RelationshipMetadata;
var from = meta.ReferencedAttribute;
var to = meta.ReferencingAttribute;
var query_parentid = tmp.Id;
var query = new QueryExpression(meta.ReferencingEntity);
query.ColumnSet = new ColumnSet(to);
query.Criteria.AddCondition(to, ConditionOperator.Equal, query_parentid);
EntityCollection childs = currentUserService.RetrieveMultiple(query);
foreach (var child in childs.Entities)
{
child[to] = new EntityReference(tmp.LogicalName, sub.Id);
currentUserService.Update(child);
}
}
currentUserService.Delete(tmp.LogicalName, tmp.Id);
}
}
}
}
// Only throw an InvalidPluginExecutionException. Please Refer https://go.microsoft.com/fwlink/?linkid=2153829.
catch (Exception ex)
{
tracingService?.Trace("An error occurred executing Plugin MergePoc.Plugins.CancelMergeForChilds_PostOperation : {0}", ex.ToString());
throw new InvalidPluginExecutionException("An error occurred executing Plugin MergePoc.Plugins.CancelMergeForChilds_PostOperation .", ex);
}
}
private EntityCollection getConfigs(IOrganizationService currentUserService, string MasterLogicalName)
{
var query_uma_parententity = MasterLogicalName;
var query = new QueryExpression("uma_mergecascadeconfiguration");
query.ColumnSet.AllColumns = true;
query.Criteria.AddCondition("uma_parententity", ConditionOperator.Equal, query_uma_parententity);
return currentUserService.RetrieveMultiple(query);
}
}
}

Hope it helps …

3 thoughts on “Dynamics 365 CRM [Dataverse] – How to cancel the merge cascade for a given relationship ?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s