Plugin Pre-validation Operation to Show an Error Message as well as Log the Error

By | March 7, 2017

Introduction:

We had a business requirement, where we created a custom entity with a grid of Associated Accounts. Here, we wanted to restrict the Account while adding Accounts in the Associated View. We wanted to do this when the Account does not have the status reason ‘Approved’ by showing an error message and sending an email to the owner of the account

Issue?

As we know, to show an error message using plugin, we have to use InvalidPluginExecutionException.

However, when we use InvalidPluginExecutionException it rollbacks any additional code executed on ‘Pre-operation’ and ‘Post-operation’ irrespective of it being ‘Synchronous’ or ‘Asynchronous’.

The need over here was not just to throw an error and notify the user but also send an email/log an error in the background.

Throwing an exception in the plugin registered on “Pre-Operation” or “Post-Operation” would also prevent the additional logging of the error message that was required.

Solution:

We found an alternate way to achieve this by registering plugin on “Pre-Validation” operation.

Pre-validation operation allows processing the actions written, before throwing invalid plugin exception.

We added a new plugin step and registered it as seen in the below screenshot:

Plugin Pre-validation operation to Show an Error Message

We have also written the code mentioned below to process actions before throwing invalid plugin exception:

try{
bool isApproved = false;
                if (context.MessageName.ToLower() == "associate")
                {
                    //validate relationship
                    if (context.InputParameters.Contains("Relationship"))
                    {
                       string relationship = context.InputParameters["Relationship"].ToString();

                    }
                    //check relationship
                    if (relationship != "relationshipname")
                    {
                        return;
                    }
                    
//business logic execution

if (!isApproved)
                        {
			//send email code

			//throw error to prevent association

			throw new InvalidPluginExecutionException(" Account Status Reason needs to be Approved !!");	
                 }

                    }
                }
}

 

Conclusion: Code in ‘Pre-validation’ is executed outside the transaction and therefore any updates made to the database in this stage persists and can therefore be used for error logging mechanism that needs to be implemented.

QuickBooks Integration with Dynamics 365/CRM – Get the Best of Both Worlds with InoLink!

7 thoughts on “Plugin Pre-validation Operation to Show an Error Message as well as Log the Error

  1. viswa

    Hello Inogic,
    How can i stop the record creation from the pre-validate plugin without throwing the Invalid plugin execution Exception ?

    Thanks in advance.
    Viswa

    Reply
    1. Inogic Post author

      We are not sure about your requirement, but currently, there is no such a way to stop creating record using plugin without throwing exception.

      Either way is to write javascript On Save event of record and use preventDefault in script to restrict user from saving record.

      //code
      function My_PreventSaveFunction(eContext) {
      eContext.getEventArgs().preventDefault();
      }

      Hope this helps.

      Thanks!

      Reply
  2. Silvia

    Hello Inogic,
    It`s really usefull but can you give us more details about 1) is [“Target”] Entity or EntityReference and 2) if it is EntityReference how exactly you get the value of the status reason option set (what`s behind isApproved), can you share this piece of code? Thank you in advance!

    Reply
    1. Inogic Post author

      Thank you for your valuable feedback. The answers for your two queries are as follows:

      1) is [“Target”] Entity or EntityReference
      When we write plugin on Associate or Disassociate message we get [“Target”] as entity reference. Below is the piece of code for your reference:
      EntityReference targetEntRef = null;
      (context.InputParameters.Contains(“Target”) && context.InputParameters[“Target”] is EntityReference) {
      targetEntRef = (EntityReference)context.InputParameters[“Target”];
      }

      2) if it is EntityReference how exactly you get the value of the status reason option set (what`s behind isApproved), can you share this piece of code?

      “isApproved” is nothing but an variable which we can set in business logic. The commented “//business logic” is where you can write logic to set the “isApproved” value.

      For Status Reason option set, you need to retrieve the optionset attribute by retrieving entity of this attribute.

      To retrieve entity use below code sample:

      Entity account = _crmSvc.Retrieve(“account”, new Guid(“PassGUIDOFRecord”), new ColumnSet(“industrycode”));

      After retrieving entity, read the optionset value as below:

      int optionsetValue = (int)((OptionSetValue)account.Attributes[“industrycode”]).Value;

      Hope this helps.

      Thanks!

      Reply
  3. Para mohan

    Hello Inogic ,

    I am confused with the below point

    Pre-validation operation allows processing the actions written, before throwing invalid plugin exception.

    if we want to restrict actions performed by plugin (we wanted to restrict the Account while adding Accounts in the Associated View) ,we have to use pre-validation ,but in the above point mentioning like “Pre-validation operation allows processing the actions written”

    Reply
    1. Inogic Post author

      Hi Para,

      As mentioned in the blog, if you write a plugin on Pre-validation, the actions performed through the plugin before throwing an error will be allowed to be completed. But because you are throwing an error in this plugin, the action due to which this plugin is triggered will not be completed.

      For example, if you write a plugin on associate of Account. In this plugin, you are first updating a date field on account to set “last assignment attempted on” date time and then further checking to verify the conditions are correct for allowing associate of Account or not. Further, you are checking if you throw an error saying the conditions for validation were not satisfied, the account will not be associated and will show an error. However, the ”Last assignment attempted on” date time field will be updated. This field update will persist even if this plugin throws an error at the end because this plugin is registered on pre-validation.

      Hope this helps!
      Thanks

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *