Sunday, March 10, 2019

Trigger common plugin code (C#.net) for any entity in Dynamics 365 (CRM)

Hello dynamic world,

Now this is a simple trick I learnt to do to make my life much easier. The simple case study was that, I wanted to call same function, on create/update of several entities, with some pre-defined conditions for each entity.

Now I could have write separate handler for each entity (entity01handler, entity02handler, .. , entitynhandler) and call the same function keeping it accessible for all handlers.

However what I did is write one handler for all the entities. It was just simple as passing null for target entity in step register.

public class CommonEntityHandler : Plugin
public CommonEntityHandler() : base(typeof(CommonEntityHandler)) {
            base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>((int)PipelineStage.PostOperation, ContextMessageName.Create, null, new Action<LocalPluginContext>(ExecuteCommonEntityCreate)));
            base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>((int)PipelineStage.PostOperation, ContextMessageName.Update, null, new Action<LocalPluginContext>(ExecuteCommonEntityUpdate)));            base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>((int)PipelineStage.PostOperation, ContextMessageName.Associate, null, new Action<LocalPluginContext>(ExecuteCommonEntityAssociate)));            base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>((int)PipelineStage.PostOperation, ContextMessageName.Disassociate, null, new Action<LocalPluginContext>(ExecuteCommonEntityDisassociate)));            base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>((int)PipelineStage.PreOperation, ContextMessageName.Disassociate, null, new Action<LocalPluginContext>(ExecuteCommonEntityDisassociate))); }
private void ExecuteCommonEntityCreate(LocalPluginContext localContext)
 {
   localContext.TracingService.Trace("Common Entity create " + localContext.PluginExecutionContext.Depth);
   if (localContext == null || localContext.OrganizationService == null)
    {
       throw new ArgumentNullException("localContext");
    }

    IOrganizationService service = localContext.OrganizationService;
    ITracingService tracingService = localContext.TracingService;
    IPluginExecutionContext context = localContext.PluginExecutionContext;
    tracingService.Trace("start create");
    try
    {
      if (localContext.PluginExecutionContext.InputParameters.Contains(InputParameter.Target) && localContext.PluginExecutionContext.InputParameters[InputParameter.Target] is Entity)
      {
        var commonEntity = localContext.PluginExecutionContext.InputParameters[InputParameter.Target] as Entity;

      // use commonEntity.Id, commonEntity.LogicalName, commonEntity.Name for your logic
      }  
    }
    catch (InvalidPluginExecutionException)
    {
        throw;
    }
 }
}