RSS

Tag Archives: Post-event

Use of Shared Variables in Plugin

Introduction

Shared Variables will be useful for sharing the data during complex Plug-in development by sharing the data between Plugins registered on both the pre and post events.

Any value stored in the Plug-in context of Pre-event will be available in the Post-event of the Plug-in. This way, we can avoid storing the values in a custom attribute. Certain data validation which needs to be done at post-event can be achieved by passing the value from Pre-event of the Plug-in. This also helps for performing business logic like updating related records asynchronously.

Using the Code

The below code snippet illustrates the usage of Shared Variable. This sample explains the data validation done at Post-event operation based on the value received from the Pre-event operation where a flag is updated with a value at the Pre-event level and sent to the Post-event through shared variable.

//Pre-Create (Entity Name) Plug-in
if (pluginContext.MessageName == "Create")
{
    if (pluginContext.InputParameters.ContainsKey("Target")
                             && 
        pluginContext.InputParameters["Target"] is Entity)
    {
        Entity targetEntity = context.InputParameters["Target"] as Entity;
        if (targetEntity != null)
        {
            bool setFlag = false;

            //Check data validation for attributes
            string country = targetEntity.Attributes["address1_country"];
            OptionSetValue industryCode = (OptionSetValue)target.Attributes["industrycode"];

            // Country is US and Industry Type is Accounting are Preferred
            if (country.ToLower() == "us" && industryCode.Value == 1)
            {
                setFlag = true;
            }
            
            pluginContext.SharedVariables.Add("flag", setFlag);
        }
    }
}

//Post-Create (Entity Name) Plug-in
if (pluginContext.MessageName == "Create")
{
    if (pluginContext.InputParameters.ContainsKey("Target")
                           && 
        pluginContext.InputParameters["Target"] is Entity)
    {
        Entity targetEntity = pluginContext.InputParameters["Target"] as Entity;
        if (targetEntity != null)
        {
            if (pluginContext.SharedVariables.ContainsKey("flag"))
            {
                bool recievedFlag = (bool)pluginContext.SharedVariables["flag"];
                if (recievedFlag)
                {
                    // Do whatever you want to do
                }
             }
         }
    }
}

This method lets you to pass data between Plug-ins without having to customize the system by creating hidden fields on entities.

Note: SharedVariables (collection of key/value pairs) property is available in the IPluginExecutionContext of the execution pipeline.

By Gitanjali
Senior Software Engineer @Team DynamicsCRM.
Mindfire Solutions

 

Tags: , , , , , , , , , , , , , , , , , ,

 
%d bloggers like this: