MSBA-272 · Lesson 2 of 12 · 20 min

Writing and registering plug-ins

▶ Video coming soon A video version of this lesson is on the way.

With the pipeline clear, the second session moved to Wiremu's laptop. Signe wanted him to build the transcript fee plug-in the way Lumenvale would maintain it for years: a proper project in source control, a predictable build, a registration that lived in a solution, and nothing done by hand in production. The prototype she had written in the summer worked, but it had been registered from her machine with settings nobody had written down, and she did not want the production version to repeat that.

Setting up the project

Dataverse plug-ins are compiled for the .NET Framework 4.6.2. That surprised Wiremu, who worked in modern .NET every day, but the sandbox that runs plug-ins is built on the .NET Framework, and assemblies must target it. The project references the Microsoft.CrmSdk.CoreAssemblies NuGet package, which provides the IPlugin interface and the SDK types such as Entity, EntityReference and OptionSetValue.

The quickest way to start is the Power Platform CLI. Running pac plugin init in an empty folder creates an SDK-style class library project with the right target framework, the SDK package reference and a small base class that handles the boilerplate of getting services from the service provider. Signe preferred this to starting from a blank Visual Studio project, because the template matched Microsoft's current guidance and set up the project for plug-in packages, which she wanted to use.

Creating and building a plug-in project with the Power Platform CLI.
mkdir Lumenvale.Registrar.Plugins
cd Lumenvale.Registrar.Plugins
pac plugin init --author "Lumenvale Central IT"
dotnet build -c Release

The template's base class, usually called PluginBase, implements IPlugin and calls an abstract method with a local context object that already holds the execution context, the tracing service and organization services for the user and for the system. Wiremu's plug-in class then contained only business logic. Signe pointed out that the base class was ordinary source code in the project, not a library, so the team owned it and could change it, and that every Lumenvale plug-in project should start from the same version so that the patterns stayed consistent.

Assemblies and plug-in packages

There are two ways to deploy plug-in code. The older way registers a single assembly, which must be signed with a strong name key and must contain everything the plug-in needs. If the plug-in uses another library, such as a JSON parser or a shared Lumenvale utility, that code has to be merged into the assembly, and Microsoft does not support merging tools such as ILMerge for this.

The newer way is a plug-in package, which Microsoft calls dependent assemblies. A plug-in package is a NuGet package that contains the plug-in assembly together with the assemblies it depends on. Dataverse stores the package in the PluginPackage table and makes the dependencies available when the plug-in runs. Signing is not required for an assembly deployed in a package, although if a team does sign, every dependent assembly must also be signed.

Deployment choices for plug-in code, as documented by Microsoft.
PointSingle assemblyPlug-in package
ContentsOne DLL with all code merged inA NuGet package with the plug-in DLL and its dependencies
Strong-name signingRequiredNot required; if used, all dependencies must be signed
Using other librariesOnly by compiling them inInclude them as dependencies
Workflow activitiesSupportedNot supported
Changing name or versionThe assembly version can changePackage name and version cannot change after creation; increment the version on updates

Microsoft documents a few limits that matter in practice. Plug-in packages do not support custom workflow activities, on-premises deployments or unmanaged code. Each assembly is limited to 16 MB. The project should be an SDK-style project targeting .NET Framework 4.6.2, which pac plugin init produces. Large packages take time to import: Microsoft gives roughly fifteen minutes for a package with a thousand plug-in types. One quirk caught Signe once: if code uses System.Text.Json, the package must include it explicitly as a dependency.

Lumenvale chose plug-in packages for all new work. The registrar plug-ins needed a small shared library that formatted money and student numbers consistently across projects, and the package model let the team keep it as a separate project with its own tests.

Writing the transcript fee logic

The fee rules came from the registrar's office, through Maribeth Ferreira-Quon, and were simple enough to state in a paragraph. An official transcript sent electronically cost one fee; a paper transcript by regular mail cost more; a courier delivery added a courier surcharge; and students who had graduated in the last twelve months received their first transcript free. The amounts themselves lived in the Transcript Fee Rate table that Signe had designed in MSBA-270, with one row per delivery method and effective dates, so the registrar's office could change prices without a developer.

The heart of the transcript fee plug-in. Column names use the lcc publisher prefix; TranscriptRateReader is a small class in the same project.
public class CalculateTranscriptFee : PluginBase
{
    public CalculateTranscriptFee(string unsecureConfig, string secureConfig)
        : base(typeof(CalculateTranscriptFee)) { }

    protected override void ExecuteDataversePlugin(ILocalPluginContext local)
    {
        var context = local.PluginExecutionContext;
        if (!(context.InputParameters["Target"] is Entity target)) return;

        // On Update, read unchanged columns from the pre-image
        var pre = context.PreEntityImages.Contains("pre") ? context.PreEntityImages["pre"] : null;
        var method = target.GetAttributeValue<OptionSetValue>("lcc_deliverymethod")
                     ?? pre?.GetAttributeValue<OptionSetValue>("lcc_deliverymethod");
        if (method == null) throw new InvalidPluginExecutionException("Choose a delivery method before saving.");

        var rates = new TranscriptRateReader(local.InitiatingUserService);
        Money fee = rates.FeeFor(method.Value, DateTime.UtcNow);

        local.Trace("Delivery method {0}, fee {1}", method.Value, fee.Value);
        target["lcc_fee"] = fee;   // PreOperation: written as part of the same save
    }
}

Signe reviewed the first version line by line. She liked that the plug-in did not trust the Target to contain the delivery method and fell back to a pre-image. She asked Wiremu to move the rate lookup into a separate class so it could be unit tested without Dataverse, which became the TranscriptRateReader in the sample. She also asked him to use the initiating user's service for the lookup, so that a user without read access to rates would get a permission error rather than a fee they could not otherwise see, and to throw InvalidPluginExecutionException with a message a registrar clerk would understand. Lesson 11 covers error handling in depth.

Registering with the Plug-in Registration tool

Code in a package does nothing until it is registered. The Plug-in Registration tool, usually called PRT, is Microsoft's desktop application for registering packages, assemblies, steps, images and service endpoints. It is installed and launched through the CLI with pac tool prt, which keeps it up to date.

In PRT, Wiremu connected to his developer environment and chose to register a new package, pointing at the .nupkg file that the build produced in the bin folder. PRT asked which solution to add it to, and he picked the Registrar Transcripts solution so the package would travel with the rest of the registrar components. The tool read the package and listed the plug-in types it found: CalculateTranscriptFee and, from Signe's summer prototype, BlockSafetyCloseWithoutPhoto, which belonged in another project and which he removed before going further.

Next came the step. Registering a step means choosing the message, the primary table, any filtering attributes, the stage, the mode, an execution order and, optionally, configuration and images.

The Update step for the transcript fee plug-in.
SettingValue for the transcript fee (on Update)Why
MessageUpdateThe fee changes when the delivery method changes; a separate step covers Create
Primary entitylcc_transcriptrequestThe table the plug-in applies to
Filtering attributeslcc_deliverymethod, lcc_graduationdateOnly run when a column that affects the fee changes
Event pipeline stagePreOperationSet the fee on the Target before the save
Execution modeSynchronousThe clerk expects to see the fee on save
Execution order1Runs before any other PreOperation step on the same message
Pre-imageAlias "pre", columns lcc_deliverymethod, lcc_graduationdate, lcc_contactidValues not in the Target on partial updates
A chain of five boxes from left to right: project built with pac plugin init, NuGet package in the bin folder, package registered in PRT, plug-in type, and two steps (Create and Update), with a pre-image attached to the Update step. A bracket under the last three boxes reads "stored in the Registrar Transcripts solution".
From project to registered steps.

Filtering attributes were the setting Signe cared about most. Without them, an Update step fires for any change to the row, including a clerk correcting a typo in the notes column or a flow updating a status. With them, the step fires only when one of the named columns is in the update. Every Update step at Lumenvale had to list its filtering attributes, and a review checklist item caught any that did not.

Configuration strings

A step can carry two configuration strings, which Dataverse passes to the plug-in class's constructor. The unsecure configuration is stored with the step and travels in solutions. The secure configuration does not travel in solutions and can be read only by administrators, which is why older code used it for secrets. Signe was clear that secrets no longer belonged there. Lumenvale stored keys in Azure Key Vault and, where a plug-in had to call an Azure resource, used a managed identity for plug-ins, as MSBA-270 had described. For ordinary settings such as a feature switch or a default value, environment variables were a better home than either configuration string, because they could be set per environment through deployment settings.

Updating code with pac plugin push

After the first registration in PRT, the package has an ID in Dataverse. From then on, developers can update the code without opening the tool by running pac plugin push with that ID. The command uploads the new build and replaces the registered package. Wiremu added it to a small script that built the project and pushed it to his developer environment, which cut his edit-and-test cycle to under a minute.

Pushing a new build of a registered package. The ID shown is a placeholder.
dotnet build -c Release
pac plugin push --pluginId 00000000-0000-0000-0000-000000000000 --type Nuget --pluginFile .\bin\Release\Lumenvale.Registrar.Plugins.1.0.4.nupkg

Because a package's version cannot be changed after it is created in Dataverse but its contents are replaced on each push, Signe asked Wiremu to keep the package version in the project file in step with the solution version, increase it with every change that went to test, and record the version in the pull request. That way anyone looking at an environment could tell which code was running.

Solutions and deployment

Everything PRT registered went into the Registrar Transcripts solution: the package, the plug-in types, the steps and the images. From there the normal application lifecycle took over. The solution was exported as managed and deployed to test and production through the pipeline described in MSBA-270, and nobody registered plug-ins directly in test or production. If a step was missing in test, the fix was to add it to the solution in development and deploy again, not to open PRT against test.

Signe added one practical warning. When a step is registered with PRT and the solution is chosen in the dialog, the step goes into that solution; if the dialog is skipped, the step is created only in the default solution and silently misses the next export. Checking the solution's list of plug-in steps before every export was part of Lumenvale's release checklist.

Worked problem

Adding the Create step

The Update step only fires when a request is changed. Wiremu needed the fee calculated when a request is first created, too, including requests created by the Request a Transcript app and by the spring bulk import.

Show solution
  1. Register a second step on the same plug-in type: message Create, table lcc_transcriptrequest, stage PreOperation, synchronous.
  2. Leave filtering attributes empty; they apply only to Update.
  3. Register no pre-image: a Create has no earlier version of the row, and the Target holds every value supplied.
  4. Make sure the code handles a missing pre-image, which it does by checking PreEntityImages.Contains first.
  5. Add the step to the Registrar Transcripts solution in the registration dialog and confirm it appears in the solution's plug-in steps.

Answer: One plug-in type, two steps: Create with no image and no filtering, and Update with filtering attributes and a pre-image, both PreOperation and synchronous.

Images in more detail

Images are registered on a step in PRT after the step itself. Each image has a type (pre-image, post-image or both), a name used in the registration list, an entity alias that the code uses to find it, and a list of columns. Microsoft's guidance is to include only the columns the code reads. An image with every column forces Dataverse to retrieve the whole row on each execution, which costs time on a busy table and hides which data the plug-in actually depends on.

Pre-images are available on PreOperation and PostOperation steps for Update and Delete. Post-images are available only on PostOperation, because before the main operation there is no saved row to take a picture of. Create has no pre-image, for the same reason. Wiremu found it helpful to think of images as a free, targeted Retrieve that Dataverse does for the plug-in at the right moment, and to treat any Retrieve of the primary row inside a plug-in as a sign that an image was missing from the registration.

The alias is a contract between the registration and the code. If someone renames the alias in PRT, the code's lookup fails silently and returns nothing, so Lumenvale kept aliases short and fixed, "pre" and "post", across every project, and the base class exposed helper methods that used those names.

Unit tests

Wiremu asked how to test a plug-in without Dataverse. Signe showed two layers. Business rules such as fee calculation should live in plain classes, like TranscriptRateReader, that take their inputs as parameters and can be tested with an ordinary test framework. The plug-in class itself can be tested with a fake execution context and a fake organization service, which several open-source testing libraries provide. Lumenvale kept the second layer small, a few tests per plug-in that checked the stage logic and the handling of missing values, and relied on testing in the developer environment for the rest.

Common mistakes

  • MistakeTargeting a modern .NET version for a plug-in project.

    InsteadTarget .NET Framework 4.6.2, as pac plugin init does.

  • MistakeMerging libraries into the assembly with ILMerge.

    InsteadUse a plug-in package so dependencies ship alongside the plug-in assembly.

  • MistakeRegistering an Update step with no filtering attributes.

    InsteadList the columns that should trigger the step.

  • MistakeKeeping secrets in the secure configuration string.

    InsteadUse Key Vault, managed identity for plug-ins and environment variables.

  • MistakeRegistering steps directly in test or production.

    InsteadRegister in development, inside the solution, and deploy the solution.

Summary and key terms

  • Plug-in projects target .NET Framework 4.6.2 and reference the Dataverse SDK; pac plugin init creates a suitable project and base class.
  • Plug-in packages deploy the plug-in assembly with its dependencies; single assemblies must be signed and self-contained.
  • PRT, launched with pac tool prt, registers packages, steps and images; pac plugin push updates registered code.
  • Steps set message, table, filtering attributes, stage, mode, order, configuration and images.
  • Registrations belong in a solution and move between environments only through deployment.
Plug-in package
A NuGet package holding a plug-in assembly and its dependent assemblies, stored in Dataverse.
Plug-in Registration tool (PRT)
Microsoft's desktop tool for registering plug-in code, steps, images and endpoints.
Filtering attributes
The columns whose change makes an Update step run.
Unsecure configuration
A step setting passed to the plug-in constructor that travels in solutions.
Secure configuration
A step setting passed to the constructor that does not travel in solutions.
pac plugin push
A CLI command that uploads a new build of an already registered package or assembly.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Which framework does a Dataverse plug-in project target?

    Show answer

    .NET Framework 4.6.2.

  2. Why are filtering attributes important on Update steps?

    Show answer

    They stop the step running for changes to unrelated columns.

  3. What must stay the same on a plug-in package after it is created in Dataverse?

    Show answer

    Its name and version; updates replace its contents.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz