web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics 365 | Integration, Dataverse...
Answered

Plugin : Cannot create a duplicate detection rule in a plugin

(0) ShareShare
ReportReport
Posted on by 35

Hi i am new to dynamics 365, i am trying to create a duplicate detection plugin using the dynamics 365 duplicate detection sample. can somebody helps ?

using System;
using System.ServiceModel;
using System.ServiceModel.Description;

// These namespaces are found in the Microsoft.Xrm.Sdk.dll assembly
// located in the SDK\bin folder of the SDK download.
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Messages;

using Microsoft.Crm.Sdk.Messages;

namespace TestPlug
{
    /// 
    /// Demonstrates how to do basic entity operations like create, and
    /// update, using Duplicate Detection attribute.
    /// 
    /// At run-time, you will be given the option to delete all the
    /// database records created by this program.
    public class InvokeDuplicateDetectionForCreateAndUpdate : IPlugin
    {

        private Guid _accountId;
        private Guid _ruleId;
        private Guid _dupAccountId;
        private OrganizationServiceProxy _serviceProxy;
        private IOrganizationService _service;
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            // Obtain the execution context from the service provider.  
            IPluginExecutionContext context = (IPluginExecutionContext)
                serviceProvider.GetService(typeof(IPluginExecutionContext));

            // Obtain the organization service reference which you will need for  
            IOrganizationServiceFactory serviceFactory =
                (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);



            // 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"];

                try
                {
                CreateRequiredRecords();
                    // Create and account record with the named Proseware, Inc. and already existing Account Number.

                    // Instantiate an account object.

                    Entity account = new Entity("account");

                    // Set the required attributes. For account, only the name is required. 

                    account["name"] = "Proseware, Inc.";

                    //Set any other attribute values.

                    account["accountnumber"] = "ACC005";
                    // Create operation by suppressing duplicate detection
                    CreateRequest reqCreate = new CreateRequest();
                    reqCreate.Target = account;
                    reqCreate.Parameters.Add("SuppressDuplicateDetection", true); // Change to false to activate the duplicate detection.
                    CreateResponse createResponse = (CreateResponse)_service.Execute(reqCreate);
                    _dupAccountId = createResponse.id;
                    Console.Write("Account: {0} {1} created with SuppressDuplicateDetection to true, ",
                        account["name"], account["accountnumber"]);
                   // Retrieve the account containing with its few attributes.
                    ColumnSet cols = new ColumnSet(
                        new String[] { "name", "accountnumber" });

                    var retrievedAccount =service.Retrieve("account", _dupAccountId, cols);
                    Console.Write("retrieved, ");
                    // Update the existing account with new account number.
                    retrievedAccount["accountnumber"] = "ACC006";

                    // Update operation – update record, if a duplicate is not found.
                    UpdateRequest reqUpdate = new UpdateRequest();
                    reqUpdate.Target = retrievedAccount;
                    reqUpdate["SuppressDuplicateDetection"] = false; // Duplicate detection is activated.

                    // Update the account record.
                    UpdateResponse updateResponse = (UpdateResponse)_service.Execute(reqUpdate);
                    Console.WriteLine("and updated.");

                    DeleteRequiredRecords(promptforDelete);
                }

                catch (FaultException ex)
                {
                    throw new InvalidPluginExecutionException("An error occurred in MyPlug-in.", ex);
                }

                catch (Exception ex)
                {
                    tracingService.Trace("MyPlugin: {0}", ex.ToString());
                    throw;
                }
                /// 
                /// Creates any entity records that this sample requires.
                /// 
                public void CreateRequiredRecords()
                {
                    // Create an account record named Fourth Coffee.

                    Entity account = new Entity("account");

                    // Set the required attributes. For account, only the name is required. 

                    account["name"] = "Fourth Coffee";

                    //Set any other attribute values.

                    account["accountnumber"] = "ACC005";

                    _accountId = service.Create(account);
                    Console.Write("Account {0} {1} created, ", account["name"], account["accountnumber"]);

                    // Create a duplicate detection rule
                    DuplicateRule accountDuplicateRule = new DuplicateRule
                    {
                        Name = "DuplicateRule: Accounts with the same Account Number",
                        BaseEntityName = "account",
                        MatchingEntityName = "account"
                    };
                    _ruleId = service.Create(accountDuplicateRule);

                    //Create a duplicate detection rule condition
                    DuplicateRuleCondition accountDupCondition = new DuplicateRuleCondition
                    {
                       BaseAttributeName = "accountnumber",
                       MatchingAttributeName = "accountnumber",
                       OperatorCode = new OptionSetValue(0), // Exact Match.
                       RegardingObjectId = new EntityReference(DuplicateRule.EntityLogicalName, _ruleId)
                    };
                    Guid conditionId = service.Create(accountDupCondition);

                    Console.Write("'{0}' created, ", accountDuplicateRule.Name);

                    // Execute the publish request.
                }
                /// Deletes any entity records that were created for this sample.
                public void DeleteRequiredRecords(bool prompt)
                {
                }
            }
        }
    }
}
7563.Capture11.PNG

I have the same question (0)
  • Verified answer
    Pankaj Gogoi Profile Picture
    3,177 on at

    Hi Jamal,

    You have to generate those classes using early bound.

    docs.microsoft.com/.../create-early-bound-entity-classes-code-generation-tool

    www.xrmtoolbox.com/.../

    Best Regards

    PG

  • Verified answer
    sdfasdf Profile Picture
    842 on at

    The sample code you shared uses early-bound classes. In the context of custom plug-in, might prefer not using early-bound classes.

  • Jamal JEK Profile Picture
    35 on at

    Thank you guys,

    Nathan Benelli what are the preferred ones ?

  • Jamal JEK Profile Picture
    35 on at

    Thank you guys,

    Nathan Benelli what are the preferred ones ?

  • Verified answer
    Pankaj Gogoi Profile Picture
    3,177 on at

    Hi Jamal,

    Please check out this link.

    docs.microsoft.com/.../detect-duplicate-data-for-developers

    Best Regards

    PG

  • Jamal JEK Profile Picture
    35 on at

    Hi again Pankaj Gogoi, I am stuck with this error. Can anyone assist me fix this? I would appreciate any form of assessment.

    using System;
    using System.ServiceModel;
    using System.ServiceModel.Description;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Query;
    using Microsoft.Xrm.Sdk.Messages;
    using Microsoft.Crm.Sdk.Messages;
    
    namespace DuplicateDetectionPlugin
    {
     public class InvokeDuplicateDetectionForCreateAndUpdate : IPlugin
        {
            private Guid _accountId;
            private Guid _ruleId;
            private Guid _dupAccountId;
            public void Execute(IServiceProvider serviceProvider)
            {
                ITracingService tracingService =
                    (ITracingService)serviceProvider.GetService(typeof(ITracingService));
    
                // Obtain the execution context from the service provider.  
                IPluginExecutionContext context = (IPluginExecutionContext)
                    serviceProvider.GetService(typeof(IPluginExecutionContext));
    
                // Obtain the organization service reference which you will need for  
                IOrganizationServiceFactory serviceFactory =
                    (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
                    try
                    {
                    CreateRequiredRecords();
                        // Create and account record with the named Proseware, Inc. and already existing Account Number.
                        Account account = new Account
                        {
                            Name = "Proseware, Inc.",
                            AccountNumber = "ACC005"
                        };
    
                        // Create operation by suppressing duplicate detection
                        CreateRequest reqCreate = new CreateRequest();
                        reqCreate.Target = account;
                        reqCreate.Parameters.Add("SuppressDuplicateDetection", true); // Change to false to activate the duplicate detection.
                        CreateResponse createResponse = (CreateResponse)service.Execute(reqCreate);
                        _dupAccountId = createResponse.id;
    
                        // Retrieve the account containing with its few attributes.
                        ColumnSet cols = new ColumnSet(
                            new String[] { "name", "accountnumber" });
    
                        Account retrievedAccount = (Account)service.Retrieve("account", _dupAccountId, cols);
    
                        // Update the existing account with new account number.
                        retrievedAccount.AccountNumber = "ACC006";
    
                        // Update operation – update record, if a duplicate is not found.
                        UpdateRequest reqUpdate = new UpdateRequest();
                        reqUpdate.Target = retrievedAccount;
                        reqUpdate["SuppressDuplicateDetection"] = false; // Duplicate detection is activated.
    
                        // Update the account record.
                        UpdateResponse updateResponse = (UpdateResponse)service.Execute(reqUpdate);
    
                        DeleteRequiredRecords();
                    }
    
                    catch (FaultException ex)
                    {
                        throw new InvalidPluginExecutionException("An error occurred in MyPlug-in.", ex);
                    }
    
                    catch (Exception ex)
                    {
                        tracingService.Trace("MyPlugin: {0}", ex.ToString());
                        throw;
                    }
                    /// 
                    /// Creates any entity records that this sample requires.
                    void CreateRequiredRecords()
                    {
                        // Create an account record named Fourth Coffee.
                        Account account = new Account
                        {
                            Name = "Fourth Coffee",
                            AccountNumber = "ACC005"
                        };
                        _accountId =service.Create(account);
    
                        // Create a duplicate detection rule
                        DuplicateRule accountDuplicateRule = new DuplicateRule
                        {
                            Name = "DuplicateRule: Accounts with the same Account Number",
                            BaseEntityName = "account",
                            MatchingEntityName = "account"
                        };
                        _ruleId =service.Create(accountDuplicateRule);
    
                        DuplicateRuleCondition accountDupCondition = new DuplicateRuleCondition
                        {
                            BaseAttributeName = "accountnumber",
                            MatchingAttributeName = "accountnumber",
                            OperatorCode = new OptionSetValue(0), // Exact Match.
                            RegardingObjectId = new EntityReference(DuplicateRule.EntityLogicalName, _ruleId)
                        };
                        Guid conditionId = service.Create(accountDupCondition);
    
                        // Execute the publish request.
                        PublishDuplicateRuleResponse response =
                            (PublishDuplicateRuleResponse)service.Execute(new PublishDuplicateRuleRequest() { DuplicateRuleId = _ruleId });
    
                        // When the publishDuplicateRule request returns, the state of the rule will still be "Publishing" (StatusCode = 1).
                        // we need to wait for the publishing operation to complete, so we keep polling the state of the
                        // rule until it becomes "Published" (StatusCode = 2).
                        int i = 0;
                        DuplicateRule retrievedRule =
                            (DuplicateRule)service.Retrieve(DuplicateRule.EntityLogicalName, _ruleId, new ColumnSet(new String[] { "statuscode" }));
                        while (retrievedRule.StatusCode.Value == 1 && i < 20)
                        {
                            i  ;
                            System.Threading.Thread.Sleep(1000);
                            retrievedRule =
                                (DuplicateRule)service.Retrieve(DuplicateRule.EntityLogicalName, _ruleId, new ColumnSet(new String[] { "statuscode" }));
                        }
    
                    }
                    /// 
                    /// Deletes any entity records that were created for this sample.
                    /// delete the records created in this sample.
                    /// 
                    void DeleteRequiredRecords()
                    {
                            service.Delete(Account.EntityLogicalName, _accountId);
                            UnpublishDuplicateRuleRequest unpublishRequest = new UnpublishDuplicateRuleRequest
                            {
                                DuplicateRuleId = _ruleId
                            };
                            service.Execute(unpublishRequest);
                            service.Delete(DuplicateRule.EntityLogicalName, _ruleId);
                            service.Delete(Account.EntityLogicalName, _dupAccountId);
                    }
                }
            }
        }
    
    
    11Capture.PNG

    Error Details: at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.CreateInternal(Entity entity, InvocationContext invocationContext, CallerOriginToken callerOriginToken, WebServiceType serviceType, Boolean checkAdminMode, Dictionary`2 optionalParameters)
    at Microsoft.Crm.Extensibility.OData.CrmODataExecutionContext.CreateOrganizationResponse(Entity entity)
    at Microsoft.Crm.Extensibility.OData.CrmODataServiceDataProvider.CreateEdmEntity(CrmODataExecutionContext context, String edmEntityName, EdmEntityObject entityObject, Boolean isUpsert)
    at Microsoft.Crm.Extensibility.OData.EntityController.PostEntitySetImplementation(String& entitySetName, EdmEntityObject entityObject)
    at Microsoft.Crm.Extensibility.OData.CrmODataUtilities.<>c__DisplayClass10_0`2.<InvokeActionAndLogMetric>b__0()
    at Microsoft.PowerApps.CoreFramework.ActivityLoggerExtensions.Execute[TResult(ILogger logger, EventId eventId, ActivityType activityType, Func`1 func, IEnumerable`1 additionalCustomProperties)
    at Microsoft.Xrm.Telemetry.XrmTelemetryExtensions.Execute[TResult(ILogger logger, XrmTelemetryActivityType activityType, Func`1 func)
    at lambda_method(Closure , Object , Object[ )
    at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[ methodParameters)
    at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
    --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()
    Activity Id: 9a742c58-544c-4c93-886e-b60f3ed9f51c

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Microsoft Dynamics 365 | Integration, Dataverse, and general topics

#1
Siv Sagar Profile Picture

Siv Sagar 93 Super User 2025 Season 2

#2
#ManoVerse Profile Picture

#ManoVerse 76

#3
Martin Dráb Profile Picture

Martin Dráb 64 Most Valuable Professional

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans