Monday, April 15, 2013

Write a common plugin for Create/Update/Delete events in Dynamics CRM 2011

If you want to write a common plugin for Create/Update/Delete events in Dynamics CRM 2011 then only you need to take care of “context.InputParameters["Target"]“. In case of Create/Update event “context.InputParameters["Target"] is Entity” and in case of Delete event “context.InputParameters["Target"] is EntityReference”. Below is the sample code for the same:


public void Execute(IServiceProvider serviceProvider)
{
     // Obtain the execution context from the service provider.
     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)
     {
          if (context.MessageName == "Create")
          {
               //Code to be executed during Create event of an entity
          }
          else if (context.MessageName == "Update")
          {
               //Code to be executed during Update event of an entity
          }
      }
      else if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is EntityReference)
      {
          if (context.MessageName == "Delete")
          {
              //Code to be executed during Delete event of an entity
          }
      }
}

No comments:

Post a Comment