Jul 27, 2014

Using same plug-in for all Create, Update and Delete events

In some cases, we may need to execute same plug-in for Create, Update and Delete. Is this possible?

Yep, you don’t need to write many plug-ins if it’s the same logic. Only thing, we need to have two different ways of triggering the logic in same code. If you need to refresh the knowledge, check Create, Update and Delete code snippets.

You can write a one code accommodating both needs. Different is, in Create/Update we get the target entity in the context while in Delete we get only the reference.

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

  // Create, Update
  
  if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
  {
     TargetEnt = (Entity)context.InputParameters["Target"];

     //Logic here
     //Read Guid like this; 
     //Guid _officeid = (Guid)TargetEnt.Attributes["new_officeid"];

  }

  // Delete

  if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is EntityReference)
  {
     EntityReference EntityRef = (EntityReference)context.InputParameters["Target"];

     //Logic here
     //Read Entity reference like this; 
     //EntityReference _officeidRef = (EntityReference)context.InputParameters["Target"];

  }
  
}
(*I suppose we use a custom entity called new_office in this example)

Hope this is Clear…  register this all Create, Update and Delete steps.

Note:
In Create/Update section always get field values by retrieve method (passing Guid), rather than reading via target entity. If you can remember, though we get all fields in the context for Create, we get only updated fields in Update. Remember?

No comments:

Post a Comment