I use the following code for plugin for create lead based on the condition while import records from excel.
Condition : The lead's mail id (which is come from excel sheet) I need to check whether this email id is available in contact or account.If its available in either contact or account i need to skip that record and add the remaining records.
public class Optimization : IPlugin
{
string errormessage = "";
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
if(context.Depth > 1) return;
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
Entity entity = (Entity)context.InputParameters["Target"];
if (entity.LogicalName == "lead")
{
IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = factory.CreateOrganizationService(context.UserId);
string emailaddress = entity.Attributes["emailaddress1"].ToString();
// Check the Lead's Email Address is available in Contact or Not
QueryExpression query = new QueryExpression();
query.EntityName = "contact";
query.ColumnSet = new ColumnSet("emailaddress1");
query.Criteria.AddCondition("emailaddress1", ConditionOperator.Equal, emailaddress);
EntityCollection contactresults = new EntityCollection();
contactresults = service.RetrieveMultiple(query);
// Check the Lead's Email Address is available in Account or Not
query.EntityName = "account";
query.ColumnSet = new ColumnSet("emailaddress1");
query.Criteria.AddCondition("emailaddress1", ConditionOperator.Equal, emailaddress);
EntityCollection accountresults = new EntityCollection();
accountresults = service.RetrieveMultiple(query);
if (contactresults.Entities.Count == 0 && accountresults.Entities.Count == 0)
{
Lead lead = new Lead();
lead.FirstName = entity.Attributes["firstname"].ToString();
lead.LastName = entity.Attributes["lastname"].ToString();
lead.EMailAddress1 = emailaddress;
service.Create(lead);
}
else
{
if (contactresults.Entities.Count != 0 && accountresults.Entities.Count != 0)
errormessage = "Contact and Account";
else if (contactresults.Entities.Count != 0)
errormessage = "Contact";
else if (accountresults.Entities.Count != 0)
errormessage = "Account";
throw new InvalidPluginExecutionException("The " + emailaddress + " is already exists in " +errormessage);
}
}
}
}
}
Register Plug In Steps :
I register the plugin pre-validation event.
Input File:
Problem:
In my input file i have test@test.com in first record so i need to skip that one and add it in remaining other 2 records.But my problem is all the 3 records are added in leads. But If I try to add the lead with "test@test.com" email through GUI its working and shows error."Already exists Error".
If I remove the if(context.Depth > 1) return; its shows infinite loop in error.
How can I solve this Issue ?