Determining Pipeline Stage of Execution

When registering a plugin step in Microsoft Dynamics CRM, you can choose at which stage of execution the plugin should run. In some situations, you may need to have a plugin run at different stages with slightly different behaviour. You can achieve this functionality without having to register separate plugins by having your code check the stage that the current plugin is running in.

Below is a snippet of code showing how you can determine if you are in either the ‘Pre’ or ‘Post’ stages of the execution:

 public class MyEntityPlugin: IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            var context = (IPluginExecutionContext) serviceProvider.GetService(typeof (IPluginExecutionContext));
            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {

                if (context.Stage == 20)//Pre Stage
                {
                    //Do something else
                }
                else if (context.Stage == 40) //Post Stage
                {
                    //Do something else
                }
            }
        }     
    }

For information regarding other stages and other information regarding the execution pipeline, please see this MSDN article.

References

Event Execution Pipeline – http://msdn.microsoft.com/en-us/library/gg327941.aspx