Saturday 7 September 2013

Context in plugin in mscrm 2011



What is context in plug-in?

All plug-ins must implement the IPlugin(base class for plug-in) interface.
 The IPlugin interface defines an Execute method, which takes an IPluginExecutionContext parameter.
 This context is contained in the System.IServiceProvider parameter.
 When a system event is fired for which a plug-in is registered, the system creates and populates the context. The system then calls the plug-in's Execute method, passing in the context as a parameter.
The context contains information that describes the run-time environment that the plug-in is executing in, information related to the execution pipeline, and entity business information.



Code used in the plug-in:

//plugin class should inherit the plugin base class i.e IPlugin
public class Plugin: IPlugin

// Obtain the execution context from the service provider.
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));

// Obtain the organization service reference.
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

// The InputParameters collection contains all the data passed in the message request.
if (context.InputParameters.Contains("Target") &&
    context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parameters.
    Entity entity = (Entity)context.InputParameters["Target"];

// Target could be of Type ‘Entity’ or ‘Entity Reference’.  For example, DeleteRequest does have a Target property but its type is EntityReference.
// The InputParameters collection contains all the data passed in the message request.
if (context.InputParameters.Contains("Target") &&
    context.InputParameters["Target"] is EntityReference)
{
// Obtain the target entity from the input parameters.
    EntityReference entity = (EntityReference)context.InputParameters["Target"];
 

No comments:

Post a Comment