MSBA-271 · Lesson 11 of 12 · 19 min

Debugging the client

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

Bronwyn, the facilities dispatcher, sent Wiremu a message one morning: the Work Order form had started showing the wrong building on new orders created from a room, but only sometimes. There was no error. Signe looked at the message and said, "Good. Today we learn to debug," and the session that followed covered the tools for finding out what client code is actually doing, rather than what its author thinks it does.

A method before tools

Debugging is a method first. Signe's version had five steps: reproduce the problem reliably, isolate the code involved, observe what actually happens, explain the cause in one sentence, and fix and confirm, including a test that would have caught it. Most wasted debugging time comes from skipping the first step and guessing at the fourth. Bronwyn's "sometimes" was the first clue: problems that happen only sometimes usually depend on timing, on data, or on which form or app is used.

A six-row table of tools. Browser developer tools: script errors, breakpoints, network calls. Monitor: form events, slow loads, Web API calls by the app. Component test harness: control output and inputs before deployment. Source maps: readable TypeScript in the debugger. Application Insights: errors and timing from real users. Solution checker: risky script patterns before import.
The client debugging toolset and what each tool is for.

Browser developer tools

Model-driven apps, code components and code apps all run as JavaScript in the browser, so the browser's developer tools are the main instrument. In Microsoft Edge or Chrome they open with F12. Four panels do most of the work.

The four developer tools panels used most.
PanelWhat it is forExample at Lumenvale
ConsoleErrors, warnings and messages written by code; running expressions against the pageReading a script error from the Work Order form
SourcesViewing loaded scripts, setting breakpoints and stepping through codePausing in the onLoad handler to inspect the form context
NetworkEvery request the page makes, with timing, headers and responsesSeeing which Web API calls the form made and what they returned
PerformanceRecording where time goes while the page worksFinding a slow render in the RoomPicker prototype

Web resources in model-driven apps are loaded from the server with their names, so they can be found in the Sources panel by searching for the file name, such as lcc_/scripts/workorder.js. Pressing Ctrl+P in the Sources panel opens a file finder. Code components and code apps are bundled, which is where source maps come in.

Breakpoints and stepping

A breakpoint pauses execution at a line so the developer can see the values of variables, the call stack and the state of the page at that moment. Set one by clicking a line number in the Sources panel. Conditional breakpoints pause only when an expression is true, such as when the building lookup is empty, which is invaluable for problems that happen only sometimes. Once paused, the developer can step over the next line, step into a function call or step out of the current function, and watch expressions in the Scope and Watch panes.

Code can also pause itself with a debugger statement. When developer tools are open, execution stops at that line as if a breakpoint were set. It is useful when a script is hard to find in the Sources panel, but it must never reach test or production; Lumenvale's linting rules in the build rejected any debugger statement.

A debugger statement used during investigation. The build rejects it, so it cannot be released.
function onRoomChange(executionContext) {
    const formContext = executionContext.getFormContext();
    const room = formContext.getAttribute("lcc_room").getValue();
    debugger; // pauses here when developer tools are open; never commit this
    if (room) {
        setBuildingFromRoom(formContext, room[0].id);
    }
}

Source maps for bundled code

Code components and code apps are written in TypeScript and bundled into one JavaScript file, often minified in release builds. Debugging the bundle directly is miserable. A source map is a file that maps positions in the bundle back to the original source files, so the Sources panel shows the TypeScript and breakpoints can be set in it. Development builds of code components include source maps; release builds normally do not, to keep them small and to avoid shipping source. For code apps, Vite produces source maps when configured to, and the same reasoning applies.

For components, the usual approach is to reproduce the problem in the test harness or in a developer environment with a development build, where the source maps are present. Wiremu also used a technique described in Microsoft's documentation and community posts: Fiddler's AutoResponder, or a similar proxy rule, which serves a local development build in place of the deployed bundle when the browser requests it. That lets a developer debug a component against real data in a test environment without deploying a new version. It requires care, and the proxy must be turned off afterwards, but for a problem that only appears with real data it can save hours.

Finding Bronwyn's problem

Wiremu reproduced the problem first. After trying several rooms, he found the pattern: the building was wrong only when the Room lookup was set by the "New Work Order" command on the Room form, not when a dispatcher picked a room by hand. That isolated the code to the form's onLoad and the room OnChange handler, which set the building by retrieving the room.

He set a breakpoint in onRoomChange and a second in the callback that wrote the building, and opened a new work order from a room. The Network panel showed two retrieve calls for room records: one for the room passed from the command, and one for the room that a default value rule set during load. Whichever response arrived last won. When the network was fast, the right one usually arrived last; when it was slow, sometimes the wrong one did. The cause, in one sentence: two asynchronous retrieves raced, and the handler wrote whichever finished last.

Ignoring stale responses so that only the latest room's building is written.
let latestRoomRequest = 0;

async function setBuildingFromRoom(formContext, roomId) {
    const request = ++latestRoomRequest;
    const room = await Xrm.WebApi.retrieveRecord("lcc_room", roomId, "?$select=_lcc_building_value");
    if (request !== latestRoomRequest) {
        return; // a newer room was chosen while this call was running
    }
    // set the building lookup from room._lcc_building_value
}

The fix ignored any response that was no longer for the latest room, and removed the conflicting default value rule, which turned out to be left over from an earlier design. Wiremu wrote the explanation into the pull request, added a Playwright test that created a work order from a room with the network slowed, and Bronwyn's problem did not return.

Monitor

Power Apps Monitor records what an app does during a session: form loads, network calls through the platform, script and business rule events, and performance markers. For model-driven apps it shows events that developer tools do not label clearly, such as which form scripts ran on load and how long each took. For canvas apps and code apps it shows data calls and their results. A developer can start a Monitor session and open the app, or ask a user to join a session, which is how the facilities team investigated problems that happened only on Bronwyn's machine. Monitor can export a session to share with a colleague.

For model-driven apps there is a related diagnostic: adding a flag to the app URL, documented by Microsoft, that shows form performance details and the handlers loaded. Signe preferred Monitor because it showed the same information with timing in one place, and because it worked for every app type the facilities team built.

Application Insights and logging

Developer tools and Monitor investigate one session. Application Insights, used in lesson 9 for the code app and in MSBA-270 for canvas apps and plug-ins, collects telemetry from many sessions over time, which is how a team finds problems no one has reported yet. For model-driven apps, Dataverse can send telemetry to Application Insights through an export configured in the admin center, including form load performance and client errors. Lumenvale's facilities environment exported to the same resource as the code app.

Client code should log carefully. Messages written to the console are visible to anyone who opens developer tools, so they must never include personal data, tokens or secrets. Lumenvale's rule was that console messages were for development only and removed by the build, and that production logging went to Application Insights with care over what was included. This is the defensive side of debugging: the information that helps a developer also helps an attacker, and should be no more visible than necessary.

Static checks: solution checker and linting

Some problems can be found without running anything. Solution checker analyses web resources and components for known problems, such as use of the deprecated Xrm.Page object, synchronous web requests that block the browser, and use of internal or undocumented APIs that may break in an update. ESLint, with the rules Microsoft publishes for Power Apps and the rules generated with a pac pcf init project, catches similar issues in the editor. Wiremu ran both in the build. Solution checker had in fact flagged the old default value rule's script months earlier, and no one had read the report.

Choosing a tool by symptom.
SymptomFirst toolThen
Error message on a formConsole for the error and stackSources to set a breakpoint at the failing line
Wrong value, no errorBreakpoints in the handlers that set itNetwork for the calls that supplied the value
Slow form loadMonitor for handler timingsPerformance panel for detail
Problem only for one userMonitor session joined by that userCheck their security role and data
Problem only in productionApplication Insights for errors and timingsA proxy rule to debug a development build safely

Worked problem

A component that fails only in canvas apps

RoomCapacity works on the model-driven Room form but shows an error in a canvas app. What should Wiremu check?

Show solution
  1. Read the error in the console; it reports that a context member is undefined.
  2. Check the manifest's uses-feature elements and the documentation: some context members, such as parts of Device and Utility, are not available in every host.
  3. Make the component check for the feature before using it, or mark the feature not required and handle its absence.
  4. Test the component in both hosts in the release checklist.

Answer: The component called a Utility method that the canvas host does not provide. Wiremu guarded the call and showed the capacity without the extra detail in canvas apps.

Debugging components in the harness and on forms

Component bugs are easiest to find in the test harness, where the developer controls every input. The harness lets the developer change property values, switch form factor and resize the container, and the component's TypeScript appears in the Sources panel through source maps, so breakpoints can be set in the original code. Wiremu reproduced most RoomCapacity problems in the harness first; only those that depended on real data or on the form needed the form itself.

On a model-driven form, the bundle loads under a name built from the component's namespace and constructor, which makes it easy to find in the Sources panel. With a development build pushed to a developer environment, source maps are present and debugging works as in the harness. With a release build, the code is minified, which is when the proxy approach described above earns its keep.

Debugging code apps locally

Code apps are the easiest of all to debug, because during development they run on the developer's own machine. Breakpoints work in the original TypeScript, and the React developer tools browser extension shows the component tree, props and state, which often explains a problem faster than stepping through code. The Network panel shows each call the generated services make through the Power Apps client library, with the request and the response, so a failing data call can be inspected directly.

Reproducing problems safely

Reproducing a problem sometimes tempts developers to copy production data into a developer environment. Lumenvale did not allow that for data containing personal information. Instead, Wiremu reproduced problems with test data shaped like the real case, and when a problem appeared only in production, he investigated with telemetry and with a Monitor session joined by the user, which shows what happened without moving data anywhere. Signe's view was that debugging is part of security, not an exception to it.

Common mistakes

  • MistakeGuessing at the cause before reproducing the problem.

    InsteadReproduce reliably, isolate the code, observe, then explain.

  • MistakeLeaving debugger statements or console logging in released code.

    InsteadUse linting to reject them in the build.

  • MistakeDebugging minified bundles.

    InsteadUse a development build with source maps, in the harness, a developer environment or through a proxy rule.

  • MistakeLogging personal data or tokens to the console.

    InsteadLog only what is needed, and send production telemetry to Application Insights with care.

  • MistakeIgnoring solution checker reports.

    InsteadRead and act on them; make them part of the release checklist.

Bronwyn noticed the fix before anyone told her. Wiremu, pleased, noticed something else: the race condition had been in a function he had written himself in lesson 2. Signe said that was the best kind of bug to find, because it was the one he would now never write again.

Summary and key terms

  • Debug with a method: reproduce, isolate, observe, explain, then fix and confirm with a test.
  • Use the browser's console, sources, network and performance panels; set breakpoints, including conditional ones.
  • Use source maps and development builds for bundled code; a proxy rule can serve a local build against real data.
  • Watch for races between asynchronous calls and ignore stale responses.
  • Use Monitor for single sessions and Application Insights for telemetry over time.
  • Run solution checker and linting, and never log personal data or secrets in client code.
Breakpoint
A marker that pauses code at a line so its state can be inspected.
Conditional breakpoint
A breakpoint that pauses only when an expression is true.
debugger statement
A line of JavaScript that pauses execution when developer tools are open.
Source map
A file mapping bundled code back to its original source files.
Race condition
A bug in which the result depends on the order in which asynchronous operations finish.
Monitor
A Power Apps tool that records the activity of an app session.

Practice problems

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

  1. Why is "only sometimes" a useful clue?

    Show answer

    It suggests the problem depends on timing, data or context, such as asynchronous calls finishing in different orders.

  2. How can a developer debug TypeScript in a deployed component?

    Show answer

    Use a development build with source maps, in a developer environment or served through a proxy rule such as Fiddler AutoResponder.

  3. What did the Network panel show in Bronwyn's case?

    Show answer

    Two retrieve calls for different rooms, whose responses could arrive in either order.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz