Working with Salesforce Duplicate Rules

If the Salesforce org has Duplicate Rules applied to the objects that you are creating, then you can experience DUPLICATES_DETECTED Salesforce Errors.

The following code demonstrates a way to work with these errors and bypass them by setting the DuplicateRuleHeader in the Salesforce Session. It is assumed that the Salesforce org has the Standard Duplicate Rules in place:

https://help.salesforce.com/articleView?id=duplicate_rules_standard_rules.htm&type=5

The example will set up a Contact with data that will trigger a match when a Lead is created

SalesforceSession session = SessionTest.GetActiveSession(); //create a sample Contact for the Duplicate Rule to match against Contact contact = new Contact(); contact.FirstName = "John"; contact.LastName = "Doe"; contact.Email = "john@doe.com"; ContactService contactService = new ContactService(session); SaveResult saveResult = contactService.Insert(contact); //create a Lead that will trigger a match with the Contact created above Lead lead = new Lead(); lead.FirstName = "John"; lead.LastName = "Doe"; lead.Email = "john@doe.com"; lead.Company = "John Doe Ltd"; LeadService leadService = new LeadService(session); List<string> matchedContactIds = new List<string>(); try { saveResult = leadService.Insert(lead); } catch (SalesforceCreateException ex) { //Check for a Duplicates Detected error if(ex.StatusCode == StatusCode.DUPLICATES_DETECTED) { //iterate through the FailedSaveResults to drill down into record match results for (int i = 0; i < ex.FailedSaveResults.Count; i++) { SaveResult failedSaveResult = ex.FailedSaveResults[i]; for (int j = 0; j < failedSaveResult.errors.Length; j++) { Error error = failedSaveResult.errors[j]; if(error.statusCode == StatusCode.DUPLICATES_DETECTED) { DuplicateError duplicateError = (DuplicateError)failedSaveResult.errors[j]; for (int k = 0; k < duplicateError.duplicateResult.matchResults.Length; k++) { MatchResult matchResult = duplicateError.duplicateResult.matchResults[k]; if(matchResult.entityType == Contact.SFType) { matchedContactIds.Add(matchResult.matchRecords[0].record.Id); } } } } } } } //set up a potential matched Contact to use instead of the Lead Contact useThisContact = null; if(matchedContactIds.Count > 0) { //do something to decide whether to use one of the Salesforce matched Contacts useThisContact = FindMatchingContact(matchedContactIds); } //if no contact was effectively matched, then allow the Lead to be saved regardless //of the Salesforce Duplication Rules by setting the DuplicateRuleHeader if(useThisContact == null) { DuplicateRuleHeader duplicateRuleHeader = new DuplicateRuleHeader(); duplicateRuleHeader.allowSave = true; session.Binding.DuplicateRuleHeaderValue = duplicateRuleHeader; leadService.Insert(lead); } else { //a contact was matched so don't do anything return; }