Wednesday, June 19, 2013

Lazy fix of Infinite Loops in Plugins

Got an error stating that CRM has identified an infinite loop?

This usually means that the number of iterations reaches a maximum of 8. We can fix this by adding a depth check at the beginning of our plugin code, just after we initialize each of the service objects:

IPluginExecutionContext _context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory _factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
_sdk = _factory.CreateOrganizationService(context.UserId);
ITracingService _tracer = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

if (_context.Depth > 1) // if the plugin has run more than once
        // if so, executes a return statement to cancel out of the plugin

Now when we run the plugin, we shouldn’t run into an infinite loop.

NB: You must be careful when using the DEPTH property as there can be more complex scenarios that you may run into. 

No comments:

Post a Comment