Automatically Publish Duplicate Detection Rules in CRM 2011

Roshan Mehta, 01 May 2013

When installing a managed or unmanaged solution for Microsoft Dynamics CRM 2011, extra care must be taken to ensure that all components of the system work as expected. Duplicate Detection rules are not solution components, but if any entity metadata is modified during a solution import, all Duplicate Detection Rules associated with the entity are automatically unpublished. These unpublished rules can often be overlooked and can cause problems for the customer, so what can we do to make sure that the rules are published?

 Automatically Publish Duplicate Detection Rules in CRM 2011

The obvious answer is to add a step to your deployment process to manually publish Duplicate Detection Rules. An even better solution is to automatically publish these rules when a user clicks on Publish All Customizations. Thankfully, we can do this with a simple plug-in.

private void PublishRules()
{
    // retrieve all duplicate detection rules 
    List<Entity> rules = GetDuplicateDetectionRules();

    rules.ForEach(r =>
    {
        _sdk.Execute(new PublishDuplicateRuleRequest 
        {
            DuplicateRuleId = r.Id
        });
    });
}

private List<Entity> GetDuplicateDetectionRules()
{
    QueryExpression query = new QueryExpression { EntityName = "duplicaterule" };
    query.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0);   // inactive 
    query.Criteria.AddCondition("statuscode", ConditionOperator.Equal, 0);  // unpublished 

   
EntityCollection results = _sdk.RetrieveMultiple(query);
    return results.Entities.ToList();
}

The plugin is registered on the Publish All message and simply retrieves all unpublished Duplicate Detection Rules and executes a PublishDuplicateRuleRequest. After we click on Publish All Customizations, we can see that the status of the Duplicate Detection Rules changes to “Publishing”. The process to publish Duplicate Detection Rules can take a long time and depends on the number of rules to publish, as well as the number of active records in the system corresponding to each rule.

 Automatically Publish Duplicate Detection Rules in CRM 2011

Enjoy!