Monday, August 28, 2023

Plugins and Shared Variables: Share Data Between Plugins - Dynamics 365 CE

Title: Dynamics 365 CE Plugins and Shared Variables: Share Data Between Plugins 

  

In the Dynamics 365 Customer Engagement (CE) customization, plugins are a powerful tool. Sometimes we need to share data between plugins, that’s when we need Shared Variables. In this blog, we'll explore the power of Shared Variables, how to use them in plugin execution context, and why they're a game-changer in your customization endeavors. 

 


To Learn more about Plugin Development: Follow:   

 



Understanding Shared Variables 

  

Shared Variables allow you to store and access data that persists across different steps of plugin execution. Think of them as memory containers where you can keep information throughout the journey of a plugin's execution. 

  

The Power of Shared Variables 

  

Shared Variables offer several advantages that enhance your plugin capabilities: 

  

1. Data Continuity: Maintain data integrity and continuity as your plugin progresses through different stages. 

2. Reduce Recalculation: Store calculated values or intermediate results to avoid redundant computations. 

3. Complex Logic Simplification: Simplify complex logic by storing data that multiple steps require. 

4. Cross-Step Communication: Enable communication between different steps of plugin execution. 

  

Working with Shared Variables 

  

1. Setting Shared Variables: 

  

//Store data in shared variables  

context.SharedVariables["Key"] = value; 

  

2. Retrieving Shared Variables: 

  

if (context.SharedVariables.Contains("Key"))  

{  

    var value = context.SharedVariables["Key"]; 

    // Use the value...  

}   

 

3. Removing Shared Variables: 

  

context.SharedVariables.Remove("Key"); 

 


Share Data Between Plugins 

 

Let’s take an example, we will pass data from Pre-Operation Plugin code to Post-Operation Plugin code. This we will register on Create of a Contact record.  

 

Pre-Operation Plugin Code -  

This plugin will store a Shared Variable in plugin execution context.  Here in this example Email of contact record.

 

using System; 

using System.ServiceModel; 

using Microsoft.Xrm.Sdk; 

 

namespace MyFirstDemoPlugin 

{ 

    public class PreContactCreate : IPlugin 

    { 

        public void Execute(IServiceProvider serviceProvider) 

        { 

            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); 

            ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); 

            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); 

            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);  

 

            try 

            { 

                tracingService.Trace("PreContactCreate Started"); 

 

                if (context.InputParameters["Target"] != null && context.InputParameters["Target"] is Entity entityContact) 

                { 

                    //Get the value which you need to share with other plugin 

                    string strEmailid = entityContact.Attributes.ContainsKey("emailaddress1") ? entityContact.GetAttributeValue<string>("emailaddress1") : string.Empty;  

 

                    //Add SharedVariable to the Context 

                    context.SharedVariables["sharedVarEmailid"] = strEmailid;  

 

                    //Tracing to check 

                    tracingService.Trace("PreContactCreate: Shared Variable Value Set: " + strEmailid); 

                }  

                tracingService.Trace("PreContactCreate Finished"); 

            } 

            catch (Exception ex) 

            { 

                tracingService.Trace(ex.ToString()); 

            } 

        } 

    } 

} 

 
 

 

Post-Operation Plugin Code - 

This plugin will read the Shared Variable from plugin execution context which was added in previous plugin. 

 

using System; 

using System.ServiceModel; 

using Microsoft.Xrm.Sdk; 

 
 

namespace MyFirstDemoPlugin 

{ 

    public class PostContactCreate : IPlugin 

    { 

        public void Execute(IServiceProvider serviceProvider) 

        { 

            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); 

            ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); 

            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); 

            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); 

 

            try 

            { 

                tracingService.Trace("PostContactCreate Started");  

 

                if (context.InputParameters["Target"] != null && context.InputParameters["Target"] is Entity entityContact) 

                { 

                    //Get SharedVariables Value 

                    string sharedVarEmailidValue = context.SharedVariables.ContainsKey("sharedVarEmailid") ? context.SharedVariables["sharedVarEmailid"].ToString() : null; 

 

                    //Tracing  

                    tracingService.Trace("PostContactCreate: Shared Variable Value Received: " + sharedVarEmailidValue);  

 

                    //Just throwing to see SharedVariables Value on screen 

                    throw new InvalidPluginExecutionException("PostContactCreate: Shared Variable Value Received: " + sharedVarEmailidValue); 

                } 

                tracingService.Trace("PostContactCreate Finished"); 

            } 

            catch (Exception ex) 

            {                 

                tracingService.Trace(ex.ToString()); 

                throw new InvalidPluginExecutionException(ex.Message); 

            } 

        } 

    } 

} 

 

 

Plugin Steps- 

 

Both Plugin steps are registered on Create of Contact Record, one is on Pre-Operation and another one on Post-Operation and both the Plugins are Synchronous.  

 

 

 

Test the Plugins 

 

Now, let's create a Contact record in Dynamics CRM Platform.  


Before saving the Contact Record -  


 


After saving the Contact Record - Email of contact record received through SharedVariables.


 

 

Best Practices for Shared Variables 

  

1. Clear Usage: Use meaningful keys to avoid confusion in shared variable storage. 

2. Size Consideration: Don't store excessive data; use shared variables for essential and commonly used information. 

3. Concurrency Awareness: Shared variables are shared across plugin instances, so be cautious with concurrent execution. 

  

Conclusion 

  

Shared Variables in Dynamics 365 CE plugins are like breadcrumbs that guide your customization journey, ensuring that essential data is retained and accessible when needed most.   

  

Stay tuned for more insights into the world of Dynamics 365 CE customization and Plugin Development. 

#Dynamics365 #Development #Plugin 

 
 

Next Steps: Learn more about other powerful features of Plugin! 

 

 

No comments:

Post a Comment