Hi ,

Recently I had a requirement to create Duplicate detection rule using c# (Plugin) in Account Entity, to avoid redundancy.

You can try like bellow method

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//CRM SDK Namespace
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Crm.Sdk.Messages;

namespace Sample
{
    public class Duplicate_Detection : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = (IOrganizationService)serviceFactory.CreateOrganizationService(context.UserId);
            ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                Entity entity = (Entity)context.InputParameters["Target"];
                var Name = entity.GetAttributeValue<string>("name");

                #region  Retrieve All Account Record

                QueryExpression Account = new QueryExpression { EntityName = entity.LogicalName, ColumnSet = new ColumnSet("name") };
                Account.Criteria.AddCondition("name", ConditionOperator.Equal, Name);
               Account.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0);

               EntityCollection RetrieveAccount = service.RetrieveMultiple(Account);

                //If the retrieved Account Count Greater Than 1 , following Error Message Throw

               if (RetrieveAccount.Entities.Count > 1)
                {
                    throw new InvalidPluginExecutionException("Following Record with Same Name Exists");

                }
               else if (RetrieveAccount.Entities.Count == 0)
                {
                    return;
                }
                #endregion
            }
        }
    }
}
  • Register your plugin Message = Create
  • Primary Entity = account
  • Post Operation

Hope This Help You . . .

Advertisements

3 thoughts on “Duplicate Detection Plugin Crm 2011

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s