I am looking to design some logic inside of my create plugin for the entity 'account'.
What it does is basically check account Names and identifies account names which are duplicates on creation.
So if there is an account Name, Barclays for example, and I try to create this again I'm going to alert the user with an error message that this has been created before and prevents this record from being added.
public void Execute(IServiceProvider serviceProvider)
{
var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));
if (context.InputParameters.Contains("Target") &&
context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parmameters.
Entity entity = (Entity)context.InputParameters["Target"];
if (entity.LogicalName == "account")
{
bool x = true;
if (entity.Attributes.Contains("Name") != recordNamesinCRM)
{
}
else
{
throw new InvalidPluginExecutionException("You Cannot Have Duplicate Country Codes!.");
}
}
}
}
In the code above I am just using "recordNamesinCRM" as an example but I'm sure there is a built in function or way of comparing on create a new name with the rest in the system or a way of counting reoccurring instances.
You can use the RetrieveDuplicatesRequest as per this example here:
See http://crm-edinburgh.com/2011/08/crm-sdk-using-detect-duplicates-settings-in-code/ for an example.
Are you aware of the built-in duplicate detection?
See following links:
although the links describe the duplicate detection of Dynamics CRM 4, they are still valid for Dynamics CRM 2011
Take a look at the article Run Duplicate Detection in the Dynamics CRM 2011 SDK.
You could either use the optional parameter
SuppressDuplicateDetection
or you could use the RetrieveDuplicatesRequest, although this will only work for existing records.