Prompt & Platform
Connect
HomeTopicsSnippetsDev toolsArticles
Theme

Copy · paste · ship

Snippets

Short pieces of code I reach for again and again. Filter by language and hit Copy.

C#

Batch create with ExecuteMultiple

Create records in batches of up to 1,000 with ExecuteMultiple.

C#
var batch = new ExecuteMultipleRequest
{
    Settings = new ExecuteMultipleSettings { ContinueOnError = true, ReturnResponses = false },
    Requests = new OrganizationRequestCollection()
};
foreach (var e in records) batch.Requests.Add(new CreateRequest { Target = e });
var response = (ExecuteMultipleResponse)service.Execute(batch);
Power Fx

Bulk update with Patch and ForAll

Update all selected gallery rows in one call: Patch with a base table and a change table of the same length.

Power Fx
With(
    { selected: Filter(galTasks.AllItems, chkSelect.Value) },
    Patch(
        Tasks,
        selected,
        ForAll(selected, { Done: true })
    )
)
FetchXML

Count records by owner

Count open cases per owner with an aggregate query.

FetchXML
<fetch aggregate="true">
  <entity name="incident">
    <attribute name="incidentid" alias="cases" aggregate="count" />
    <attribute name="ownerid" alias="owner" groupby="true" />
    <filter>
      <condition attribute="statecode" operator="eq" value="0" />
    </filter>
  </entity>
</fetch>
Web API

Expand a lookup in one call

Get accounts with the primary contact's name in one request.

OData
GET [org]/api/data/v9.2/accounts?$select=name&$expand=primarycontactid($select=fullname,emailaddress1)&$top=20
CLI

Export a managed solution

Export a managed solution with the Power Platform CLI.

Terminal
pac auth create --name dev --environment https://contoso-dev.crm.dynamics.com
pac solution export --name ContosoCore --path ./out/ContosoCore_managed.zip --managed
FetchXML

Join contacts to accounts

Contacts together with their parent account's name.

FetchXML
<fetch top="50">
  <entity name="contact">
    <attribute name="fullname" />
    <link-entity name="account" from="accountid" to="parentcustomerid" alias="acc" link-type="outer">
      <attribute name="name" />
    </link-entity>
  </entity>
</fetch>
JavaScript

Make a column conditionally required

Make a column required only when another column has a value.

JavaScript
function onReasonChange(executionContext) {
  const form = executionContext.getFormContext();
  const reason = form.getAttribute("pp_reason").getValue();
  form.getAttribute("pp_details").setRequiredLevel(reason === 3 ? "required" : "none");
}
Power Fx

Named formulas for the current user

Named formulas (App.Formulas) for the current user's details, calculated only when needed.

Power Fx
// App.Formulas
CurrentUser = LookUp(Users, 'Primary Email' = User().Email);
IsManager = !IsBlank(LookUp(Teams, Name = "Managers"));
Power Fx

Patch a record with a lookup

Create a record with a lookup in Dataverse.

Power Fx
Patch(
    Orders,
    Defaults(Orders),
    {
        Name: txtName.Text,
        Customer: LookUp(Accounts, 'Account Number' = txtAcc.Text),
        Quantity: Value(txtQty.Text)
    }
)
C#

Plugin boilerplate

The services every plugin needs, in one place.

C#
public void Execute(IServiceProvider serviceProvider)
{
    var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
    var factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
    var service = factory.CreateOrganizationService(context.UserId);
    var tracing = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

    if (!(context.InputParameters["Target"] is Entity target)) return;
    tracing.Trace("Running on {0} {1}", target.LogicalName, target.Id);
}
C#

Prevent plugin recursion

Stop a plugin from triggering itself in an infinite loop.

C#
if (context.Depth > 1)
{
    tracing.Trace("Depth {0} – exiting to avoid recursion", context.Depth);
    return;
}
JavaScript

Update a record with Xrm.WebApi

Update a record from a form script with Xrm.WebApi.

JavaScript
async function closeTask(id) {
  try {
    await Xrm.WebApi.updateRecord("task", id.replace(/[{}]/g, ""), {
      statecode: 1,
      statuscode: 5
    });
    Xrm.Navigation.openAlertDialog({ text: "Task closed." });
  } catch (e) {
    Xrm.Navigation.openErrorDialog({ message: e.message });
  }
}