This scenario deals with the usage of shared variables in a plugin. Using shared variables, Dynamics CRM provides a framework in which custom data values can be exchanged between registered plugins in the same execution context.
Shared variables are the most useful when we need to handle some complex scenarios involving plugins. Using shared variables, we can avoid creating unnecessary calls to the Dynamics CRM organization service as well as the creation of unnecessary fields. This scenario explains a very basic situation related to shared variables in which we will pass a value calculated during a pre-event to be used across a post event.
- Here is the code base of a plugin written on the pre-event of a Contact entity. For creating and assigning a value in a shared variable, we can use the following code:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xrm.Sdk; using Microsoft.Crm.Sdk.Messages; using Microsoft.Xrm.Sdk.Query; namespace SamplePluginProject { public class PreCreateUpdateStudent : IPlugin { public void Execute(IServiceProvider serviceProvider) { if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity) { Entity entity =
(Entity)context.InputParameters["Target"]; if (entity.LogicalName == "contact") { if (context.MessageName.ToLower() == "create" ||
context.MessageName.ToLower() == "update") { // Setting value in Shared variable context.SharedVariables.Add("VariableName",
(Object)"variablevalue"); } } } } } }
Note that whatever value is being passed must be serializable; otherwise, the plugin execution will fail. The following plugin code base can be written on the post update event of the Contact entity:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xrm.Sdk; using Microsoft.Crm.Sdk.Messages; using Microsoft.Xrm.Sdk.Query; namespace SamplePluginProject { public class PostCreateUpdateStudent : IPlugin { public void Execute(IServiceProvider serviceProvider) { // Obtain the value from the execution
// context shared variables. if (context.SharedVariables.Contains("VariableName")) { string variableValue = new (string)context.SharedVariables["VariableName "]; // Do something with the value. } } } }