Infinite loop on Plugin – Dynamics CRM

Have you ever had a situation where you want to use a plugin when a state of a record changes, and the logic needed to implement at the end of the code is to set that record again in the same state?

For instance, if you have a plugin registered in the Quote entity, message SetState/SetStateDynamicEntity and when you activate the Quote, the plugin starts. Your logic in the plugin says that is going to search for some records that are Active, put them in Draft state, changing the necessary fields and Activate it again.

What do we get? The infinite loop….

There is always a problem to these types of plugin, but sometimes you need to do it and how can you get around this problem? We can add a bool field, hidden in the form, to validate this operation at the begining of the plugin and when we first run the plugin, we change that field so the next time it tries to run, it will exit the execution.
It is just one more field, that is hidden in the form and maybe it is easier to manage (you need to remember that if is when you Activate, then when you Revise you need to revert the field), but sometimes there are so many fields that maybe it is better not to implement like that (and not so elegant).

There is another way to do this. You can build a plugin that can be used in a workflow (a workflow plugin), you have the same plugin logic implemented like you have in a normal plugin, but just need to change some of the execution steps of the plugin and how it is registered. If you use the Developer Toolkit for Visual Studio you can do it easily.

1-Create a Workflow Plugin class

Create Workflow Plugin

2-Add Input Parameters if necessary

Input Parameters
Next part of the plugin

3-Deploy your workflow plugin (if you are using Developer ToolKit, otherwise you register via PluginRegistrationTool)

Deploy Workflow Plugin

4-Create your workflow – This workflow can run on a changing of a field, changing of status, etc. In our case we had a button that called this workflow to Activate the Quote and then run my workflow plugin

Create Workflow.

5-Add the step to run your plugin

Choose the plugin

6-Choose the input – After you have added the step you can insert the input to the plugin

Step added
Input from fields

After this, everytime you can this plugin, automatic or via javascript it will run the plugin too.

If you want to just prevent that the plugin goes in an infite loop, you can use Deep property to check if already run.

if (context.Depth > 1) { return; }

Hope this helps.

Advertisements