Tuesday, 13 March 2012

ExecutionContext.CallerOrigin in Microsoft Dynamics CRM 2011?

I only realised this a couple of days ago... but this property has been made obsolete, supposedly because it was unreliable. My delayed realisation is probably due to my absence from the CRM scene until about 6 months ago!

Anyway, there were a few reasons why we needed the CallerOrigin in MSCRM 4.0, so it's a pity it was removed. But there are ways around each scenario where we needed it:


Prevent infinite loops (over 2 plugins)

This was the reason I was looking for the CallerOrigin and I started to ask this question. I only wanted the plugin to fire if it came from a user on the form, not from another plugin (i.e. asyc process/webservice). In my case the distinction of it being "over 2 plugins" is quite important, because I cannot use InputParameters to solve the problem. My example was similar to the following:

  • Update Plugin for "Parent" Entity. If optionset called "Status" on the parent entity was set to "Approved" I subsequently wanted to set a status on all the child entities to "Approved" as well.
  • Update Plugin for "Child" Entity. If the optionset called "Status" on the child entity was set to "approved", and all other children of the same parent has this set to "Approved" I needed to update the Status on the parent to approved as well.

This causes an infinite loop if you don't protect yourself against it. You also cannot use the InputParameters to solve it. Solution? Use depth checking:

context.PluginExecutionContext.Depth

If this is greater than 1 it's been called by another plugin.


Prevent syncing issues from an offline client

We've been given different properties to help us distinguish these ones. Use these instead:

context.PluginExecutionContext.IsExecutingOffline
context.PluginExecutionContext.IsOfflinePlayback


Reacting differently depending on what the origin is

Ok, so this is the only scenario where we really do need the CallerOrigin. The only way I think you'd be able to do this is by checking the type of the PluginExecutionContext itself. I know for async it's the type:

Microsoft.Crm.Asynchronous.AsyncExecutionContext

and for plugins it seems to be:

Microsoft.Crm.Extensibility.PipelineExecutionContext

Outside of that you would probably have to check the

PluginExecutionContext.ParentContext


Alternatives?

The only other method I've come across for detecting where the update came from is using a custom flag on the form. So you could create an OptionSet called "OriginOfChange" (or something similar) with the options

  • CRM Form (Javascript onsave)
  • Workflow
  • Plugin
  • etc.

Then what ever updates the entity sets this field during the update. In this way you could check the Input Parameters each time to see where the update has come from.

No comments:

Post a Comment