Showing posts with label SharedVariables. Show all posts
Showing posts with label SharedVariables. Show all posts

Friday, April 24, 2009

Use of Shared Variables in Plugins

Apart from the various improvisations of Plugin over Callouts, is the ability to share data between events of an entity. This option was not available when working with Callouts in CRM 3.0. The workaround we used then was to create an attribute and store the information in an attribute in the Pre Create event. In the Post Create use the value of the attribute.

Plugins in CRM 4.0 have introduced the concept of Shared Variables. So now instead of storing the values in a custom attribute you can store the value in a context variable. This is then available in the Post event for use. It is possible to read/write data into SharedVariables of context.

The following code example shows how to use SharedVariables to pass data from a pre-event registered plug-in to a post-event registered plug-in.

Example:
public class PreTest : IPlugin
{
public void Execute(IPluginExecutionContext context)
{
// Create or retrieve some data that will be needed by the post event handler. You could run a query, create an entity, or perform a calculation.
//In this sample, the data to be passed to the post plug-in is represented by a GUID.
Guid contact = new Guid("{74882D5C-381A-4863-A5B9-B8604615C2D0}");
// Pass the data to the post event handler in an execution context shared variable named PrimaryContact.
context.SharedVariables["PrimaryContact"] = contact.ToString();
}
}

public class PostTest : IPlugin
{
public void Execute(IPluginExecutionContext context)
{
// Obtain the contact from the execution context shared variables.
if (context.SharedVariables.Contains("PrimaryContact"))
{
Guid contact = new Guid((string)context.SharedVariables["PrimaryContact"]);
// perform action on contact.
}
}
}