Tuesday, June 13, 2017

How to share data b/w plugins

he 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"] isEntity) { Entity target = context.InputParameters["Target"] as Entity; if (target != null) { // some wacky data validation string city = target.GetAttributeValue("address1_city") ?? string.Empty; int numEmployees = target.GetAttributeValue("numberofemployees"); int accountCategory = target.GetAttributeValue("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"] isEntity) { 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.

No comments:

Post a Comment