Sam's Dynamics, Power Platform & AI Blog

Friday, 2 October 2026

Display Density in Model-Driven Apps: Less Whitespace, More CRM

 If you work with Dynamics 365, you've heard this one: "Why is there so much empty space on the screen?"

Microsoft now has an answer. It's called Display Density, and it's in preview for model-driven apps.

What it does

It tightens the gaps between fields, rows and buttons, so you see more on one screen and scroll less. The buttons and fields stay the same size. Only the space around them shrinks.

The three choices

  • Comfortable: what you have today
  • Cozy: a little tighter
  • Compact: the most on one screen

How to switch it on

Go to Settings, then Personal settings, then Appearance, then Display density.

Can't see the Appearance tab? The app's new header and navigation isn't turned on yet.

Good to know

  • Admins and makers can set a default, but each user's own choice wins.
  • Some controls don't tighten up yet, including custom PCF controls with fixed spacing. Test yours.
  • It's a preview. Microsoft expects general availability around November 2026.

Why it matters for AI

When the Copilot pane is open, your form gets narrower. Compact gives some of that room back.

Sources: Microsoft Learn and the message center notice.

Thanks for reading this article. Hope this Article will help you. Cheers!!!

Thursday, 1 October 2026

Under the Hood of the New Copilot: Managed Runtime, Agent Identity and Copilot Credits

A technical guide for Dynamics 365 and Power Platform architects

My last post covered what Microsoft announced on 25 September. This one is about how it works: where the code runs, which identity the agents use, how Copilot gets its grounding, and who pays for what. Most of this is in preview, so treat it as a map for planning, not production guidance.




1. The architecture in one picture

Here's how I'd sketch the new stack, top to bottom:


The three experiences sit at the top. Everything else is plumbing, and the plumbing is where architects need to pay attention.

2. Copilot Managed Runtime: where generated code actually runs

When someone builds an app in Code, it has to be hosted somewhere. That's what Copilot Managed Runtime is for. Microsoft put it into public preview as a platform that runs code within the Microsoft 365 tenant boundary, governed by IT, while keeping features users expect such as sharing, live data connections and easy access to their apps.

Key technical points:

  • Built-in auth and connectors. Apps built with the SDK include Microsoft Entra authentication without any custom code and can connect to more than 1,500 data sources, including Microsoft Graph, SQL and SharePoint.
  • Source control by default. The platform provisions a managed Git repository when you create an app, so no extra setup is needed. You can also connect your own GitHub repo.
  • Multiple entry points, one host. The Microsoft entry points are already live in Copilot Cowork, Copilot Code and Copilot Studio, and developers can use the SDK and plugins to build apps for the same host.
  • Central inventory. Hosted apps show up in a new Apps experience in the Microsoft 365 admin center, where admins can review access, usage, health and policy in one place.

For pro developers, the tooling is a CLI and an SDK on npm:

bash
# Copilot Managed Runtime CLI (preview)
npm install -g @microsoft/managed-apps-cli
ms --version

# SDK package used inside the app
@microsoft/managed-apps

Why this matters for Power Platform people: if you've worked with Power Apps code apps, this will feel familiar. One community write-up describes Managed Runtime as the name for what Code Apps was growing into, with the admin home moving from the Power Platform admin center to the Apps node in the Microsoft 365 admin center. That's a real shift in where makers' work gets governed. Your CoE team needs to look at both admin centres from now on.

My design rule: a Code app is a UI and logic layer. Customer, case and opportunity data should still live in Dataverse, where your security model, auditing and business rules already apply. Before you let teams build against CRM data, check in your own tenant which connector path they'll use to reach Dataverse.

3. Autopilot and agent identity

Autopilot is the piece that changes the security conversation.

Autopilot takes a role and a goal from the person who sets it up, then keeps working in the background without needing a new prompt for each step. Each Autopilot gets its own governed Entra identity and agent user account, which separates the agent's permissions and activity from those of its creator.

This builds on Microsoft Entra Agent ID, which Copilot Studio developers have been dealing with for months:

  • An Entra Agent ID is a Microsoft Entra service principal with an "Agent" subtype.
  • Since May 2026, Copilot Studio automatically creates an Entra Agent ID for each new agent. Before that, it created an Azure app registration per agent.
  • No one in your tenant, including tenant administrators, can generate tokens using the agent identity.
  • Every Agent ID is a directory object and counts against your tenant's Entra resource quota. If you hit the quota, agent creation fails.

A practical detail that's easy to miss: according to TechGig, as reported by Windows Forum, an Autopilot agent's governed Entra identity doesn't automatically come with email, a calendar or OneDrive. The model separates the agent identity (a service principal) from an optional agent user account that's flagged as an AI agent and needs licences.

What this means for Dataverse: an agent with its own identity is a new principal that needs access to your CRM. Before Autopilot or any persistent agent touches Dynamics 365, decide:

  1. Which identity reaches Dataverse? The agent's own identity (an application user with a dedicated security role), or the signed-in user's identity passed through? These give very different audit trails.
  2. What's the minimum security role? Start with read-only access on the specific tables the agent needs. Don't copy a human user's role.
  3. Which business unit owns it? Business unit scoping decides which records the agent sees. Get it wrong and you'll leak data across regions or divisions.
  4. Field-level security. Sensitive columns such as pricing, margins and personal data should be protected by column security profiles, not by hoping the prompt avoids them.
  5. Human sign-off. Microsoft says each agent runs with scoped credentials, approved-destination limits, optional human sign-off and Purview enforcement. Use the sign-off option for anything that writes to CRM.

Where to look:

  • Power Platform admin center → Copilot → Settings → Entra Agent Identity for Copilot Studio to enable agent identities for Copilot Studio agents
  • Microsoft Entra admin center → Agent ID to audit every agent identity in the tenant
  • Power Platform inventory, which exposes per-agent fields such as whether the agent is part of a managed Dataverse solution. That's useful for checking that your agents went through proper ALM.

4. Grounding: Work IQ, Fabric IQ and the Plugin Registry

Microsoft says Copilot will draw more fully on organisational data, business processes and applications through Fabric IQ, Work IQ and a new Plugin Registry.

  • Work IQ is the Microsoft 365 context layer. Its REST API lets custom apps hold multi-turn conversations with Microsoft 365 Copilot using enterprise and web search grounding, without building and maintaining your own vector indexes and orchestration. For developers, there's also an open-source plugin collection that connects GitHub Copilot to Microsoft 365 data through MCP servers and skills.
  • Fabric IQ grounds Cowork on Power BI reports and their semantic models, but not yet on dashboards, paginated reports, lakehouses or eventhouses. One detail I like: sensitivity labels on the source data are respected, and new content Cowork creates inherits the label of the Power BI item it was grounded on.
  • Plugin Registry: a plugin packages one or more capabilities, such as skills, MCP servers or agents, so Copilot can support your organisation's own workflows. Work IQ Developer Tools (WIQD) helps you package existing work into a plugin and publish it to the registry.

The Dynamics angle: if you already have Dataverse-backed logic, such as a Custom API, an MCP server or a Copilot Studio agent, the Plugin Registry is the route for making it available in Home and Cowork. Don't rebuild it from scratch. For reporting questions, a well-modelled Power BI semantic model on top of Dataverse now does double duty as Copilot's grounding through Fabric IQ. One more reason to invest in a clean data model.

5. Copilot Credits: cost becomes architecture

Billing has two layers. The user licence covers Copilot in Chat, Word, Excel, PowerPoint, Outlook and Teams. Usage-based billing applies to Cowork, Code, Autopilot and long-running agent work.

Key mechanics:

  • Cowork usage counts model responses, tool and skill calls, image generation and browser tasks. Admins can set per-user or per-group limits.
  • Credits are managed in two places: the Microsoft 365 admin center (Cost Management) for Cowork and the Work IQ API, and the Power Platform admin center for Copilot Studio agents and environment allocation.
  • Copilot Credits are pooled at the tenant level, and Microsoft's own guide lists Dynamics 365 agents among the experiences that consume them.
  • Managed Runtime apps consume credits each time an app launches and for each API call.
  • At the time of writing, one credit is $0.01 at pay-as-you-go rates, with discounts for pre-purchase.

Design implications:

  • Chatty agents cost money. An agent that polls Dataverse every few minutes looking for work costs more than one triggered by an event. Use Dataverse events, plugins or Power Automate triggers to wake the agent instead.
  • Keep deterministic logic out of the LLM. If a rule can be a plugin, a business rule or a calculated column, don't make an agent "reason" through it on every run. That was already good design. Now it's also cheaper.
  • Set budgets before go-live. Admins should set tenant, group and user budgets and spend alerts before a continuously running agent starts consuming credits.

6. Pre-flight checklist for CRM teams

Before Code and Autopilot reach your tenant, I'd work through this list:

  • Inventory existing agent identities in the Entra admin center
  • Review Dataverse security roles that any agent or app user will receive
  • Apply field-level security to sensitive CRM columns
  • Decide which environments and connectors Code apps may use, and align DLP across the Power Platform and Microsoft 365 admin centres
  • Set up Copilot Credit budgets, per-group limits and alerts
  • Agree an ALM path: agents and apps in managed solutions or Git, not built directly in production
  • Clean up duplicate and stale CRM data before an always-on agent starts acting on it
  • Pick one pilot use case with a measurable outcome and a named owner

7. Availability, as of today

Home and Code are coming to testers through the Frontier program over the coming weeks, and Autopilot moves into private preview at the end of this month. Frontier needs a Microsoft Copilot licence and has to be turned on by an IT admin. Copilot Managed Runtime is already in public preview.

Previews change, so check the Microsoft Learn pages on the day you configure anything.

Final thoughts

The headline features are Home, Code and Autopilot. The real story is underneath: a governed runtime for generated code, a first-class identity for every agent, a plugin model for grounding, and a meter on everything agentic.

For Dynamics 365 architects, none of this replaces the fundamentals. It raises the stakes on them. Security roles, data quality, ALM and cost-aware design are what decide whether these tools help your organisation or create a mess that's hard to clean up.

I'll test these hands-on as they land and post what I find. If you're planning agents on top of Dynamics 365 and want help with the design, feel free to reach out.

Sources:

Thanks for reading this article. Hope this Article will help you. Cheers!!!

#Dynamics365 #PowerPlatform #MicrosoftCopilot #DynamicsCRM #CopilotStudio #Dataverse #AIDeveloper #DynamicsAIEngineer #HireAIEngineer #AIEngineer #D365Consultant #CRMDeveloper #AIAgents #MSDyn365

The New Copilot: Home, Code and Autopilot. What It Means If You Build on Dynamics 365 and Power Platform

 On 25 September, Microsoft announced what it calls the new Copilot. I've read through it with one question in mind: what changes for those of us who design and build business apps on Dynamics 365, Dataverse and Power Platform?

The short answer is quite a lot. Most of it isn't about new buttons, though. It's about who builds things, where agents run, and how the bill gets paid.

What Microsoft actually announced

The new Copilot is organised around three spaces. Home brings Chat and Cowork together in one central place, and Microsoft is also building Word, Excel and PowerPoint directly into Copilot. Code lets users build apps and automations in natural language. It's based on the same technology as GitHub Copilot and is aimed at helping non-developers create their own solutions inside their organisation's environment. Autopilot is the newest piece. It was previously called Scout, and it's an always-on personal agent that lives in its own tab in the Copilot app. New Microsoft Copilot Brings Home, Code, and Autopilot Together - Source EMEA +2

Under the hood, Microsoft is improving Copilot's grounding with Fabric IQ, Work IQ and a new Plugin Registry so it can draw more fully on organisational data, processes and applications. microsoft

Code: the citizen-developer story gets a new front door

For years, "build it yourself" in the Microsoft world meant Power Apps and Power Automate. Code now offers a second route, starting from a sentence instead of a canvas.

The part I'd pay most attention to is hosting. Microsoft is introducing Copilot Managed Runtime, which hosts code inside a Microsoft 365 environment. It will support apps built in Cowork, Code and Copilot Studio, and it's also being opened to third-party and professional developers. channellife

For CRM teams, I see three practical questions:

  • Where does the data live? An app built in Code still needs a system of record. For customer data, that should still be Dataverse, not a new spreadsheet hidden behind a nice UI.
  • Who governs it? Your Power Platform CoE, environment strategy and DLP policies were built for makers. You'll want the same discipline here before people start shipping apps from chat.
  • Who maintains it? "Anyone can build" also means anyone can leave the company. Ownership and ALM don't go away because the code was generated.

Autopilot: an agent with its own identity

This is the change I think matters most for architects. Microsoft says Autopilot is cloud-hosted and operates with its own identity, memory, computer and workspace inside a customer tenant. channellife

An agent with its own identity is an agent that needs permissions. If it can work across your tenant while nobody is watching, then Dataverse security roles, business units, field-level security and column-level access stop being "nice to have". They become the actual guardrails. I covered this in an earlier post on what a Copilot agent can actually see. Autopilot makes that question more urgent, not less.

It's also why data quality matters. An always-on agent working from duplicate accounts and stale opportunities will do the wrong thing confidently and quickly.

The billing change is a design decision

A user subscription licence covers Copilot in Chat, Word, Excel, PowerPoint, Outlook and Teams, while usage-based billing applies to Cowork, Code, Autopilot and long-running agentic capabilities. Microsoft's admin documentation describes Copilot Credits as a common currency for eligible services billed by usage. technobezzdev

For consultants, that means estimating agent usage becomes part of the solution design, the same way we already think about API limits and Dataverse capacity. "Should this be a plugin, a flow or an agent?" now has a cost dimension as well as a technical one.

When can you use it?

Not quite yet for most people. Home and Code will reach testers through the Frontier program in the coming weeks, while Autopilot moves into private preview at the end of this month. Frontier requires a Microsoft Copilot licence and has to be switched on by an IT admin. Microsoft has also previewed things still to come, including Today in Home and @Copilot in Teams. Microsoft Adds Home, Code and Autopilot to Copilot +2

My take

For years the question was "how do I add AI to my CRM?" With this release, Microsoft is turning that around. Copilot becomes the place where work starts, and the CRM becomes one of the systems it reaches into.

That doesn't make Dynamics 365 less important. It makes the foundations more important: clean data, a sensible security model, proper ALM and governance that keeps up with the people now able to build. Those are the things to get right before Code and Autopilot reach your tenant.

I'll be testing these as they become available and writing up what holds up in real projects. If you're planning a Copilot or agent rollout on Dynamics 365 and want a second pair of eyes, get in touch.

Sources:


Thanks for reading this article. Hope this Article will help you. Cheers!!!


#Dynamics365 #PowerPlatform #MicrosoftCopilot #DynamicsCRM #CopilotStudio #Dataverse #AIDeveloper #DynamicsAIEngineer #HireAIEngineer #AIEngineer #D365Consultant #CRMDeveloper #AIAgents #MSDyn365


Wednesday, 30 September 2026

Generative pages in Power Apps: building model-driven pages from a prompt

Generative pages in Power Apps

You describe a page, and the agent writes React code for both the UI and the logic behind it. Think of it as a custom page where you don't need Power Fx.


Two ways to build

  • Browser — make.powerapps.com, conversational, no setup
  • Code tools like GitHub Copilot CLI — Microsoft's recommended route: newer models, works worldwide, and one request can build multiple pages plus the Dataverse tables they need


Before you start

  • Environment must be in the US, Great Britain, Australia or Singapore — otherwise the option won't appear and you'll need the code-tools route
  • Browser prompts are US English only
  • No extra AI or message credits needed

Build it

  1. App designer → Add page → Generative page → Describe a page
  2. Prompt with functional requirements first, then UX — name the columns
  3. Add data → Add table — max six Dataverse tables
  4. Optionally attach a sketch or wireframe
  5. Generate page

The agent shows its plan first — requirements and assumptions — then writes, transpiles and renders. Check the assumptions before iterating. Fixing a bad plan later costs more.

Iterate

  • Chat with the agent, or Edit on the Code tab — your edit saves as a new iteration
  • Compare diffs iterations, but only from the second iteration in the current session
  • The accessibility assistant scans each iteration; Auto fix hands violations back to the agent

Patterns worth knowing

  • Inputs: pages accept recordId, entityName and data — say so in the prompt and the agent writes the init code
  • Form embedding: form designer → Components → Display → Generative page. The record ID is passed in automatically, no config needed. This is the one I'd use most
  • Navigation: open a page with Xrm.Navigation.navigateTo, passing parameters
  • Data: everything goes through the dataApi object — read what it's calling
  • Connectors (preview): create a connection, then a connection reference in the Default Solution, and it appears under Add data → Connectors. Not for production yet

ALM

  • Solution-aware — add the app and sitemap; pages come across as UX Agent Project rows via the sitemap dependency
  • Missing from the dependency check? Make a small sitemap change, republish, export again
  • Only the first prompt and published code move to the target — the conversation stays behind. Write your intent down somewhere else

Limits

  • 50,000-character prompt maximum
  • One maker per page at a time
  • Model-driven apps only
  • Fixed list of supported column types — check before designing around anything unusual


My take

Microsoft is explicit: validating the generated code is your job. Check the dataApi calls, and make sure no rule that must hold has ended up in browser code. That belongs in a plugin.

Use it for dashboards, card galleries, Kanban boards and record panels on forms. Keep PCF for reusable field-bound controls and anything performance-sensitive.


Thanks for reading this article. Hope this Article will help you. Cheers!!!

Related Article: https://learn.microsoft.com/en-us/power-apps/maker/model-driven-apps/generative-pages


 #Dynamics365 #PowerPlatform #MicrosoftCopilot #DynamicsCRM #CopilotStudio #Dataverse #AIDeveloper #DynamicsAIEngineer #HireAIEngineer #AIEngineer #D365Consultant #CRMDeveloper #AIAgents #MSDyn365



Thursday, 17 September 2026

Testing a Copilot agent: evaluation, not "it seemed to work"



Given input, expect output works for a plugin. Agent responses depend on prompt, retrieval and context interpretation, so you measure response quality and task alignment, not correctness.


Test sets. Built into Copilot Studio. Up to 100 cases per set — hand-written, spreadsheet import, or AI-generated. Quick set: 10 questions from the agent's description and instructions. Full set: up to 100 from knowledge sources or topics.

The generator reaches knowledge sources using the connected account's credentials, so generated cases can contain sensitive data that account can see. Review before sharing the set.

Grading. Every method except general quality needs expected responses or keywords — writing down what a good answer looks like is the actual work. Custom Graders (classification method) encode your own policies where built-in dimensions don't fit.

Test user profiles. Evaluations run under a designated test account, and that account connects to knowledge sources and tools during the run. Testing as yourself proves nothing about what a sales rep sees. Simulate profiles to check behaviour across roles and access levels.

Limits: GCC can't add user profiles to test sets and doesn't support the similarity method. User-auth evaluations need the Copilot Studio connector enabled.

Automation. Results live 89 days — export CSV for anything auditable. REST API triggers evaluations programmatically for release validation and CI/CD regression runs.

Copilot Studio Kit goes deeper: tests via Direct Line API, enriched from Application Insights and Dataverse transcripts, so you get triggered topic and intent recognition scores behind each pass or fail. Multi-turn tests, and pipeline gating — deploy pauses, tests run, thresholds checked, then promote.

What goes in the set:

  • Questions users actually ask, badly phrased ones included
  • Every bug that ever shipped, permanently
  • Questions the agent should refuse or escalate
  • The same question from two profiles where correct answers differ
  • Anything near column-secured fields

Correction to the ALM post. I said keep a manual list of twenty questions and run it after each deploy. Right instinct, wrong implementation — put them in a test set, grade them, run them from the pipeline.

Related: Copilot in Dynamics 365 — what it actually does


Thanks for reading this article. Hope this Article will help you. Cheers!!!

#Dynamics365 #PowerPlatform #MicrosoftCopilot #DynamicsCRM #CopilotStudio #Dataverse #AIDeveloper #DynamicsAIEngineer #HireAIEngineer #AIEngineer #D365Consultant #CRMDeveloper #AIAgents #MSDyn365

Monday, 14 September 2026

Packaging and Deploying Web Resources: A Practical ALM Workflow for Dynamics 365 JavaScript

You've written the script. You've unit-tested the logic and stepped through it in dev tools. It works perfectly on your form. Now comes the part that trips up more Dynamics 365 projects than any bug ever does: getting that script safely out of your dev environment and into production without breaking something else on the way.

This post is about the plumbing — solutions, environment variables, and a repeatable release process — rather than more JavaScript syntax. If you've been following the series, think of it as the missing link between "my script works" and "my script is live, and I can update it again next sprint without a two-hour outage window."

Web resources live in a solution — always

A web resource that exists only in your dev environment isn't deployable. The first rule of ALM in Dynamics 365 is simple: every JavaScript file, every image, every HTML web resource you build has to sit inside an unmanaged solution in dev, so it can be exported and carried forward.

Create one solution per project or product area — not the Default Solution — with your own publisher and a prefix:

Publisher: Contoso CRM Team
Prefix: con_

Web resource name: con_/scripts/opportunity.form.js
Web resource name: con_/scripts/lib/discountLogic.js

Notice the folder-style naming. Dynamics doesn't enforce folders, but the "/scripts/", "/styles/", "/images/" convention inside the name keeps a solution with 40+ web resources from turning into an unreadable flat list. Pick a convention on day one — renaming a web resource later means updating every form event handler that references it by name.

Stop hardcoding URLs and GUIDs

This is the single most common thing I see go wrong in a promotion from dev to test to production: a script with a hardcoded environment URL, flow trigger endpoint, or record GUID baked directly into the code.

// don't do this
const flowUrl = "https://prod52a1.environment.api.powerplatform.com/powerautomate/...";
const escalationTeamId = "3f9a1c20-...-...-...-prodonly";

That script works in production and breaks the moment someone imports the same managed solution into UAT, because the flow URL and team GUID are different there. Use environment variables instead — a Dataverse table type built exactly for this. Define the environment variable in your solution, give it a default value for dev, and set the current value per environment after import (test, UAT, and prod each get their own).

// do this instead
async function getEnvVarValue(schemaName) {
  const result = await Xrm.WebApi.retrieveMultipleRecords(
      "environmentvariabledefinition",
          `?$filter=schemaname eq '${schemaName}'&$expand=environmentvariabledefinition_environmentvariablevalue($select=value)`
            );
              const def = result.entities[0];
                const values = def.environmentvariabledefinition_environmentvariablevalue;
                  return values && values.length ? values[0].value : def.defaultvalue;
                  }
                  
                  const flowUrl = await getEnvVarValue("con_DiscountApprovalFlowUrl");

Yes, it's a couple more lines than a hardcoded string. It's also the difference between a 30-second solution import and a support ticket at 5pm on a Friday because someone forgot to swap a URL by hand.

A release path you can actually repeat

The environments-and-arrows diagram is familiar to anyone who's worked on a real project, but the part people skip is making it boring — the same steps, every time, ideally without a human retyping anything:

Dev (unmanaged)
  → export as MANAGED solution
      → import into Test/UAT
            → validate, set environment variable values
                    → export the same version as MANAGED
                              → import into Production
                                          → set production environment variable values

A few rules that keep this from going sideways:

Only your dev environment is unmanaged. Every downstream environment gets a managed solution. Managed solutions can't be casually edited in the target environment — which is exactly what stops someone from "just quickly" fixing a bug directly in production and having it silently overwritten by the next real release.

Bump the solution version every release (1.0.0.3, 1.0.0.4...) so you can tell at a glance what's actually deployed in each environment, and so a re-import doesn't get silently skipped as "no changes detected."

Never hand-edit a web resource inside the target environment's UI. If test or production needs a change, it goes back through dev, gets re-exported, and flows down the same path. The moment someone edits a web resource directly in production "just this once," your source of truth splits in two.

Keep the actual JavaScript in source control

The solution zip is not source control. Treat the Dataverse web resource as a deployment target, not the place your code lives. The workflow that scales:

1. Write/edit the .js file in your repo (VS Code, real linting, real diffs)
2. Use the Power Platform CLI to push it straight to your dev web resource:

   pac webresource push --file ./src/opportunity.form.js `
        --solution ConCrmTeamSolution --publisher con
        
        3. Commit the .js file to git like any other source file
        4. When it's time to release, export/pack the SOLUTION (not the .js file) via:
        
           pac solution export --name ConCrmTeamSolution --managed
              pac solution unpack --zipfile ConCrmTeamSolution.zip --folder ./solution --packagetype Managed

Once the unpacked solution folder is in git alongside your web resource source, a pull request actually shows you a meaningful diff — not a base64 blob — and code review on a form script becomes possible for the first time.

Cache is the silent killer of "but it worked in dev"

You imported the solution, the web resource clearly has your new code in the customizations, and the form still runs the old logic. Nine times out of ten, that's the browser serving a cached copy of the .js file. A few things that actually fix it, in order of how often I reach for them:

Do a hard refresh (Ctrl+Shift+R / Cmd+Shift+R) on the form before assuming your deployment failed. If it's happening to your whole team repeatedly after every release, increment a version query string convention in how the web resource is referenced, or use the "Publish All Customizations" step deliberately — a solution import doesn't always auto-publish everything, and an unpublished web resource will serve the old version even though the record itself shows the new content.

A short pre-flight checklist

Before you ship a form script anywhere past dev, it's worth running down a short list rather than trusting memory:

Is the web resource actually included in the solution (added web resources don't auto-include just because they exist)? Are there any hardcoded URLs, GUIDs, or environment-specific values left in the code? Does the target environment already have its environment variable values set, or will the script silently fail on first load after import? Did you bump the solution version? And — the one everyone forgets at least once — did you publish?

Where this leaves you

None of this is exciting the way a working Copilot Studio integration is, but it's the reason that integration keeps working three months from now, across three environments, maintained by more than one person. A script that only exists correctly in your head and your dev environment isn't shipped — it's a demo.

Next in the series, we'll go back to the form itself and look at ribbon and command bar customization with JavaScript — enable rules, custom buttons, and the display rules that decide when a command even shows up.

Ribbon and Command Bar Customization with JavaScript in Dynamics 365

Everything so far in this series has lived inside the form body — fields, lookups, Web API calls, agent responses. This post moves up one level, to the command bar sitting above all of it: the Save button, the ribbon buttons, the custom "Send for Approval" or "Escalate to Manager" buttons that show up (or don't) depending on the state of the record. That behavior is driven by JavaScript too, and it trips people up in a different way than form scripting does, because the wiring is less obvious.

Two ways to control a button, and why this post is about the JS one

Dynamics 365 gives you two paths to command bar logic. The modern command bar designer lets you write simple Power Fx-style formulas directly against a button's Visible and Enabled properties — no code, no web resource, good enough for straightforward conditions. The classic path — Enable Rules and Display Rules backed by a JavaScript function — is what you reach for when the condition is genuinely complex: multiple entity checks, a Web API call to decide visibility, or logic you want to unit test the same way you'd test any other function in this series.

This post covers the JavaScript path, because that's where the interesting problems are.

Enable Rules vs Display Rules — they are not the same thing

A Display Rule decides whether a button appears at all. A Enable Rule decides whether a button that's already visible can be clicked — a visible-but-greyed-out state. Mixing these up is the single most common ribbon bug: a button that a user can see and click, but that silently does nothing because the actual intent was to hide it until certain conditions were met, not just enable it.

Both rule types point at a JavaScript function with the same signature — Dynamics calls it a CommandChecker function — and both must return a plain boolean.

function canSendForApproval(primaryControl) {
  var formContext = primaryControl;
    var status = formContext.getAttribute("statuscode").getValue();
      var isDirty = formContext.data.getIsDirty();
      
        // only show/enable once saved and still in Draft
          return status === 1 && !isDirty;
          }

Notice the parameter isn't literally "the form" — it's whatever you configured as a CRM Parameter when you wired the rule up in the Ribbon Workbench (or classic solution ribbon editor). PrimaryControl is the one you'll use constantly, because it gives you the same formContext-shaped object you already know from every other post in this series — getAttribute, getValue, ui, all of it.

A realistic enable rule: role- and state-aware

Real conditions are rarely just one field check. Here's a button that should only be enabled for the record owner, only once the opportunity has reached the Propose stage, and only if there's no pending approval already:

async function canEscalate(primaryControl) {
  var formContext = primaryControl;
    var userId = Xrm.Utility.getGlobalContext().userSettings.userId;
      var ownerId = formContext.getAttribute("ownerid").getValue();
      
        if (!ownerId || ownerId[0].id.toLowerCase() !== userId.toLowerCase()) {
            return false;
              }
              
                var recordId = formContext.data.entity.getId().replace(/[{}]/g, "");
                  var result = await Xrm.WebApi.retrieveRecord(
                      "opportunity", recordId, "?$select=salesstage,con_hasopenescalation"
                        );
                        
                          return result.salesstage === 2 && !result.con_hasopenescalation;
                          }

CommandChecker functions can be async — Dynamics will wait for the promise before deciding the button's state. Just be aware that every extra Web API call in a rule adds latency to ribbon rendering, especially on grids with dozens of visible rows each re-evaluating their own rule. Keep the check as cheap as you can; if you find yourself calling the Web API from an enable rule on a subgrid, it's often faster to precompute that value onto the record itself (a rollup field or a plugin-set field) and check it directly, rather than querying live from the ribbon.

What actually happens on click

The rule only controls visibility and enablement — a separate function, wired up as the button's Action, is what runs when someone actually clicks it:

async function escalateToManager(primaryControl) {
  var formContext = primaryControl;
    var confirm = await Xrm.Navigation.openConfirmDialog({
        title: "Escalate this opportunity?",
            text: "Your manager will be notified and the record flagged for review.",
              });
              
                if (!confirm.confirmed) return;
                
                  await formContext.data.save();
                    await Xrm.WebApi.updateRecord(
                        "opportunity",
                            formContext.data.entity.getId().replace(/[{}]/g, ""),
                                { con_hasopenescalation: true }
                                  );
                                  
                                    formContext.ui.refreshRibbon();
                                    }

That last line matters more than it looks. Ribbon state doesn't automatically re-evaluate just because you changed a value in code — Dynamics re-checks your rules on load, on save, and on a few built-in events, but not every time an attribute changes. If your action changes something an enable rule depends on, call formContext.ui.refreshRibbon() yourself, or the button will sit in its old state until the user manually refreshes the page.

Where the JavaScript actually lives

Same rule as every other post in this series: the function has to be in a web resource that's part of your solution, and the Ribbon Workbench (or the classic ribbon customization) references it by $webresource: path plus function name — not by file path alone. A function that works perfectly when you test it in the console but does nothing on the actual button almost always means one of three things: the web resource reference in the ribbon XML is wrong, the function isn't actually included in that web resource, or you edited the JS but forgot to publish afterward — the same publish-and-cache trap from the ALM post shows up here too.

Testing rules without clicking through the UI fifty times

Because CommandChecker functions take a plain object shaped like formContext and return a boolean, they're some of the easiest ribbon-adjacent code to unit test — you don't need a real form, just an object with the methods your function actually calls:

test("escalate disabled when not the owner", async () => {
  const fakeForm = {
      getAttribute: () => ({ getValue: () => [{ id: "other-user-guid" }] }),
        };
          expect(await canEscalate(fakeForm)).toBe(false);
          });

This is the same pattern from the testing and debugging post — mock the pieces of formContext your function actually touches, and you can validate ribbon logic in milliseconds instead of navigating to a record, checking a button state, changing data, and reloading, over and over.

A short checklist before you ship a ribbon change

Did you use a Display Rule where you meant "hide it" and an Enable Rule where you meant "show it but grey it out" — not the other way around? Is any Web API call inside an enable rule cheap enough to run on every grid row, not just a form? Does your click-handler call refreshRibbon() if it changes something another rule depends on? And is the web resource holding these functions actually included in the solution you're about to export — the same ALM discipline from a couple of posts back applies just as much to ribbon code as it does to form scripts.

Next up

We've covered forms, data, agents, testing, deployment, and now the command bar. Next in the series: Business Process Flow JavaScript — reading and moving the active stage in code, and the specific quirks of scripting against a BPF versus a regular form.

From Script to Agent: Wiring a Copilot Studio Action into a Dynamics 365 Ribbon Button

We've spent this series in the form: events, field logic, lookups, subgrids, and calling the Web API. This last post is where it connects to the other thing you're probably building right now — a JavaScript-driven ribbon button that hands off to a Copilot Studio agent and brings the answer back onto the form.

The Pattern: Ribbon Button → JavaScript → Agent

There's no direct client-side SDK call from form JavaScript into a Copilot Studio agent. The reliable pattern is: a ribbon button runs a JavaScript function, that function calls an HTTP-triggered Power Automate flow (or an Azure Function) that invokes the agent's topic, and the response comes back as JSON that your script uses to update the form or show a notification.

Step 1: Add the Ribbon Button

Using the modern command bar designer (Power Apps maker portal → table → Forms → Command bar) or Ribbon Workbench, add a button with a JavaScript action pointing to a function in a form library, e.g. new_/ribbon/agentActions.js, function summarizeCaseWithAgent. Pass PrimaryControl as a parameter so your function gets the form context.

Step 2: Expose the Agent as a Callable Endpoint

In Copilot Studio, publish the topic you want to trigger, then wrap it with a Power Automate flow that starts with an HTTP request trigger, calls the agent (or the underlying logic the agent uses), and responds with the result. This gives you a stable HTTPS URL your form script can call — the same pattern used for any external integration, just fronting an agent instead of a plain API.

Step 3: Call It from the Button's JavaScript

async function summarizeCaseWithAgent(primaryControl) {
    var formContext = primaryControl;
        formContext.ui.setFormNotification("Asking the agent for a summary...", "INFO", "agent_call");
        
            var caseId = formContext.data.entity.getId().replace("{", "").replace("}", "");
                var description = formContext.getAttribute("description").getValue();
                
                    try {
                            var response = await fetch("https://your-flow-endpoint.example.com/trigger", {
                                        method: "POST",
                                                    headers: { "Content-Type": "application/json" },
                                                                body: JSON.stringify({
                                                                                caseId: caseId,
                                                                                                description: description
                                                                                                            })
                                                                                                                    });
                                                                                                                    
                                                                                                                            if (!response.ok) {
                                                                                                                                        throw new Error("Flow returned " + response.status);
                                                                                                                                                }
                                                                                                                                                
                                                                                                                                                        var result = await response.json();
                                                                                                                                                                formContext.ui.clearFormNotification("agent_call");
                                                                                                                                                                        formContext.ui.setFormNotification(result.summary, "INFO", "agent_summary");
                                                                                                                                                                            } catch (error) {
                                                                                                                                                                                    formContext.ui.clearFormNotification("agent_call");
                                                                                                                                                                                            formContext.ui.setFormNotification("Couldn't reach the agent right now.", "ERROR", "agent_error");
                                                                                                                                                                                                    console.error(error);
                                                                                                                                                                                                        }
                                                                                                                                                                                                        }

A Practical Example: "Summarize This Case" Button

The function above is a working version of this: it reads the case description, calls the flow, and shows the agent's summary as a form notification instead of navigating anywhere. You can just as easily write the result into a field, or open it in a side panel — whatever fits the workflow.

A Word on Security

The agent's flow runs under its own connection identity, not the signed-in user's — so it can potentially see more (or less) than the user calling it. That's a topic on its own, and worth checking against your Dataverse security roles before you wire up anything that touches sensitive data.

Common Pitfalls

  • No loading state. Agent calls can take a few seconds; always show a notification (or disable the button) while waiting, so users don't click twice.
  • No timeout handling. Set a reasonable timeout on the fetch call and handle it gracefully — an agent call that hangs shouldn't hang the form.
  • Trusting the response shape blindly. Validate the JSON structure before reading fields off it; an agent or flow change can silently alter the response.
  • Hardcoding the endpoint URL. Store it in an environment variable or a configuration record instead, so it survives a move between environments.

Wrapping Up the Series

Five posts in, the throughline hasn't changed: form scripting is still the layer that makes everything else — Business Rules, Power Automate, Copilot agents — actually usable inside the form users work in every day. Knowing both the fundamentals and where they connect to AI is what keeps a CRM developer's skill set current without starting over. Thanks for following along.

Testing and Debugging Dynamics 365 Form Scripts: A Practical Workflow

Five posts in, you can write form scripts that handle events, field logic, lookups, subgrids, Web API calls, and even agent handoffs. None of that matters much if you can't quickly tell why a script isn't working, or catch it breaking before a user does. This post is about the workflow around the code — debugging, logging, and a lightweight way to test the logic outside the form entirely.

Debugging in the Browser

Skip alert() debugging. Open dev tools (F12), go to Sources, and find your web resource under the model-driven app's origin (usually nested under something like /webresources/). Set a real breakpoint by clicking the line number, then trigger the event from the form — execution will pause there with full access to inspect formContext, step through, and watch variables change.

function onChangeHandler(executionContext) {
    debugger; // pauses here automatically when dev tools are open
        var formContext = executionContext.getFormContext();
            // ...
            }

A Lightweight Logging Pattern

console.log calls scattered through production code get noisy and get left in by accident. A small wrapper keeps things consistent and easy to strip out or redirect later:

var Logger = {
    enabled: false, // flip on only while diagnosing an issue
    
        info: function (message, data) {
                if (Logger.enabled) console.log("[Form Script] " + message, data || "");
                    },
                        error: function (message, error) {
                                console.error("[Form Script] " + message, error);
                                        // optionally: send to Application Insights or a Dataverse log table here
                                            }
                                            };
                                            
                                            // Usage
                                            Logger.info("Status changed", formContext.getAttribute("statuscode").getValue());

Errors always log regardless of the flag — you want those visible in production. Informational logs stay quiet unless you're actively debugging.

Common Runtime Errors and What They Actually Mean

  • "Cannot read properties of undefined/null (reading 'getValue')" — getAttribute() returned null, almost always because that field isn't on the current form. Always check before calling methods on it.
  • "formContext.getControl(...).setVisible is not a function" — you're calling a control method on an attribute, or vice versa. Attributes hold values; controls are the UI.
  • Nothing happens, no error at all — usually the event isn't registered correctly (check "Pass execution context as first parameter" is ticked), or the library isn't added to this particular form.
  • Works in the maker portal preview, fails for users — security role differences. Test with a real (non-admin) user's role before calling it done.

Unit Testing with Jest (Mocking Xrm)

You don't need a live environment to test pure logic. Extract the decision-making into a plain function and mock the pieces of formContext it touches:

// discountLogic.js - the logic under test, extracted from the form script
function needsDiscountReason(discountPercent, customerType) {
    return discountPercent > 10 && (customerType === 1 || customerType === 2);
    }
    module.exports = { needsDiscountReason };
    
    // discountLogic.test.js
    const { needsDiscountReason } = require("./discountLogic");
    
    test("requires a reason above 10% for customer types 1 and 2", () => {
        expect(needsDiscountReason(15, 1)).toBe(true);
            expect(needsDiscountReason(15, 3)).toBe(false);
                expect(needsDiscountReason(5, 1)).toBe(false);
                });

This won't test the Dataverse integration itself, but it catches logic bugs instantly, without opening a browser — and it's the part of your script most likely to have an off-by-one or wrong-operator bug.

A Quick Smoke-Test Checklist Before You Publish

  • Test on a new, unsaved record as well as an existing one
  • Test with a non-administrator security role, not just your own
  • Test on the mobile app if the form is used there
  • Clear the browser cache or hard-refresh — stale web resource caching hides real bugs
  • Check the console for errors even when the feature "looks" like it worked

Common Pitfalls

  • Leaving debug logging on in production. Flip the Logger flag off (or gate it behind a config value) before publishing.
  • Testing only the happy path. Try blank fields, unexpected option set values, and records that predate the script.
  • Trusting the maker portal preview alone. It often runs with elevated privileges the real users won't have.

Wrapping Up

A script that works once in your own testing isn't the same as a script that's actually reliable. Debugging properly, logging deliberately, and testing the logic outside the form catches the bugs before your users do — which matters even more once your scripts start calling out to Web APIs and agents that can fail in their own ways too.

Calling the Dataverse Web API from Dynamics 365 Form Scripts

Everything so far in this series has stayed on the form: fields, events, lookups, subgrids. This post steps off the form and into Dataverse directly, using the Web API to read and write records the form doesn't already have loaded — the foundation you need before the next post, where this starts connecting to Copilot Studio agents.

Why Call the Web API from a Form Script

A few common reasons: pulling in data that isn't on the form (like a related account's credit limit), creating a related record without navigating the user away, running a real-time check against other records before save, or calling a custom Dataverse action. All of it goes through Xrm.WebApi, and every method returns a Promise.

The Basics: Xrm.WebApi

// Read one record
Xrm.WebApi.retrieveRecord("account", accountId, "?$select=name,creditlimit");

// Read multiple records
Xrm.WebApi.retrieveMultipleRecords("contact", "?$select=fullname&$filter=parentcustomerid_value eq " + accountId);

// Create a record
Xrm.WebApi.createRecord("task", {
    subject: "Follow up",
        "regardingobjectid_account@odata.bind": "/accounts(" + accountId + ")"
        });
        
        // Update a record
        Xrm.WebApi.updateRecord("account", accountId, { creditlimit: 50000 });

Note the entity set names are plural and lowercase (accounts, contacts), but retrieveRecord/createRecord/updateRecord take the singular logical name (account) — it's a common source of confusion.

Reading a Related Record

Here's a real example: when a contact form loads, pull the parent account's credit limit and show it in a notification:

async function onLoad(executionContext) {
    var formContext = executionContext.getFormContext();
        var accountValue = formContext.getAttribute("parentcustomerid").getValue();
            if (!accountValue) return;
            
                var accountId = accountValue[0].id.replace("{", "").replace("}", "");
                
                    try {
                            var result = await Xrm.WebApi.retrieveRecord("account", accountId, "?$select=creditlimit");
                                    formContext.ui.setFormNotification(
                                                "Account credit limit: " + (result.creditlimit || 0),
                                                            "INFO",
                                                                        "credit_limit_info"
                                                                                );
                                                                                    } catch (error) {
                                                                                            console.error("Failed to retrieve account credit limit", error);
                                                                                                }
                                                                                                }

Creating a Related Record

async function logFollowUpTask(executionContext) {
    var formContext = executionContext.getFormContext();
        var contactId = formContext.data.entity.getId().replace("{", "").replace("}", "");
        
            var task = {
                    subject: "Follow up on discount request",
                            "regardingobjectid_contact@odata.bind": "/contacts(" + contactId + ")"
                                };
                                
                                    try {
                                            await Xrm.WebApi.createRecord("task", task);
                                                } catch (error) {
                                                        console.error("Failed to create follow-up task", error);
                                                            }
                                                            }

A Practical Example: Real-Time Duplicate Check on Save

Combining an async Web API call with OnSave, including blocking the save until the check completes:

formContext.data.entity.addOnSave(onSaveCheckDuplicate);

async function onSaveCheckDuplicate(executionContext) {
    var eventArgs = executionContext.getEventArgs();
        var formContext = executionContext.getFormContext();
            var email = formContext.getAttribute("emailaddress1").getValue();
            
                if (!email) return;
                
                    eventArgs.preventDefault(); // pause the save while we check
                    
                        try {
                                var query = "?$select=contactid&$filter=emailaddress1 eq '" + email + "'";
                                        var result = await Xrm.WebApi.retrieveMultipleRecords("contact", query);
                                        
                                                var isDuplicate = result.entities.some(function (c) {
                                                            return c.contactid !== formContext.data.entity.getId().replace("{", "").replace("}", "");
                                                                    });
                                                                    
                                                                            if (isDuplicate) {
                                                                                        formContext.ui.setFormNotification("A contact with this email already exists.", "ERROR", "dup_check");
                                                                                                } else {
                                                                                                            formContext.data.entity.save(); // safe to save now
                                                                                                                    }
                                                                                                                        } catch (error) {
                                                                                                                                console.error("Duplicate check failed", error);
                                                                                                                                        formContext.data.entity.save(); // don't block save on a broken check
                                                                                                                                            }
                                                                                                                                            }

Common Pitfalls

  • Forgetting await. Without it, your code moves on before the API call resolves, and you end up reading undefined data or saving before a check completes.
  • Not handling rejected promises. A network error or a security-role denial throws — always wrap calls in try/catch.
  • Wrong entity set name. retrieveMultipleRecords needs the plural set name; retrieveRecord/createRecord/updateRecord need the singular logical name.
  • Too many calls per save. Each Web API call is a real HTTP request; batch or cache where you can instead of calling it inside a loop.

What's Next

Last post in this series: wiring a Copilot Studio agent action into a JavaScript-driven ribbon button — where form scripting and agents meet.

Working with Lookups, Option Sets, and Subgrids in Dynamics 365 Forms Using JavaScript

So far in this series we've covered basic form events and field-level show/hide/required logic. This post covers the three field types that trip people up most: lookups, option sets, and subgrids — including how to filter a lookup so users only see relevant records.

Reading and Setting Lookup Values

A lookup's value is always an array of objects, even though it only ever holds one record on most forms. Each object has id, name, and entityType:

var formContext = executionContext.getFormContext();
var lookupValue = formContext.getAttribute("parentcustomerid").getValue();

if (lookupValue) {
    var id = lookupValue[0].id;
        var name = lookupValue[0].name;
            var entityType = lookupValue[0].entityType;
            }
            
            // Setting a lookup value
            formContext.getAttribute("parentcustomerid").setValue([
                {
                        id: "00000000-0000-0000-0000-000000000000",
                                name: "Contoso Ltd",
                                        entityType: "account"
                                            }
                                            ]);

Filtering a Lookup's Results

By default a lookup searches the whole entity. To narrow it — say, only show contacts belonging to the account selected elsewhere on the form — use addPreSearch with a custom filter:

function onLoad(executionContext) {
    var formContext = executionContext.getFormContext();
        formContext.getControl("primarycontactid").addPreSearch(filterContactsByAccount);
        }
        
        function filterContactsByAccount(executionContext) {
            var formContext = executionContext.getFormContext();
                var accountValue = formContext.getAttribute("parentaccountid").getValue();
                
                    if (accountValue) {
                            var accountId = accountValue[0].id.replace("{", "").replace("}", "");
                                    var filter = "<filter type='and'>" +
                                                "<condition attribute='parentcustomerid' operator='eq' value='" + accountId + "' />" +
                                                            "</filter>";
                                                                    formContext.getControl("primarycontactid").addCustomFilter(filter, "contact");
                                                                        }
                                                                        }

One gotcha: addCustomFilter only applies to the next search, so it has to run inside addPreSearch every time, not just once on load.

Working with Option Sets

Option sets (choice fields) store and return the underlying numeric value, not the label. Use getOption or getOptions when you need the label or want to build the list dynamically:

var attribute = formContext.getAttribute("new_prioritylevel");

// Read/write the numeric value
var currentValue = attribute.getValue(); // e.g. 2
attribute.setValue(1);

// Get the label for the current value
var options = attribute.getOptions();
var selected = options.find(function (o) { return o.value === currentValue; });
console.log(selected ? selected.text : "none selected");

// Remove an option a user shouldn't be able to pick
var control = formContext.getControl("new_prioritylevel");
control.removeOption(3);

Refreshing a Subgrid

Subgrids don't automatically know when related data changes elsewhere on the form. Refresh one explicitly after an action that affects its rows:

var gridControl = formContext.getControl("Subgrid_Orders");
if (gridControl) {
    gridControl.refresh();
    
        // Reading the currently loaded rows
            var grid = gridControl.getGrid();
                var rows = grid.getRows();
                    console.log("Row count: " + rows.getLength());
                    }

Common Pitfalls

  • Treating a lookup value as a single object. It's always an array — forgetting the [0] is one of the most common form-script bugs.
  • Comparing option set values as strings. They're numbers; "2" === 2 is false in JavaScript.
  • Custom filters that don't reset. If you conditionally apply a filter, make sure the "else" branch clears it, or users will get a stale filter after changing the related field.
  • Calling grid methods before the subgrid has loaded. On OnLoad, wrap subgrid access in the control's onLoad event rather than assuming it's ready immediately.

What's Next

Next post: calling the Dataverse Web API directly from a form script — reading related records, creating child rows, and handling the async responses properly.

Display Density in Model-Driven Apps: Less Whitespace, More CRM

 If you work with Dynamics 365, you've heard this one: "Why is there so much empty space on the screen?" Microsoft now has an ...