PreValidate plug in example

PreValidation plug in example:

One of the most common interview question that never forgotten by any one and of course in Realtime this will rarely used.

When we want to get no of child records when we are deleting the main/parent record then we can use PreValidation stage to get the count.

 

As some one thinks at very first time, why can’t we get the count in PreOperation stage. Because this will be in the same execution and we will not get the record count and by the stage it reaches to 20(PreOperation) all the child records gets deleted as per the relationship behavior.

 

So we need to register our plug in in PreValidaton. Below is the sample example to get the count of child records when we register the plug in in Delete message.


 

if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is EntityReference)

            {

 

                // Obtain the target entity from the input parameters.

                var entityReference = (context.InputParameters["Target"] as EntityReference);

                try

                {

                    QueryExpression query = new QueryExpression("contact");

                    query.Criteria.AddCondition(new ConditionExpression("parentcustomerid", ConditionOperator.Equal, entityReference.Id));

                    query.ColumnSet = new ColumnSet("lastname", "firstname", "fullname");

                    EntityCollection contactCollection = service.RetrieveMultiple(query);

                    int count = 0;

                    if (contactCollection.Entities.Count > 0)

                    {

                        count = contactCollection.Entities.Count;

                    }

 

                    tracingService.Trace($"starting try in PreOperation Delete account");

                    // Create a task activity to follow up with the account customer in 7 days

                    Entity followup = new Entity("task");

 

                    followup["subject"] = "Creating task, using PreValidate, Delete account.Child record(contact) count:" + count;

                    followup["description"] = $"Follow up with the customer. Check if there are any new issues  that need resolution.";

                    followup["scheduledstart"] = DateTime.Now;

                    followup["scheduledend"] = DateTime.Now.AddDays(2);

                    followup["category"] = context.PrimaryEntityName;

 

                    // Create the followup activity

                    service.Create(followup);

                }

                catch (Exception ex)

                {

                  

                }

 


Comments

Popular posts from this blog

Connecting Dynamics 365 Web api using external HTML page

Get azure blob files inside Sub Directories

Interview questions on MS CRM