I have registered a Plugin onCreate of account. My requirement is to Check Duplicates on User Records if Record already exists in Admin Records.
Example : User Create account with name="Mark". If Admin Records already have Account with name "Mark", It must throw an error to User, else Save the Record
Now, I am getting An unexpected error occurred from ISV code. Error on Save Form
Here Is the code I used
using System.ServiceModel;
using Microsoft.Crm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Client;
using System.ServiceModel.Description;
using System.Collections.Generic;
{
public class DuplicationCheck : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
try
{
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(null);
IOrganizationService serviceUser = serviceFactory.CreateOrganizationService(context.UserId);
if (context.InputParameters.Contains("Target") &&
context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parameters.
Entity entity = (Entity)context.InputParameters["Target"];
QueryExpression query = new QueryExpression();
query.EntityName = "account";
ColumnSet col = new ColumnSet("name");
query.ColumnSet = col;
//collection is of Admin Records
EntityCollection collection = service.RetrieveMultiple(query);
//collection of User Records
EntityCollection collectionUser = serviceUser.RetrieveMultiple(query);
string str;
string str1;
//string booleanField;
foreach (Entity e in collectionUser.Entities)
{
str = e.Attributes["name"].ToString();
foreach (Entity e1 in collection.Entities)
{
str1 = e1.Attributes["name"].ToString();
{
Console.WriteLine("Sorry Equal Record Found");
throw new InvalidPluginExecutionException("It seems the record of this Name already Exists!!");
}
}
}
}
catch (InvalidPluginExecutionException e)
{
// catch exception
throw new InvalidPluginExecutionException("An error has occurred: " + e.Message);
}
}
}