Skip to content

Tips

RSS

Short tips about Dynamics 365, Power Pages and the Power Platform: one problem, one solution, read in two minutes. A new one every week.

Search for text in every file of a folder with PowerShell

Which file in the solution was using that column? Where did that old URL end up? You don’t need Visual Studio for this, one line of PowerShell will do:

cd "C:\path\to\my\project"
Get-ChildItem -Recurse -File | Select-String -Pattern "new_field" -List | Select-Object Path

-List stops at the first match in each file, which is exactly what you want when you only need to know which files contain the text. To see every matching line with its number, drop -List and the trailing | Select-Object Path. If you only care about certain file types, filter with Get-ChildItem -Recurse -Include *.cs,*.js.

I almost always leave out bin, obj and node_modules. Otherwise the search takes forever and the output is full of results you don’t care about:

Get-ChildItem -Recurse -File | Where-Object FullName -notmatch '\\(bin|obj|node_modules)\\' | Select-String -Pattern "new_field" -List | Select-Object Path
Share:LinkedInX

Create and update records from Power Pages with the Web API

Once the Web API is enabled for the table and the safeAjax wrapper is in the Header, creating a record is a POST and updating one is a PATCH, both against /_api/<entity-set>:

function createRecord(entitySet, data) {
  return utilities.safeAjax({
    type: "POST",
    url: "/_api/" + entitySet,
    contentType: "application/json",
    data: JSON.stringify(data),
    success: function (res, status, xhr) {
      console.log("Created with id", xhr.getResponseHeader("entityid"));
    },
  });
}
 
function updateRecord(entitySet, id, data) {
  return utilities.safeAjax({
    type: "PATCH",
    url: "/_api/" + entitySet + "(" + id + ")",
    contentType: "application/json",
    data: JSON.stringify(data),
  });
}
 
createRecord("accounts", { name: "Axazure", address1_city: "Madrid" });

Note that the name is plural, since it’s the entity set (accounts, contacts). And you won’t find the new record’s id in the response body; it comes back in the entityid header.

If you try to read what you just created straight away, it may not be there yet. That’s the Power Pages cache, not a bug in your code.

How to get the primary name column of any Dataverse table

As soon as you write generic code, like a plugin that runs on several tables or a tool, you need to know the primary name column of each table. For accounts it’s name, for contacts fullname, for cases title. Rather than hardcoding it, I ask the metadata.

In C# a RetrieveEntityRequest is enough:

public static string GetPrimaryNameAttribute(IOrganizationService service, string logicalName)
{
    var response = (RetrieveEntityResponse)service.Execute(new RetrieveEntityRequest
    {
        LogicalName = logicalName,
        EntityFilters = EntityFilters.Entity, // only the table, no columns: much faster
    });
 
    return response.EntityMetadata.PrimaryNameAttribute; // PrimaryIdAttribute for the id
}

With the Web API it’s a single request:

GET /api/data/v9.2/EntityDefinitions(LogicalName='account')?$select=PrimaryNameAttribute,PrimaryIdAttribute

Metadata hardly ever changes, so there’s no point fetching it inside a loop. If you call this often, keep the result in a static variable or a cache.

Share:LinkedInX

How to debug Dynamics 365 JavaScript without uploading it every time

Uploading the web resource, publishing and refreshing every time you change a line is painfully slow. A much nicer option is to make the browser load your local file instead of the one stored in Dynamics.

These days the quickest way is Local Overrides in Chrome or Edge. In DevTools, go to Sources → Overrides and pick a local folder. Then, in the Network tab, find your JavaScript file, right click it and choose Override content. From then on you edit the file (in DevTools or in that folder), reload, and the form runs your version.

If you already have Fiddler installed, its AutoResponder does the same thing and has been the go-to approach for years:

  1. Tools → Options → HTTPS, turn on Decrypt HTTPS traffic and trust the certificate.
  2. Rules → Performance → Disable Caching.
  3. In AutoResponder, tick Enable rules and Unmatched requests passthrough.
  4. Add a rule with REGEX:(?insx).+(?'yourjsname'[^?]*.js) and the path to your local file.

More than once I’ve had the JS not show up in Fiddler at all. It’s nearly always the browser cache, and ticking Disable cache in DevTools → Network sorts it out.

Remember to switch it off when you’re done. Nobody else sees your changes, so if you leave it on you end up testing code that only exists on your machine.

Share:LinkedInX

The safeAjax wrapper to call the Power Pages Web API

Calls to /_api/ that write data need the anti-forgery token (__RequestVerificationToken). Microsoft suggests a small wrapper around $.ajax that adds it for you, and I put it in the site Header so every page can use it:

(function (utilities, $) {
  function safeAjax(ajaxOptions) {
    const deferredAjax = $.Deferred();
    shell.getTokenDeferred().done(function (token) {
      ajaxOptions.headers = ajaxOptions.headers || {};
      ajaxOptions.headers["__RequestVerificationToken"] = token;
      $.ajax(ajaxOptions)
        .done(function (data, textStatus, jqXHR) {
          validateLoginSession(data, textStatus, jqXHR, deferredAjax.resolve);
        })
        .fail(deferredAjax.reject);
    }).fail(function () {
      deferredAjax.rejectWith(this, arguments);
    });
    return deferredAjax.promise();
  }
  utilities.safeAjax = safeAjax;
})((window.utilities = window.utilities || {}), jQuery);

From then on, any page can call utilities.safeAjax({ type: "PATCH", url: "/_api/accounts(" + id + ")", ... }).

You don’t have to define shell.getTokenDeferred() or validateLoginSession, both come with Power Pages. The second one also sends the user back to the login page if their session has expired.

A word of warning from experience: some ad blockers cut these requests off. If nothing seems to happen when you test, turn the blocker off before you start going through your code line by line.

Xrm.WebApi cheat sheet: create, retrieve, update and delete

This is the cheat sheet I keep around for the four basic operations with Xrm.WebApi from a form, using async/await:

// Create: returns { entityType, id }
const { id } = await Xrm.WebApi.createRecord("account", {
  name: "Axazure",
  revenue: 5000000,
  "primarycontactid@odata.bind": "/contacts(00000000-0000-0000-0000-000000000000)",
});
 
// Retrieve a record
const account = await Xrm.WebApi.retrieveRecord("account", id, "?$select=name,revenue");
 
// Update (note: the id is the second parameter)
await Xrm.WebApi.updateRecord("account", id, { revenue: 6000000 });
 
// Delete
await Xrm.WebApi.deleteRecord("account", id);

Lookups are set with field@odata.bind and the path /<entity-set-name>(<guid>), in plural (/contacts(...)). That field name is the navigation property, which for custom columns usually matches the schema name, capitals included.

Always use $select when reading. Without it you get every column back and the call is noticeably slower.

The mistake I see most is with updateRecord, when someone forgets the id and passes the data as the second parameter. It fails, and the error message doesn’t make it obvious why.

Share:LinkedInX

"The entity name doesn't exist" error in Dynamics 365 views

You open a view on a custom table and get “The entity name doesn’t exist”. Most likely the view has an object type code (ObjectTypeCode) stored that doesn’t belong to this environment. It tends to happen when you move solutions between environments, because custom tables don’t necessarily get the same code in each one. Standard tables like account or contact won’t give you this problem, since their code never changes.

To fix it, first get the real ObjectTypeCode of the table in your environment:

https://YOUR-ENV.crm4.dynamics.com/api/data/v9.2/EntityDefinitions?$select=LogicalName,ObjectTypeCode&$filter=LogicalName eq 'table_name'

Then open XrmToolBox → View Designer, load the table and, in each view, edit the XML to replace the old number in the object attribute with the one you just copied. Save, publish, and the view should open normally again.

Share:LinkedInX

How to move your changes to another Git branch without committing

You start coding and halfway through you notice you’re on the wrong branch, usually main. There’s no need to copy files around by hand.

If the branch already exists, stash the changes, switch and bring them back:

git stash
git checkout other-branch
git stash pop

If the branch doesn’t exist yet it’s even simpler. Uncommitted changes come along when you create a branch, so you can skip stash entirely:

git switch -c my-new-branch

git stash pop may give you conflicts if the other branch changed the same files. Just resolve them like any other conflict. The stash isn’t dropped until it applies cleanly, so nothing gets lost, and git stash list will show it to you.

Share:LinkedInX

Dataverse plugin template: context, service and Target

Every plugin starts the same way. You need the context, the tracing service, the organization service and the record that fired the plugin (Target). This is the boilerplate I always copy:

public void Execute(IServiceProvider serviceProvider)
{
    var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
    var tracing = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
    var factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
    var service = factory.CreateOrganizationService(context.UserId);
 
    if (!context.InputParameters.Contains("Target") || !(context.InputParameters["Target"] is Entity target))
        return;
 
    tracing.Trace("Plugin executed on {0} {1}", target.LogicalName, target.Id);
    // Your logic here
}

CreateOrganizationService(context.UserId) gives you a service with the permissions of the user who triggered the action. Pass null and it runs as SYSTEM, bypassing security, which I only do when there’s really no other way.

The type check on Target is there for a reason too. On a Delete you get an EntityReference rather than an Entity, so casting it straight to Entity would make the plugin fail.

Finally, on an Update the Target only contains the columns that changed. If you need to read others, register a pre-image on the step.

Share:LinkedInX

How to set a lookup from JavaScript in a Dynamics 365 form

You can’t set a lookup field by just passing it a GUID. It expects an array containing an object with id, name and entityType, so I usually keep a small helper around to avoid writing it out every time:

function setLookup(executionContext, fieldName, id, name, entityType) {
  const formContext = executionContext.getFormContext();
  formContext.getAttribute(fieldName).setValue([
    { id: id, name: name, entityType: entityType },
  ]);
}
 
// Example: set the parent account
setLookup(executionContext, "parentcustomerid", "00000000-0000-0000-0000-000000000000", "Axazure", "account");

entityType takes the logical name of the table (account, contact), not the display name. name is the text shown on the form, and if you leave it out the field looks empty until you save.

Customer lookups such as customerid or parentcustomerid need a bit more care. They accept several tables, and if entityType isn’t the right one the save fails.

To clear the field, use formContext.getAttribute(fieldName).setValue(null).

Share:LinkedInX

How to enable the Power Pages Web API for a table

The Power Pages Web API (/_api/...) doesn’t work with any table until you enable it yourself. You need two things, the site settings and the table permissions.

In Site Settings, add these two entries:

NameValue
Webapi/account/enabledtrue
Webapi/account/fieldsaddress1_city,description

Replace account with your table’s logical name. fields is a comma separated list of the columns that can be read and written. You can use * to include all of them, but I’d rather keep it to the ones I actually use.

Then, under Table Permissions, create a permission for the table with the privileges you need (read, create, write) and the right access type, whether that’s global, contact or account. Assign it to the web role of the users who will call the API.

If it still doesn’t respond after all that, it’s probably the cache not having picked up the changes yet. As an administrator you can force a refresh from /_services/about.