MSBA-272 · Lesson 1 of 12 · 19 min
Plug-in basics and the execution pipeline
▶ Video coming soon A video version of this lesson is on the way.
In the developer design reviews earlier in the term, Signe Tavernier-Mbeki had sketched two pieces of server-side logic for Lumenvale Community Colleges: a plug-in that calculates the fee for a transcript request, and a custom API that other apps and flows could call to get the same answer. Rupert Ellingsworth approved both designs and asked for one thing in return. Wiremu Quaresma, the other pro developer in central IT, would write most of the code, and Signe would teach him as they went. Wiremu came from a web agency and knew TypeScript, React and Azure well, but he had never written code that ran inside Dataverse. This course follows their working sessions in the second half of the fall term of 2026, in Wiremu's developer environment, from the first plug-in to a full pricing engine.
Signe started with a warning she gave every new developer. A plug-in is not a web service you call; it is code that Dataverse calls, inside its own processing of a request, under its rules. Once you understand where your code sits and what Dataverse expects of it, plug-ins are straightforward. Most of the bugs she had fixed over the years came from developers who treated a plug-in like ordinary application code.
What a plug-in is
A plug-in is a .NET class that implements the IPlugin interface from the Dataverse SDK. The interface has one method, Execute, which receives an IServiceProvider. When an event happens in Dataverse, such as a row being created or a message being called, Dataverse looks for registered steps that match the event, loads the plug-in class for each one, and calls Execute. Through the service provider the plug-in gets the services it needs: the execution context, which describes what is happening; a tracing service for diagnostic messages; and an organization service factory for reading and writing data.
The compiled class lives in an assembly, a DLL built for the .NET Framework, which is registered in Dataverse. On its own, a registered assembly does nothing. It needs at least one step, which tells Dataverse which message and table to watch, at which stage, and whether to run synchronously or asynchronously. One assembly can hold many plug-in classes, and one class can be registered on several steps.
using System;
using Microsoft.Xrm.Sdk;
namespace Lumenvale.Registrar.Plugins
{
public class CalculateTranscriptFee : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
var tracing = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
var factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
var service = factory.CreateOrganizationService(context.UserId);
tracing.Trace("Message {0} on {1}, stage {2}, depth {3}",
context.MessageName, context.PrimaryEntityName, context.Stage, context.Depth);
// Business logic goes here
}
}
}Wiremu asked why the code created the organization service with the context's user ID. Signe explained that this decides whose permissions the plug-in's own reads and writes use. Passing the calling user's ID means the plug-in can only do what that user could do. Passing null runs the calls as the SYSTEM user, which bypasses security roles and should be a deliberate, documented choice. Lesson 7 of MSBA-270 covered the security side; here she only wanted him to notice that the choice is made on this line.
The execution pipeline
Every message that reaches Dataverse passes through the event execution pipeline. MSBA-270 introduced the stages; Signe reviewed them with the transcript fee in mind. The pipeline has four stages that matter to developers, identified by number.
| Stage | Number | Inside the transaction? | Typical use |
|---|---|---|---|
| PreValidation | 10 | Not necessarily; runs before the main transaction starts | Cheap checks that should cancel the operation early, before security checks and locks |
| PreOperation | 20 | Yes | Changing values on the row before it is saved; validation that needs the transaction |
| MainOperation | 30 | Yes | Dataverse's own work; custom APIs place their main logic here |
| PostOperation | 40 | Yes for synchronous steps; asynchronous steps run later, outside it | Work that needs the saved row, such as creating related rows |
For the transcript fee, the stage choice was easy. The fee had to be on the row when it was saved, so that the request form, the payment flow and the reports all saw the same number. Changing values on the Target entity in PreOperation is the efficient way to do that: the plug-in modifies the data that Dataverse is about to write, and no extra update is needed. Doing the same in PostOperation would mean a second update of the row, which runs the pipeline again and costs a database write.
Synchronous and asynchronous steps
A synchronous step runs while the caller waits. If it throws an exception, the whole operation is rolled back and the caller sees the error. An asynchronous step is queued as a system job and runs shortly afterwards, outside the transaction; the caller has already received a success response, and a failure shows up in the system job record rather than on the user's screen. Asynchronous steps can only be registered in PostOperation.
Signe's rule of thumb was that a step should be synchronous only if the user must see its effect or its error immediately. The fee calculation qualified: an adviser saving a transcript request expected to see the fee. Sending a confirmation email, updating a dashboard count or calling an external system did not, and those belonged in asynchronous steps or flows. Microsoft's own guidance points the same way, recommending asynchronous registration whenever an extension would take more than about two seconds.
The execution context
The IPluginExecutionContext is the plug-in's view of the event. Wiremu printed its main properties to the trace log on his first test run and was surprised how much was there.
| Property | What it tells the plug-in |
|---|---|
| MessageName | The message being processed, such as Create, Update or a custom API name |
| PrimaryEntityName | The table the message applies to |
| Stage and Mode | Which pipeline stage, and whether the step is synchronous (0) or asynchronous (1) |
| InputParameters | The request data; for Create and Update the "Target" entity holds the column values |
| OutputParameters | The response data, filled in after the main operation; custom APIs write their results here |
| PreEntityImages and PostEntityImages | Snapshots of the row before and after the operation, if images are registered |
| UserId and InitiatingUserId | The user the step runs as, and the user who actually started the operation |
| Depth | How deep in a chain of plug-in calls this execution is |
| SharedVariables | A dictionary for passing values between steps in the same operation |
| ParentContext | The context of the operation that caused this one, when steps trigger further operations |
Two properties caused most confusion. InputParameters["Target"] on an Update contains only the columns the caller changed, not the whole row. A plug-in that reads a column from the Target and finds it missing must not assume the column is empty; it may simply not have been changed. That is what images are for. A pre-image registered on the step gives the plug-in the row's values before the update, with only the columns it asks for. Combining the Target with the pre-image gives the full picture without a separate Retrieve call.
The other was Depth. Each time a plug-in's own operation triggers another plug-in, the depth goes up by one. A plug-in that updates the row it is registered on, on a step that fires on that same update, triggers itself again and again. Dataverse detects runaway chains and stops them with an error, but a plug-in should not rely on that safety net. Filtering attributes, checking whether a value actually changed and, in the rare cases it is needed, checking Depth are the usual defenses.
The sandbox
Plug-ins in Dataverse run in an isolated sandbox. The sandbox limits what code can do: it cannot read or write the server's file system, cannot use the registry, and has restricted network access. Outbound calls are allowed over HTTP and HTTPS, which is how plug-ins call external web services, but they should use proper host names and not depend on anything inside Microsoft's data center. The sandbox also watches resources. If a plug-in uses too much CPU or memory or stops responding, Dataverse ends its worker process.
There is also a hard limit on time. A message operation, including every synchronous and asynchronous plug-in registered on it, must finish within two minutes or Dataverse throws a timeout and rolls the operation back. Signe pointed out that this budget is shared with everything else on the message, so the two-second guidance for a single plug-in leaves room for others. Lesson 10 returns to limits in more detail.
Statelessness
Dataverse caches plug-in instances and may run the same instance for many requests, including at the same time on different threads. A plug-in class must therefore be stateless: no instance fields that change during Execute, no static variables holding data between calls. Configuration read once in the constructor is fine; per-request data belongs in local variables inside Execute. Wiremu's web background made this easy to accept once Signe compared a plug-in instance to a shared singleton service in a web app.
Plug-ins and other ways to run logic
Wiremu asked when a plug-in was the right answer at all, since MSBA-270 had spent a whole lesson on the alternatives. Signe summarized: a plug-in is the right tool when logic must run on the server, every time, whatever app or integration touches the data, inside the transaction, and faster than a flow could react. Business rules and formula columns cover simple cases with no code. Power Automate covers work that can happen afterwards. Low-code plug-ins and functions, covered in lesson 9, sit in between. The transcript fee met every condition for a plug-in: it had to be correct whether the request came from the Transcript Office model-driven app, the Request a Transcript app in Teams or the bulk import the records office ran each spring.
Worked problem
Choosing stage and mode for three registrar rules
Signe gave Wiremu three rules to place. (1) A transcript request for a student with an active financial hold must be refused with a clear message. (2) The fee must be calculated and stored on the request when it is created or when the delivery method changes. (3) When a request is marked Sent, a row must be written to an audit table that a nightly report reads.
Show solution
- Rule 1 must stop the save and show the user why. It needs only a quick lookup of the student's holds, so it fits PreValidation (or PreOperation), synchronous. PreValidation cancels before any locks are taken.
- Rule 2 sets a column on the row being saved. PreOperation, synchronous, on Create and on Update filtered to the delivery method column, changing the Target directly.
- Rule 3 can happen a moment later and nobody waits for it. PostOperation, asynchronous, on Update filtered to the status column, with a pre-image to confirm the status actually changed to Sent.
Answer: Rule 1: PreValidation, synchronous. Rule 2: PreOperation, synchronous, Target changed in place. Rule 3: PostOperation, asynchronous, with filtering and a pre-image.
Messages beyond Create and Update
Create and Update are the messages most plug-ins watch, but they are not the only ones. Delete, Assign, SetState and its successors, Associate and Disassociate for many-to-many relationships, Retrieve and RetrieveMultiple, and every custom API are all messages a step can be registered on. Retrieve and RetrieveMultiple deserve caution: a plug-in on them runs every time anyone reads the table, including every view a user opens, so even a few milliseconds of work multiply quickly. Signe had once traced a slow Lumenvale form to a RetrieveMultiple plug-in that a contractor had written to hide archived rows; a view filter would have done the same job for free.
Wiremu also learned that a single user action can produce several messages. Saving a form that changes the owner and a status column may arrive as one Update, but a flow or integration might send an Assign followed by an Update. Plug-ins should be written for the message and data they receive, not for the screen a developer imagines the user is looking at.
A first working plug-in
By the end of the first session, Wiremu had a plug-in that did nothing but trace the context and set a placeholder fee of zero in PreOperation. It was not useful, but it proved the whole chain: the project built, the assembly registered, the step fired, the trace appeared and the value landed on the row. Signe insisted on this "hello pipeline" before any real logic, because every later problem would be easier to diagnose once the plumbing was known to work. Lesson 2 covers how he built and registered it; lesson 3 covers how he read the traces.
Common mistakes
MistakeReading a column from the Update Target and treating its absence as an empty value.
InsteadRemember the Target holds only changed columns; use a pre-image for the rest.
MistakeUpdating the same row in PostOperation to set a calculated value.
InsteadSet the value on the Target in PreOperation so no second update is needed.
MistakeStoring request data in fields of the plug-in class.
InsteadKeep plug-ins stateless; use local variables inside Execute.
MistakeMaking every step synchronous so its effects are immediate.
InsteadUse synchronous steps only when the user must see the result or error; queue the rest.
MistakeCreating the organization service with null without thinking.
InsteadUse the calling user by default and document any deliberate use of SYSTEM.
Summary and key terms
- A plug-in is a .NET class implementing IPlugin, registered in an assembly and attached to steps that name a message, table, stage and mode.
- The pipeline stages are PreValidation (10), PreOperation (20), MainOperation (30) and PostOperation (40); stages 20 to 40 synchronous run inside the database transaction.
- Synchronous steps make the caller wait and roll back on error; asynchronous steps run later as system jobs, only in PostOperation.
- The execution context provides the message, table, Target, images, users, depth and shared variables; Update Targets hold only changed columns.
- Plug-ins run in a sandbox with network, resource and two-minute limits, and must be stateless.
- Plug-in
- A .NET class implementing IPlugin that Dataverse runs in response to a registered event.
- Step
- A registration that connects a plug-in class to a message, table, stage and mode.
- Event execution pipeline
- The ordered stages every Dataverse message passes through.
- Target
- The input parameter that holds the row data for Create and Update messages.
- Pre-image
- A snapshot of selected columns of a row before the operation, registered on a step.
- Depth
- A context value that counts how deep a plug-in execution is in a chain of triggered operations.
- Isolated sandbox
- The restricted environment in which Dataverse runs plug-in code.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Why is PreOperation usually the right stage for calculating a value stored on the same row?
Show answer
The plug-in can change the Target before it is written, so no second update is needed.
In which stage can an asynchronous step be registered?
Show answer
Only PostOperation.
What does the Target contain on an Update message?
Show answer
Only the columns that the caller changed.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.