Tuesday, 20 July 2021

Custom Duplicate detection in Dynamics CRM - Plugin

Recently I had a requirement to create Duplicate detection rule using c# (Plugin) in Account Entity, to avoid redundancy.

You can try like bellow method

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//CRM SDK Namespace
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Crm.Sdk.Messages;
 
namespace Sample
{
    public class Duplicate_Detection : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = (IOrganizationService)serviceFactory.CreateOrganizationService(context.UserId);
            ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
 
            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                Entity entity = (Entity)context.InputParameters["Target"];
                var Name = entity.GetAttributeValue<string>("name");
 
                #region  Retrieve All Account Record
 
                QueryExpression Account = new QueryExpression { EntityName = entity.LogicalName, ColumnSet = new ColumnSet("name") };
                Account.Criteria.AddCondition("name", ConditionOperator.Equal, Name);
               Account.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0);
 
               EntityCollection RetrieveAccount = service.RetrieveMultiple(Account);
 
                //If the retrieved Account Count Greater Than 1 , following Error Message Throw
 
               if (RetrieveAccount.Entities.Count > 1)
                {
                    throw new InvalidPluginExecutionException("Following Record with Same Name Exists");
 
                }
               else if (RetrieveAccount.Entities.Count == 0)
                {
                    return;
                }
                #endregion
            }
        }
    }
}
  • Register your plugin Message = Create
  • Primary Entity = account
  • Post Operation

No comments:

Post a Comment

Power Apps Drag & Drop Kanban code sample

  Introduction: The Kanban Board App Developers at a software company use the Kanban board to show their progress on development tasks and b...