CRM 2011 Plug-ins and Shared Variables

The Microsoft Dynamics CRM 2011 platform and the execution pipeline provides the ability to pass data from one plug-in to another through an IPluginExecutionContext property called SharedVariables. This property is a collection of key/value pairs which developers can use to share data between plug-ins which are registered on both the pre and post events.

Here is a simple code snippet which shows shared variables in action. We may perform some data validation on the pre-create stage of an Account and then pass an updateRelated boolean variable to a post-create Account plug-in which can perform some additional business logic such as asynchronously updating child records of an Account.

Pre-Create Account Plug-in

if (context.InputParameters.ContainsKey("Target") && context.InputParameters["Target"] is Entity)
{
    Entity target = context.InputParameters["Target"] as Entity;
    if (target != null)
    {
        // some wacky data validation
        string city = target.GetAttributeValue<string>("address1_city") ?? string.Empty;
        int numEmployees = target.GetAttributeValue<int>("numberofemployees");
        int accountCategory = target.GetAttributeValue<int>("accountcategorycode");

        // city is auckland, numEmployees > 100, account category is preferred customer
        bool updateRelated = city.Equals("Auckland", StringComparison.InvariantCultureIgnoreCase) && numEmployees > 100 && accountCategory == 1;
        context.SharedVariables.Add("updatedRelated", updateRelated);
    }
}

Post-Create Account Plug-in

if (context.InputParameters.ContainsKey("Target") && context.InputParameters["Target"] is Entity)
{
    Entity target = context.InputParameters["Target"] as Entity;
    if (target != null)
    {
        if (context.SharedVariables.ContainsKey("updatedRelated"))
        {
            bool updateRelated = (bool)context.SharedVariables["updatedRelated"];
            if (updateRelated)
            {
                // additional logic to update related records of the Account
            }
        }
    }
}

That’s all there is to it. This technique lets you build complex plug-ins and pass data between plug-ins without having to set hidden fields on entities.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s