CRM Crate

How to use the Shared Variables in plugins – Dynamics CRM

In this course, we will learn to use the Shared Variables in plugins. Before we start, make sure to subscribe CRM Crate in order to recieve all latest updates & courses in the field of Microsoft Dynamics CRM.

How to use the Shared Variables in plugins

What are Shared Variables in plugins?

Shared Variables in Plug-in were introduced in later version of CRM 4.0. Shared Variables are used for passing data between plug-ins registered on both pre and post events. Thus, instead of capturing / storing values in custom made attributes, those values can be stored in context variable. With help of Shared Variables we can read and write data from one plugin to another via the plugin execution context.

How to use Shared Variables for passing data between two different plugins?

In the below example, we will pass the variable data from one plugin which is running in Pre-Operation pipeline to another plugin which is running in Post-Operation pipeline within the same plugin assembly.
The above mentioned plugins are executing on the creation of an Account record.

  • Pre-Operation Plugin Code –
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using System.Threading;
using Microsoft.Crm.Sdk.Messages;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ClassLibraryProject
{
    public class AccountCreate : IPlugin
    {
        #region Global Variables. 
        public static ITracingService tracing;
        public static string debug = string.Empty;
        #endregion

        //Main Execute Method.
        public void Execute(IServiceProvider serviceProvider)
        {
            //Initializing Service Context.
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = factory.CreateOrganizationService(context.UserId);
            OrganizationServiceContext orgContext = new OrganizationServiceContext(service);
            tracing = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            Entity eTarget = null;

            //Initializing Target Entity.
            eTarget = (context.InputParameters.Contains("Target") && context.InputParameters["Target"] != null) ? context.InputParameters["Target"] as Entity : null;
            tracing.Trace("Target Record GUID : " + eTarget.Id);

            try
            {

                //Calling The Method For Shared Variable Declaration.
                SharedVariableMethod(service, context, eTarget);

            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
        }

        //Method Used To Pass The Shared Variable.
        public void SharedVariableMethod(IOrganizationService service, IPluginExecutionContext context, Entity eTarget)
        {
            try
            {
                tracing.Trace(" Entered AccountPreCreate");

                //Passing Account Name In Shared Variable Context.
                context.SharedVariables.Add("MySharedVariable", eTarget.GetAttributeValue<string>("name"));
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
        }

    }
}

Code Explanation –

  1. This plugin will create a Shared Variable in the plugin execution context.
  2. Target Account record is retrieved in the eTarget variable.
  3. The Shared Variable is added in the plugin execution context. The value present in the Shared Variable will be the name of retrieved target Account record.
  • Post-Operation Plugin Code –
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using System.Threading;
using Microsoft.Crm.Sdk.Messages;

namespace ClassLibraryProject
{
    public class ReadSharedVariable : IPlugin
    {
        #region Global Variables. 
        public static ITracingService tracing;
        public static string debug = string.Empty;
        #endregion

        //Main Execute Method.
        public void Execute(IServiceProvider serviceProvider)
        {
            //Initializing Service Context.
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = factory.CreateOrganizationService(context.UserId);
            OrganizationServiceContext orgContext = new OrganizationServiceContext(service);
            tracing = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            //Retrieving Shared Variable Information
            try
            {
                if (context.SharedVariables.Contains("MySharedVariable"))
                {
                    string SharedVariableValue = (string)context.SharedVariables["MySharedVariable"];
                    tracing.Trace("Value Captured In Shared Variable = " + SharedVariableValue);

                    //Exception TO Observe Shared Variable On UI.
                    throw new InvalidPluginExecutionException("Shared Variable Value = " + SharedVariableValue);
                }
                else
                {
                    tracing.Trace("Shared Variable Is Not Present In The Context.");
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
        }

    }
}

Code Explanation –

  1. This plugin is used to read the Shared Variable which was created by the above Pre-Operation plugin.
  2. Plugin will read the Shared Variable value present in the execution context.
  3. In order to display the output, the plugin will print the retrieved Shared Variable in the UI with help of InvalidPluginExecutionException on creation of an Account record.

Output demonstration of the Shared Variable implementation

On creation of an Account record, the system throws an error message for displaying the value captured by the Post-Operation plugin. As we are passing the Account Name in the Shared Variable, the value of Account Name will be captured in the Shared Variable.

Before saving an Account record –

After saving an Account record –

Thus, we learned the significance and implementation of the Shared Variables in plugins of Microsoft Dynamics CRM.

CRM Crate

All In One Platform For Learning Microsoft CRM.

4 2 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
error: CRM Crate Security Engine - Disabled Right Click & Selection!

Congratulations!

Well Done,
Welcome to CRM Crate

Stay tuned with us and get all latest updates and learning in Microsoft CRM and related techonologes.