Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics 365 | Integration, Dataverse...
Answered

Plugin Validation to work on Data Import as well

Posted on by Microsoft Employee

Hi there,

I have a business logic to validate whether any contact available with same email address as in lead record. If yes, pop up a Business Process Error that there is a contact available with same email address. If not, I can let the lead get created in the system. 

I'm able to do the validation for existing contact on creation of lead record from lead entity but is not letting me to create a new lead record when there is no matching found in contact. 

I've registered the plugin on Post Operation of lead entity with the below code.

Also, I would need to do the same validation while data import.

 public void Execute(IServiceProvider serviceProvider)
        {
            // Get Plugin Execution Context
            IPluginExecutionContext executionContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            // Get a reference to the Organization service.
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            //Get Currently User ID
            IOrganizationService service = factory.CreateOrganizationService(executionContext.UserId);
            //Extract the tracing service for use in debugging sandboxed plug-ins.
            ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
           // try
            //{
                Entity lead = (Entity)executionContext.InputParameters["Target"];
                LeadCreation objLogic = new LeadCreation();
                bool isDuplicateContactPresent = isDuplicateContactPresent = objLogic.IsDuplicateContactPresent(serviceProvider, tracingService, service, executionContext);
                if (isDuplicateContactPresent)
                {
                 
                    throw new InvalidPluginExecutionException("There is already a contact available with same email address");
                }
                else
                {
                  Entity leadRecord = new Entity("lead");
                  service.Create(leadRecord);
                }
        }
    }


        /// 
        /// To Create Contact when Lead gets created from D365
        /// This class has one method
        /// 
        public class LeadCreation
        {
        /// 
        /// To Check If there Duplicate Email ID in Contact
        /// PluginMessage.Create()
        /// 
            string leadEmailId;
            public bool IsDuplicateContactPresent(IServiceProvider serviceProvider, ITracingService tracingService, IOrganizationService service, IPluginExecutionContext executionContext)
            {
            try
            {
                Entity entity = (Entity)executionContext.InputParameters[SMO_constants_plugin.EntityTargetName];
                if (entity.Contains(SMO_constants_plugin.leadEmailAddress))
                {
                    leadEmailId = entity.GetAttributeValue(SMO_constants_plugin.leadEmailAddress);
                }

                if (entity.Contains(SMO_constants_plugin.leadEmailAddress))
                {
                    QueryExpression Contact = new QueryExpression { EntityName = SMO_constants_plugin.contactEntityName, ColumnSet = new ColumnSet(SMO_constants_plugin.contactEmailAddress) };
                    Contact.Criteria.AddCondition(SMO_constants_plugin.contactEmailAddress, ConditionOperator.Equal, leadEmailId);
                    EntityCollection RetrieveContact = service.RetrieveMultiple(Contact);
                    if (RetrieveContact.Entities.Count > 0)
                    {
                        return true;

                    }
                    else
                    {

                        return false;
                    }

                }
            
            }
            catch (InvalidOperationException ex)
            {
                tracingService.Trace("IsDuplicateContactPresent", ex.Message);

            }
            return true;
            }

Can anyone please help me  how this can be done here. 

Thank you,

Leo

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Plugin Validation to work on Data Import as well

    Thanks alot for this work around. 

    I have checked depth in the code where this validation works and captures the business process error in backend for the failed records while importing data using OOTB import as well.

    Please note that I didn't check without depth condition.

    Best Regards,

    Leo

  • Suggested answer
    meelamri Profile Picture
    meelamri 13,204 User Group Leader on at
    RE: Plugin Validation to work on Data Import as well

    Hello Leo,

    No need to check the depth. The plugin will be executed even for data import. Please don't forget to verify my above answer if it was helpful. Thank you !

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Plugin Validation to work on Data Import as well

    Hi Mehdi,

    Thank you very much for this workaround which is working for me. Also, I'm trying to make the same plugin validation work on OOTB data import as well. Do I need to check depth of the plugin for this?

    If (executioncontext.depth=1 || executioncontext.depth=2)

    {

        Incorporate the same code here. 

    }

    Best Regards,

    Leo

  • Verified answer
    meelamri Profile Picture
    meelamri 13,204 User Group Leader on at
    RE: Plugin Validation to work on Data Import as well

    Hello,

    First, you need to register your plugin on Pre-Validation. Then you need to remove the service.create(leardRecord), the system will create the lead in the main operation... You will get something like:

     

    public void Execute(IServiceProvider serviceProvider)
            {
                // Get Plugin Execution Context
                IPluginExecutionContext executionContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                // Get a reference to the Organization service.
                IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                //Get Currently User ID
                IOrganizationService service = factory.CreateOrganizationService(executionContext.UserId);
                //Extract the tracing service for use in debugging sandboxed plug-ins.
                ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
               // try
                //{
                    Entity lead = (Entity)executionContext.InputParameters["Target"];
                    LeadCreation objLogic = new LeadCreation();
                    bool isDuplicateContactPresent = isDuplicateContactPresent = objLogic.IsDuplicateContactPresent(serviceProvider, tracingService, service, executionContext);
                    if (isDuplicateContactPresent)
                    {
                     
                        throw new InvalidPluginExecutionException("There is already a contact available with same email address");
                    }
            }
        }

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Plugin Validation to work on Data Import as well

    Hi Mehdi,

    Thank you for your reply! Here is the error message,

    Exception Message: Lead With Id = c8ba376e-5107-4828-b870-1ced513a7ac5 Does Not Exist

    ErrorCode: -2147220969
    HexErrorCode: 0x80040217

    ErrorDetails:
    ApiExceptionSourceKey: Plugin/Microsoft.Crm.ObjectModel.BpfBusinessEntityService
    ApiStepKey: 1c196a9e-4f96-eb11-b1ac-000d3adcf323
    ApiDepthKey: 1
    ApiActivityIdKey: 12d28e91-7d39-4d02-b934-655505516ce4
    ApiPluginSolutionNameKey: System
    ApiStepSolutionNameKey: System
    ApiExceptionCategory: ClientError
    ApiExceptionMesageName: ObjectDoesNotExist
    ApiExceptionHttpStatusCode: 404

    HelpLink: go.microsoft.com/.../

    Activity Id: 6882b97b-b317-4e87-b97b-1b0e670ab670

    Best Regards,

    Leo

  • meelamri Profile Picture
    meelamri 13,204 User Group Leader on at
    RE: Plugin Validation to work on Data Import as well

    Hello,

    What is the error message  when there is no matching found in contact ?

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,280 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,235 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Product updates

Dynamics 365 release plans