Tuesday, January 26, 2016

Infinite loop at CRM

Infinite loop at CRM


Definition of infinite loop:-

An infinite loop (or endless loop) is a sequence of instructions in a computer program which loops endlessly, either due to the loop having no terminating condition, having one that can never be met, or one that causes the loop to start over.

How it happens in CRM:-

CRM detects an infinite loop with two variables 'depth' and 'time', the theory says that if some code (Plugins or Workflows) had been called in one transaction for 8 times (default value of max depth) in 1 hour (default value of time), the system would detect that as infinite loop.

The Depth is passed to plugins or to custom steps as follows:-
  • For plugins:
// Obtain the execution context from the service provider.
IPluginExecutionContext context =
(IPluginExecutionContext) serviceProvider.GetService(typeof(IPluginExecutionContext));
 // Obtain the depth
var depth = Context.Depth;

    • And for Custom Steps:
    var workflowContext = context.GetExtension<IWorkflowContext>();
     // Obtain the depth
    var depth = workflowContext.Depth;
    If plugin had been called from the user directly (for example you created a record) the depth would be 1,
    But if it had been called from workflow or another plugin (for example a workflow updated a field that fires the plugin) then the depth would be 2.

    So, it's not guaranteed to do the following check to prevent the infinite loop


    Code:
    If(depth > 1)
    return;
    

    And it's better to solve the problem instead of working around it.

    There are some cases when a plugin might need to update itself but for the majority of the time avoid doing because it’s confusing/complex and there is usually a better way.

    e.g.

     scheduled process

    I had tried to use Recursive or Scheduled Workflows approach



    For every 15 minutes it calls itself, according to CRM infinite loop definition above it will not countered this as an error, because if we reached the 8th time then, 1 hour and 45 minutes would be passed. For example if we started the workflow at 12:00 then when it would reach 8th at 1:45.

    But unfortunately the CRM will detect this as an infinite loop error


    So, we can rephrase the definition above 
    "If some code (Plugins or Workflows) had been called in one transaction for 8 times (default value of max depth) in 1 hour (default value of time), the system would detect that as infinite loop".

    Finally, you can make external tool that runs for every X of time and check what's failed from the infinite loop and re-run it again.

    Tip:

    You can find the maximum depth and the default value of time by running this query on MSCRM_CONFIG database

    SELECT messageprocessormaximumdepth, messageprocessorminimuminactiveseconds
    FROM   deploymentproperties 




    No comments:

    Post a Comment