Compartilhar via


BulkDetectDuplicatesRequest Class

Definition

Contains the data that is needed to submit an asynchronous system job that detects and logs multiple duplicate records.

public ref class BulkDetectDuplicatesRequest sealed : Microsoft::Xrm::Sdk::OrganizationRequest
[System.Runtime.Serialization.DataContract(Namespace="http://schemas.microsoft.com/crm/2011/Contracts")]
public sealed class BulkDetectDuplicatesRequest : Microsoft.Xrm.Sdk.OrganizationRequest
[<System.Runtime.Serialization.DataContract(Namespace="http://schemas.microsoft.com/crm/2011/Contracts")>]
type BulkDetectDuplicatesRequest = class
    inherit OrganizationRequest
Public NotInheritable Class BulkDetectDuplicatesRequest
Inherits OrganizationRequest
Inheritance
BulkDetectDuplicatesRequest
Attributes

Examples

The following example shows how to use this message. For this sample to work correctly, you must be connected to the server to get an IOrganizationService interface instance.

/// <summary>
/// Detects duplicate account records
/// </summary>
/// <param name="service">The authenticated IOrganizationService instance</param>
static void BulkDetectDuplicatesExample(IOrganizationService service )
{
      // Verify there are published duplicate rules
      // for accounts matching other accounts
      QueryExpression duplicateRuleQuery = new("duplicaterule")
      {
         ColumnSet = new ColumnSet("name")
      };
      duplicateRuleQuery.Criteria.AddCondition(
         attributeName: "baseentityname", 
         conditionOperator: ConditionOperator.Equal, 
         values: "account");
      duplicateRuleQuery.Criteria.AddCondition(
         attributeName: "matchingentityname", 
         conditionOperator: ConditionOperator.Equal, 
         values: "account");
      duplicateRuleQuery.Criteria.AddCondition(
         attributeName: "statuscode", 
         conditionOperator: ConditionOperator.Equal, 
         values: 2); //Published

      // Retrieve the duplicate rules
      EntityCollection duplicateRules = service.RetrieveMultiple(duplicateRuleQuery);

      if (duplicateRules.Entities.Count == 0)
      {
         Console.WriteLine("There are no published duplicate rules for accounts matching other accounts");
         return;        
      }

      // Compose the request
      BulkDetectDuplicatesRequest request = new()
      {
         JobName = "Detect Duplicate Accounts",
         Query = new QueryExpression()
         {
            EntityName = "account"
         },
         RecurrencePattern = string.Empty,
         RecurrenceStartTime = DateTime.Now,
         ToRecipients = Array.Empty<Guid>(),
         CCRecipients = Array.Empty<Guid>()
      };

      // Send the request
      var response = (BulkDetectDuplicatesResponse)service.Execute(request);

      // Monitor the asynchronous results
      int testLimit = 1000; // ~ 16 minutes
      int count = 0;
      string status = "Error";


      // Poll the system job every second to determine if it has finished.
      while (count < testLimit)
      {
         Task.Delay(1000).Wait(); // Wait a second

         //Retrieve the system job
         Entity job = service.Retrieve(
            "asyncoperation",
            response.JobId,
            new ColumnSet("statecode", "statuscode"));

         int stateCode = job.GetAttributeValue<OptionSetValue>("statecode").Value;
         int statuscode = job.GetAttributeValue<OptionSetValue>("statuscode").Value;

         // The system job may be created in a Suspended state.
         // The following will Resume the system job.

         // When the system job is suspended
         if (stateCode == 1)
         {
            Entity systemJob = new("asyncoperation")
            {
                  Id = response.JobId,
                  Attributes = {
                     { "statecode", new OptionSetValue(0)}, // Ready
                     { "statuscode", new OptionSetValue(0)} // Waiting For Resources
                  }
            };
            // Resume the system job
            service.Update(systemJob);
         }

         // Capture the status when the system job is completed
         if (stateCode == 3)
         {
            status = statuscode switch
            {
                  30 => "Success",
                  31 => "Failed",
                  32 => "Cancelled",
                  _ => "Error",
            };
            break;
         }

         count++;
      }

      Console.WriteLine($"Duplicate Detection system job status: {status}.\n");
      if (status != "Success")
      {
         Console.WriteLine("There was a problem executing the Duplicate Detection system job.");
         return;
      }
      else {
         //Retrieve information about the results
         QueryExpression duplicateRecordQuery = new("duplicaterecord")
         {
            ColumnSet = new ColumnSet("baserecordid", "duplicateruleid")
            // duplicaterecordid never has a value
         };
         duplicateRecordQuery.Criteria.AddCondition(
            attributeName: "asyncoperationid",
            conditionOperator: ConditionOperator.Equal,
            values: response.JobId);

         EntityCollection duplicateRecords = service.RetrieveMultiple(duplicateRecordQuery);

         if (duplicateRecords.Entities.Count == 0)
         {
            Console.WriteLine("No duplicate records detected.");
            return;
         }

         Console.WriteLine("Duplicate accounts:\n");
         foreach (Entity entity in duplicateRecords.Entities)
         {
            Guid baserecordid = entity.GetAttributeValue<EntityReference>("baserecordid").Id;
            Guid duplicateruleid = entity.GetAttributeValue<EntityReference>("duplicateruleid").Id;

            Entity baseRecord = service.Retrieve("account", baserecordid, new ColumnSet("name"));
            string baseRecordName = baseRecord.GetAttributeValue<string>("name");
            // Use the duplicate rules retrieved earlier to lookup the rule name
            string duplicateruleName = (string)duplicateRules.Entities.SingleOrDefault(x => x.Id == duplicateruleid)["name"];

            Console.WriteLine($"\tAccount: '{baseRecordName}' ({baserecordid})");
            Console.WriteLine($"\tDuplicateRule: '{duplicateruleName}'.");
            Console.WriteLine();
         }
      }
}

Output:

Duplicate Detection system job status: Success.

Duplicate accounts:

         Account: 'Contoso, Ltd' (2ada33e7-ef8b-ee11-8179-000d3a9933c9)
         DuplicateRule: 'Accounts with the same website'.

         Account: 'Contoso, Ltd' (567fa9fb-f38b-ee11-8179-000d3a993550)
         DuplicateRule: 'Accounts with the same website'.

For a complete sample, see Sample: Detect multiple duplicate records

Remarks

Learn to detect duplicate data using code Detect duplicate data using the SDK for .NET

For the Web API use the BulkDetectDuplicates action.

Usage

Pass an instance of this class to the Execute(OrganizationRequest) method, which returns an instance of the BulkDetectDuplicatesResponse class.

Privileges and Access Rights

To perform this action, the caller must have read privileges and access rights on the records that are specified in the request class.

Notes for Callers

The asynchronous system job detects multiple duplicate records and logs them as duplicate records by using the DuplicateRecord table. Before you use this message, set the EntityMetadata.IsDuplicateDetectionEnabled property for an table to true and publish all duplicate rules (duplicate detection rules) for a table.

Constructors

BulkDetectDuplicatesRequest()

Initializes a new instance of the BulkDetectDuplicatesRequest class.

Properties

CCRecipients

Gets or sets an array of IDs for the system users (users) who are listed in the Cc box of the email notification.

ExtensionData

Gets or sets the structure that contains extra data. Optional.

(Inherited from OrganizationRequest)
Item[String]

Gets or sets the indexer for the Parameters collection.

(Inherited from OrganizationRequest)
JobName

Gets or sets the name of the asynchronous system job that detects and logs multiple duplicate records. Required.

Parameters

Gets or sets the collection of parameters for the request. Required, but is supplied by derived classes.

(Inherited from OrganizationRequest)
Query

Gets or sets the query criteria for detecting multiple duplicate records. Required.

RecurrencePattern

Gets or sets the recurrence pattern for the asynchronous system job that detects multiple duplicate records. Optional.

RecurrenceStartTime

Gets or sets the start date and time of an asynchronous system job that detects and logs multiple duplicate records. Optional.

RequestId

Gets or sets the ID of the request. Optional.

(Inherited from OrganizationRequest)
RequestName

Gets or sets the name of the request. Required, but is supplied by derived classes.

(Inherited from OrganizationRequest)
SendEmailNotification

Gets or sets a value that indicates whether an email notification is sent after the asynchronous system job that detects multiple duplicate records finishes running. Required.

TemplateId

Sets the ID of the template (email template) that is used for the email notification.

ToRecipients

Gets or sets an array of IDs for the system users (users) who are listed in the To box (recipients) of the email notification.

Applies to

See also