Search code examples
dynamics-crmdynamics-crm-onlinedynamics-crm-2015

Are Dynamics CRM plugins registered as "post operation" run inside or outside the DB transaction?


I'm working on plugin registration for custom C# plugins for Dynamics CRM (2015 and CRM Online).

When you create a new plugin using the Visual Studio CRM Explorer, you get the standard "Create Plug-in" dialog:

enter image description here

Under "Pipeline Stage", there are three options:

  1. Pre-Validation
  2. Pre-Operation
  3. Post-Operation

Selecting Post-Operation here results in this code being added to the XML registration file:

    <Plugin Description="..." FriendlyName="PostContactCreate" Name="Cacheron.PostContactCreate" Id="00000000-0000-0000-0000-000000000000" TypeName="Cacheron.PostContactCreate">
      <Steps>
        <clear />
        <Step CustomConfiguration="" Name="PostContactCreate" Description="Post-Operation of Contact Create" Id="00000000-0000-0000-0000-000000000000" MessageName="Create" Mode="Synchronous" PrimaryEntityName="contact" Rank="1" SecureConfiguration="" Stage="PostOutsideTransaction" SupportedDeployment="ServerOnly">
          <Images />
        </Step>
      </Steps>
    </Plugin>

The key part there is that middle line, where it says Stage="PostOutsideTransaction"

The corresponding C# code that's generated by the tool includes the line:

base.RegisteredEvents.Add(
  new Tuple<int, string, string, Action<LocalPluginContext>>(
    40, 
    "Create", 
    "contact", 
    new Action<LocalPluginContext>(ExecutePostContactCreate)
  )
);

That magic number 40 in the plugin registration appears to correspond to the "pipeline stages" documented at https://msdn.microsoft.com/en-gb/library/gg327941.aspx, which says

Post-Event

Post-operation

40

Stage in the pipeline for plug-ins which are to execute after the main operation. Plug-ins registered in this stage are executed within the database transaction.

So I've got registration XML generated by the tool that clearly says PostOutsideTransaction, and C# code generated by the same tool that specifies stage 40, which is "executed within the database transaction"

So which is it? Is the XML registration syntax using a misleading name, or is this a bug in the plugin creation tool, or is the execution pipeline doing something clever that I don't understand?


Solution

  • It depends on the message your post operation plugin step is registered for. For the most common messages the step executes inside a database transaction:

    • Create
    • Update
    • Delete
    • SetState
    • Assign

    Some other messages may be executed outside a database transaction, e.g. Publish and PublishAll, and for other it varies (Retrieve, RetrieveMultiple).

    In the IPluginExecutionContext object you can check the IsInTransaction property.