Today we will learn how to restrict users from entering duplicate value in MS Dynamics CRM.
Let’s take as an example of Contact entity where we need to restrict users from entering duplicate email address which is already present in CRM while creating or updating a contact record.
I know there would a thought in your mind why don’t we use Duplicate Detection rule instead of plugin. So the answer to this question is duplicate detection rule will give user a warning message about the presence of duplicate record but still user will have the ability to ignore the warning message and save the record. Therefore, plugin is required for restricting users from entering duplicate records.
Note*: Below are the different techniques using which we can retrieve records. In this plugin we will be using Query Expression.
- Fetch XML
- Using Retrieve
- Query Expression
- Query By Attribute
- LINQ
using System;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
namespace HelloPlugin
{
public class DuplicateCheck: IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
// Get a reference to the Organization service.
IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = factory.CreateOrganizationService(context.UserId);
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
//Obtain the target entity from the input parameter
Entity contact = (Entity)context.InputParameters["Target"];
try
{
//Implement Plugin Business Logic here
string email = string.Empty; //Variable declared to check whether emailaddress field is empty or not.
if (contact.Attributes.Contains("emailaddress1"))
{
email = contact.Attributes["emailaddress1"].ToString();
QueryExpression query = new QueryExpression("contact");
query.ColumnSet = new ColumnSet(new string[] { "emailaddress1" });
query.Criteria.AddCondition("emailaddress1", ConditionOperator.Equal, email);
EntityCollection collection = service.RetrieveMultiple(query);
if (collection.Entities.Count > 0) //Check if any record is present with duplicate email address
{
throw new InvalidPluginExecutionException("Contact with email already exist");
}
}
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(ex.Message);
}
}
}
}
}
Points to Remember for registering the plugin. Add two steps one for create contact another for update contact.
- Message = Create and Update
- Primary Entity = contact
- Pipeline Event = PreValidation
Hope this helps!!
