MSBA-272 · Lesson 3 of 12 · 19 min
Debugging plug-ins
▶ Video coming soon A video version of this lesson is on the way.
The transcript fee plug-in passed Wiremu's first tests, and Maribeth Ferreira-Quon spent an afternoon trying it in his developer environment with copies of real requests. She found two problems within the hour. A courier delivery entered in the late evening sometimes showed a fee of zero, and changing the delivery method twice in quick succession on one request occasionally produced an error about a plug-in calling itself. Neither happened on Wiremu's machine when he stepped through the logic in his head. Signe used the two bugs to teach him how plug-ins are debugged, which is different from debugging a web app, because the code runs on Microsoft's servers and no debugger can be attached to it there.
Why plug-in debugging is different
A plug-in runs in the sandbox inside Dataverse. There is no console to watch, no breakpoint to set on the server, and no log file on disk. Developers have three main tools instead: the tracing service, which writes messages to the plug-in trace log; the Plug-in Profiler, which captures the context of a real execution so it can be replayed on a developer's machine with a debugger; and unit tests with a fake context, covered briefly in lesson 2. Each answers a different question. Tracing tells you what happened in production or test. The profiler lets you step through the exact execution that failed. Tests stop the same bug from coming back.
| Tool | Where it works | Best for | Cost |
|---|---|---|---|
| Tracing service and plug-in trace log | Any environment where the trace setting allows it | Seeing the path a real execution took and the values it saw | Small; trace lines are cheap, the log has a storage cost |
| Plug-in Profiler | An environment where the profiler solution can be installed, normally development | Stepping through a captured execution in Visual Studio | Profiling changes the step temporarily; not for production |
| Unit tests with a fake context | The developer's machine and the build pipeline | Reproducing a bug once understood and preventing regressions | Writing and maintaining tests |
| System jobs view | Any environment | Failures of asynchronous steps | None; it is standard |
The tracing service
Every plug-in can get an ITracingService from the service provider and call Trace with a format string and values. Trace messages are collected during the execution. If the plug-in throws an exception, they are shown in the error details that the user can download from the error dialog. If tracing is turned on for the environment, they are also written to the plug-in trace log, a Dataverse table that administrators and developers can view.
Trace output is limited in size per execution; Microsoft documents that if it is too long, only the latest part is kept. That makes short, structured traces more useful than long dumps. Signe's convention, written into the Lumenvale base class, was one line at the start with the message, table, stage, depth and correlation ID, one line per decision with the values that drove it, and one line at the end with the result. She asked for values, not commentary: "method 3, rate row found, effective 2026-11-01, fee 18.00" told her more than "calculating fee now".
local.Trace("Start {0} {1} stage {2} depth {3} corr {4}",
ctx.MessageName, ctx.PrimaryEntityName, ctx.Stage, ctx.Depth, ctx.CorrelationId);
local.Trace("Method {0}; graduation date {1:yyyy-MM-dd}; as-of {2:o}",
method.Value, graduated, asOf);
local.Trace("Rate row {0}; effective {1:yyyy-MM-dd}; amount {2}",
rate?.Id, rate?.GetAttributeValue<DateTime>("lcc_effectivefrom"), fee.Value);Traces must not contain personal data. A trace log is readable by anyone with access to the Plug-in Trace Log table, which at Lumenvale meant developers and administrators, and its content can end up in support tickets. Student numbers, names, dates of birth and addresses stay out of traces. Row IDs, choice values and amounts are fine. Dr. Philippa Ondaatje-Ruiz, the privacy officer, had asked for this rule after reviewing the facilities inspection solution in MSBA-250, and it applied to all code.
Turning on the trace log
Whether traces are written to the log depends on an environment setting, Enable logging to plug-in trace log, with three values: Off, Exception and All. Off writes nothing. Exception writes traces only for executions that throw. All writes traces for every execution of every plug-in and custom workflow activity.
| Setting | What is logged | Lumenvale use |
|---|---|---|
| Off | Nothing | Not used; even failures leave no record |
| Exception | Traces from executions that throw an exception | Test and production by default |
| All | Traces from every execution | Developer environments, and briefly in test to chase a specific bug |
Signe warned against leaving All on outside development. On a busy table it writes a row for every save, which adds storage and makes the log hard to search. Trace log rows are also removed automatically after a short period, so the log is a tool for recent investigation, not an archive. If evidence needed to be kept, a developer copied what mattered into the work item before it disappeared.
The log is viewed in the Plug-in Trace Log list in the classic advanced settings area or queried like any table, through the Web API or a tool such as XrmToolBox's plug-in trace viewer, which Lumenvale's developers used. Each row records the plug-in type, message, table, stage, mode, depth, correlation ID, duration, the trace text and any exception details.
Bug one: the zero fee at night
Wiremu set his developer environment to All, asked Maribeth to repeat the evening courier case, and found the trace within a minute. The trace showed an as-of time of 04:12 the next morning, a rate row search that found nothing, and a fee of zero from a fallback he had added "just in case". The cause was visible in the values. The rate for courier delivery had been raised on November 1, entered by the registrar's office as a date-only column with the behavior set to user local. The plug-in compared it with DateTime.UtcNow. For a few hours each evening in Boise, the UTC date was already the next day, and on the evening of a rate change the comparison fell into a gap where the old rate had ended and the new one appeared not to have started.
Two fixes were needed. The first was the real one: the rate table's effective dates were changed to the Date only behavior, which stores a calendar date without any time zone conversion, and the plug-in compared them with the request's submitted date converted to the college's local date. The second was to remove the fallback. A fee of zero was worse than an error, because nobody would notice it. If no rate row matched, the plug-in now threw an InvalidPluginExecutionException asking the user to contact the registrar's office, and traced the delivery method and date it had searched for.
Signe pointed out that the trace had made the fix obvious only because it recorded the as-of time and the search result. A trace that said "fee calculated" would have left Wiremu guessing.
The Plug-in Profiler
The second bug was harder to read from traces, because it involved several executions interacting. For this Signe used the Plug-in Profiler, which is part of PRT. The profiler is installed into an environment as a solution from PRT's toolbar. Once installed, a developer selects a step and chooses to start profiling. PRT changes the registration so that the next time the step runs, the profiler captures the complete execution context, including the input parameters, images and the results of every organization service call the plug-in makes.
The capture can be stored in two ways. In exception mode the profiler makes the step throw, and the profile is returned to the user in the error details to download. In persist mode the step runs normally and the profile is saved to a table in the environment. Persist mode is far less disruptive and was the only mode Lumenvale used.
To debug, the developer opens Visual Studio with the plug-in project, sets breakpoints, and attaches the debugger to the PRT process. In PRT they choose Replay Plug-in Execution, select the captured profile and the local build of the assembly, and start the replay. PRT runs the plug-in code on the developer's machine with the recorded context, and the debugger stops at the breakpoints. Organization service calls are not sent to Dataverse during replay; their recorded responses are returned instead, which means replay is safe and repeatable but cannot show how a code change would affect the server's answers.
When the debugging session is over, the developer must stop profiling the step in PRT, which restores the original registration, and should uninstall the profiler solution from the environment when it is no longer needed. Signe had once found a step in a shared test environment that had been left profiled for weeks and was quietly writing profile rows on every save. Microsoft also documents a limit relevant to the next lesson: the profiler cannot be used on the main operation of a custom API, so custom API logic is debugged by tracing and by unit tests, or by putting the logic into a class that can be exercised from a test harness.
Bug two: the plug-in that called itself
Wiremu profiled the Update step and asked Maribeth to change the delivery method twice. The replay showed a depth of 1 on the first execution and a depth of 2 on a second one triggered from inside the first. Stepping through, he found the cause. In an early refactoring he had moved part of the logic to PostOperation and called Update on the transcript request to store a "fee last calculated" timestamp. That update included the fee column, and the step's filtering attributes had briefly included the fee column too, because a colleague had added it while testing something else. Each execution updated the row, which triggered the step again.
Dataverse detects plug-ins that keep triggering each other and stops the chain with an error, which is what Maribeth had seen. The fix had three parts. The timestamp moved into the PreOperation logic and was set on the Target, so no separate update was needed. The filtering attributes were restored to the two columns that should trigger a recalculation. And the code gained a guard: if the fee it calculated equalled the fee already on the row, it did not set the column at all, which kept the update small and avoided unnecessary audit history.
Signe was careful about the guard Wiremu proposed first, which checked whether Depth was greater than 1 and returned immediately. A depth check stops recursion, but it also stops the plug-in from running when its operation is legitimately caused by another plug-in or a flow, which happens often. A request created by the bulk import, for example, might arrive at depth 2 if another step created it. Depth checks were acceptable only with a comment explaining which chain they were meant to break, and only after filtering attributes and change checks had been considered.
Worked problem
Reading a failed asynchronous step
A week later, an asynchronous PostOperation step that wrote an audit row when a request reached Sent stopped working in Wiremu's environment. Users saw no error at all. How should he find out what happened?
Show solution
- Remember that asynchronous steps run as system jobs, so their failures are recorded on the system job, not shown to the user.
- Open the system jobs view, filter to failed or waiting jobs for the plug-in, and open the latest one. The message and the trace text are on the job.
- If the job shows a permission error, check which user the step runs as; asynchronous steps run in the context set on the step, which may differ from the user who triggered it.
- Fix the cause, then resume or retry the waiting jobs if their work still needs doing.
Answer: Look in system jobs, not in the user interface. The job held an error about a missing privilege on the audit table, because the step ran as a user without create access. Granting the correct role fixed it.
Turning bugs into tests
Once each bug was understood, Wiremu wrote a unit test that reproduced it before he wrote the fix. The time zone bug became a test that passed a rate effective on November 1 and a request submitted at 9 p.m. local time on October 31, and asserted the old rate. The recursion became a test that confirmed the plug-in made no organization service Update calls. Both tests failed before the fix and passed after it, and both ran in the GitHub Actions build on every pull request from then on.
Common mistakes
MistakeLeaving the trace log on All in test or production.
InsteadUse Exception by default and All only briefly to investigate.
MistakeWriting student names or numbers into traces.
InsteadTrace IDs, choice values and amounts, never personal data.
MistakeUsing a zero or blank as a silent fallback when data is missing.
InsteadThrow a clear error and trace the values that were searched for.
MistakeLeaving a step profiled after debugging.
InsteadStop profiling in PRT and uninstall the profiler when finished.
MistakeFixing recursion with a blanket Depth check.
InsteadFix filtering attributes and avoid self-updates; use Depth only with a documented reason.
Summary and key terms
- Plug-ins cannot be debugged on the server; developers rely on tracing, the Plug-in Profiler and unit tests.
- The tracing service writes messages that appear in error details and, depending on the environment setting, in the plug-in trace log.
- The trace log setting is Off, Exception or All; use Exception outside development.
- The profiler captures a real execution and replays it locally in Visual Studio through PRT; it cannot target a custom API's main operation.
- Asynchronous failures appear in system jobs; recursion is fixed with filtering attributes and avoiding self-updates.
- Tracing service
- The ITracingService that collects diagnostic messages during a plug-in execution.
- Plug-in trace log
- A Dataverse table that stores trace output when logging is enabled.
- Plug-in Profiler
- A PRT feature that captures an execution context for local replay with a debugger.
- Persist mode
- A profiler setting that saves the captured profile to a table without making the step fail.
- Correlation ID
- An identifier shared by all executions that result from the same original request.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Which trace log setting should a production environment normally use?
Show answer
Exception.
During a profiler replay, are organization service calls sent to Dataverse?
Show answer
No. The recorded responses are returned.
Where do failures of asynchronous steps appear?
Show answer
On the system job records.
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.