Export D365 F/SCM Data Packages to SharePoint for Power BI with Power Automate

ErpCoder

A customer running Dynamics 365 Supply Chain Management wanted a few Power BI reports on top of their ERP data. They didn’t need near-real-time numbers: a daily refresh was fine. Instead of setting up Synapse Link, Fabric or BYOD, I went with something simpler. I reused the data export projects they already had in the Data Management workspace and let Power Automate do the rest.

The result is three scheduled flows. They start a data package export, wait until D365 has finished it, then download the package and unzip it into a SharePoint document library. Power BI reads the CSV files from SharePoint. No Azure resources, no custom X++ code.

The idea to call the Data Management package API directly over HTTP isn’t mine. Vijay Yelmame showed it with Postman in his post Data management package REST API – Export package in Dynamics 365 FO using Postman on the Dynamics 365 Community. That post was my starting point. This article shows how to turn those Postman calls into an unattended solution with Power Automate.

How the Data Management package API works

The export is asynchronous. You tell D365 to run an export project, D365 queues a batch job, and you get nothing back except an acknowledgement. You have to ask again later whether the job has finished. Only then can you request a download link for the package.

That makes three OData actions, all on the DataManagementDefinitionGroups entity and all called with POST:

StepActionBodyReturns
1. StartExportToPackagedefinitionGroupId, packageName, executionId, reExecute, legalEntityIdThe execution ID
2. PollGetExecutionSummaryStatusexecutionIdStatus, e.g. Executing, Succeeded, Failed
3. FetchGetExportedPackageUrlexecutionIdA time-limited blob URL (SAS) for the ZIP package

The full URL is https://<your-environment>.operations.dynamics.com/data/DataManagementDefinitionGroups/Microsoft.Dynamics.DataEntities.<Action>.

The execution ID ties the three calls together. You can pass your own ID to ExportToPackage, which means you know it before the export even starts. That is what makes splitting the process across several flows easy.

Microsoft documents all actions in Data management package REST API. According to Microsoft Learn, the exported file stays in blob storage for seven days before it is deleted automatically.

Architecture: three flows and a SharePoint list as the glue

Each of the three API steps gets its own flow. A SharePoint list keeps track of every export run and its state, so the flows never call each other directly.

Architecture: three scheduled flows between the D365 package API and SharePoint

Architecture: three scheduled flows between the D365 package API and SharePoint

FlowSchedulePicks upDoes
01 Data ExportDaily, 3 amEvery row in the package listStarts the export, writes a history row
02 Check Export StatusDaily, a few minutes laterHistory rows with Ready = NoPolls the status, sets Ready = Yes on success
03 Download PackageDaily, 4 amHistory rows with Ready = Yes and Started = NoDownloads the ZIP, extracts it, sets Finished = Yes

Why not one flow with a Do-until loop? A few reasons:

  • The API is asynchronous anyway. Waiting inside a flow means a run sits there for minutes or hours doing nothing. A scheduled flow that looks at a list fits the API much better.
  • Fault isolation. If one run fails, for example because the download hits a timeout, the other steps and the other packages are not affected. The next run simply picks up what is left.
  • Easier support. When something breaks, you see immediately which step failed, and for which execution ID. Debugging one 40-action “monster flow” is a lot less fun.
  • Not time-critical. The reports refresh once a day. Nobody cares whether the data lands at 4:00 or 4:30.

The SharePoint site holds three things:

  • Export Pakete (German for export packages): a list with one row per D365 export project. The Title must match the data project name in D365 exactly. Adding a new export for Power BI means adding a row here, no change to the flows.
  • Export History: one row per export run with Title, Execution ID and three Yes/No columns: Ready, Started and Finished. These flags form a small state machine. They also double as a log you can read without opening Power Automate.
  • Export Downloads: a document library where the extracted packages end up, one folder per package and one subfolder per run.
The Export Pakete list: one row per D365 export project

The Export Pakete list: one row per D365 export project

The Export History list: every run with its execution ID and status flags

One more design decision: all D365 calls use the plain HTTP action, not the Fin & Ops connector. The connector does not offer the package API actions, so we call the OData actions ourselves and handle the OAuth token in the flow.

Prerequisites

  1. An export project in D365. In Data management, create an export data project with the entities you need, e.g. Customers V3 in CSV format. Its name is the definitionGroupId the API expects.
  2. An app registration in Microsoft Entra ID with a client secret. No API permissions are needed for the client credentials flow against Fin & Ops.
  3. The app registered in D365. Go to System administration > Setup > Microsoft Entra applications, add the client ID and map it to a user who may run data projects.
  4. A SharePoint site with the two lists and the document library described above.
  5. A Power Automate Premium licence (or a per-flow plan) for the flow owner, because the HTTP action is a premium connector.

In D365, the job history in the Data management workspace shows every run triggered by the flows, just as if you had clicked Run project yourself.

Export project and job history in the D365 Data management workspace

Export project and job history in the D365 Data management workspace

Getting a bearer token with the HTTP action

All three flows start the same way. They first read their SharePoint list. If the list has nothing to work on, the flow ends there without requesting a token. An idle run costs a single SharePoint call.

The token comes from the Entra ID v2 endpoint using the client credentials grant:

  • Method: POST
  • URI: https://login.microsoftonline.com/<tenant-id>/oauth2/v2.0/token
  • Header: Content-Type: application/x-www-form-urlencoded
  • Body (expression):
concat(
'grant_type=client_credentials&client_id=',
variables('V_ClientID'),
'&client_secret=',
variables('V_Client_Secret'),
'&scope=https://<your-environment>.operations.dynamics.com/.default'
)

A Parse JSON action with this schema reads the response, and Set variable stores access_token in V_Bearer_Token:

{
"type": "object",
"properties": {
"token_type": { "type": "string" },
"expires_in": { "type": "integer" },
"ext_expires_in": { "type": "integer" },
"access_token": { "type": "string" }
}
}

Every call to D365 then carries the header Authorization: Bearer @{variables('V_Bearer_Token')}. A condition checks that the token variable isn’t empty before the main loop runs.

Flow 1: Start the export

Flow 1 reads the package list and starts one export per row. It runs on a daily recurrence trigger.

  1. Initialize the variables V_ClientID, V_Client_Secret, V_Bearer_Token and V_Execution_Id.
  2. Get items from the Export Pakete list.
  3. If the list isn’t empty, get the bearer token as shown above.
  4. Apply to each row of the list:
    1. Set V_Execution_Id to a new, unique ID: concat('PBix-', guid()). The prefix makes these runs easy to spot in the D365 job history.
    2. Call ExportToPackage with the HTTP action.
    3. Create a row in Export History with the title, the execution ID and Ready, Started and Finished set to No.
Flow 1 with the HTTP action that calls ExportToPackage

Flow 1 with the HTTP action that calls ExportToPackage

The HTTP action posts to .../data/DataManagementDefinitionGroups/Microsoft.Dynamics.DataEntities.ExportToPackage. The body uses the list item’s title as both project name and package name:

{
"definitionGroupId": "@{items('For_each')?['Title']}",
"packageName": "@{items('For_each')?['Title']}",
"executionId": "@{variables('V_Execution_Id')}",
"reExecute": false,
"legalEntityId": "<your legal entity>"
}

legalEntityId is the company the export runs in. If you export from several companies, add a column to the package list and use that instead of a fixed value.

Flow 2: Check the export status

Flow 2 asks D365 how each open export is doing and flags the finished ones as ready.

  1. Get items from Export History with the OData filter Ready eq 0.
  2. If there are any, get a bearer token.
  3. Apply to each history row:
    1. Call GetExecutionSummaryStatus with the row’s execution ID.
    2. Parse the response.
    3. If the status is Succeeded, update the row and set Ready to Yes.
Flow 2 polls GetExecutionSummaryStatus and sets Ready

Flow 2 polls GetExecutionSummaryStatus and sets Ready

The request body is just the execution ID:

{ "executionId": "@{items('For_each')?['ExecutionID']}" }

The response is a plain OData value, so the Parse JSON schema is short:

{
"type": "object",
"properties": {
"@odata.context": { "type": "string" },
"value": { "type": "string" }
}
}

The condition compares body('Parse_JSON_execution_state')?['value'] with Succeeded. Rows that are still Executing stay at Ready = No and are checked again on the next run.

Flow 3: Download and extract the package

Flow 3 downloads every ready package and unpacks it into the SharePoint library.

  1. Get items from Export History with the filter Ready eq 1 and Started eq 0.
  2. If there are any, get a bearer token.
  3. Apply to each history row:
    1. Set Started to Yes right away, so the row is not picked up twice.
    2. Call GetExportedPackageUrl with the execution ID and parse the response. Its value is the download URL.
    3. Create new folder in Export Downloads: <package name>/<timestamp>.
    4. Download the ZIP with a second HTTP action: GET on the URL from step 2. No Authorization header here, because the URL already contains a SAS token.
    5. Create file <execution ID>.zip in the new folder, with the HTTP response body as content.
    6. Extract folder (SharePoint connector) unpacks the ZIP into the same folder, with Overwrite on.
    7. Delete file removes the ZIP.
    8. Set Finished to Yes.
Flow 3 downloads the ZIP, extracts it and updates the history row

Flow 3 downloads the ZIP, extracts it and updates the history row

The folder path keeps each run separate and sorts by date:

concat(
items('For_each')?['Title'],
'/',
convertFromUtc(utcNow(), 'W. Europe Standard Time', 'yyyy-MM-dd_HH-mm-ss')
)

After a run, each folder holds the entity file (e.g. Customers V3.csv) plus the Manifest.xml and PackageHeader.xml that every DMF package contains.

An extracted package in the Export Downloads library

An extracted package in the Export Downloads library

Reading the data in Power BI

In Power BI, use the SharePoint folder connector on the site and pick the newest file of each entity. Because the folder names are timestamps in yyyy-MM-dd_HH-mm-ss format, sorting by folder path is enough. Here is a sketch in Power Query:

let
Source = SharePoint.Files("https://<tenant>.sharepoint.com/sites/<site>", [ApiVersion = 15]),
Files = Table.SelectRows(Source, each
Text.Contains([Folder Path], "/DX_CUSTOMERS/")
and [Name] = "Customers V3.csv"),
Latest = Table.First(Table.Sort(Files, {{"Folder Path", Order.Descending}})),
Csv = Csv.Document(Latest[Content], [Delimiter = ",", Encoding = 65001, QuoteStyle = QuoteStyle.Csv]),
Result = Table.PromoteHeaders(Csv, [PromoteAllScalars = true])
in
Result

Once the semantic model is published, schedule its refresh in the Power BI service after Flow 3 has run.

Lessons learned and tips

  • Keep the client secret out of the flow. For a quick start, a variable works. For production, read the secret from Azure Key Vault or a secret-type environment variable. Also turn on Secure inputs and Secure outputs on the token action, so neither the secret nor the token shows up in the run history.
  • Handle more than Succeeded. The status can also be Failed, PartiallySucceeded or Canceled. If you only check for success, a failed export stays in the queue and is polled forever. Add a Failed flag, or an error column, and send a notification.
  • Watch out for variables in loops. Apply to each runs in parallel by default, and variables are global to the flow. Either set the loop’s concurrency to 1 or generate the execution ID in a Compose action inside the loop.
  • Download right after asking for the URL. The package URL contains a SAS token that expires, and the file itself is removed from blob storage after seven days. Flow 3 therefore fetches the URL and downloads in the same run.
  • Poll more often if you need to. Flows 2 and 3 only do real work when the history list has open rows. Running them every 15 or 30 minutes costs almost nothing and gets the data to SharePoint sooner.
  • Clean up both ends. Use Job history cleanup in D365, and a retention policy or a small extra flow for old folders in the SharePoint library.
  • Restart by editing the list. If a download fails, set Started back to No in the history list and Flow 3 picks the row up again on its next run. Support doesn’t need to touch the flows.

Conclusion

With three small flows, two SharePoint lists and one document library, you get a daily, unattended export from D365 F/SCM into Power BI. You don’t need Azure or custom code, and you can use the export projects you already have. Adding another dataset is a new row in a list. Because each step runs on its own, a failed run is easy to find and easy to restart.

Thanks again to Vijay Yelmame for the Postman walkthrough that started it all.

Links

Dynamics 365 Contact Center

Copilot Serivce Workspace (aka. Contact Center) is great Addon for Dynamics 365 Customer Service. It’s purpose is to handle direct customer interaction. It supports different channels like Chat, SMS and Phone calls. You can configure customer routing, e.g.

  • Priority based (Silver / Gold)
  • Callcenter agent compentency (e.g. Sales, Technic)

Copilot adds values to the solution:

  • Copilot can be used to generate Knowledge Base articles based on cases
  • Copilot can summarize cases and propose solutions based on Kbx articles.
  • Copilot can handle customer chats as well as customer phone calls

I’ve created a short video to demonstrate Dynamics 365 Concact Center capabilities:

Configure Best-Price discounts in D365 F/SCM Unified Price Management

Here is my second video on Unified Price Management explaining how to Best-Price discounts work and how to configure concurrent Back-to-School and Black-Friday discounts.

How to use your custom product attributes in Unified Price Management

I’ve recorded a short video that shows how to you use product attributes in Unified Price Management

Dual Write Error “Failed to authenticate” and “Unable to get access token” from Tier1 Cloud-Hosted to Dynamics 365 Sales

Since Tier1 Cloud Hosted Environments (CHE) will be deprecated, there are still good reasons (💰) to use them anyway instead of UDEs. Tier1 CHE from withing Lifecycle Services can be paired with Power Platform environment including Dual Write Configuration with Dynamics 365 Sales. In the Tier1 configuration I’ve encountered an authentication error at creating new records in FO.

History and symptoms 🤒

I’ve deployed a new Tier1 Dev/Test Environment 10.0.43 to the linked Azure Subscriptions. At the configuration dialog in LCS I’ve enabled Power Platform integration based on Dynamics 365 Sandbox. Deployment took a while but succeeded. 👍

After the deployment I’ve restored a AxDB database with some basic configurations and performed a full database synchronization in Visual Studio. 👍

Next I’ve linked the D365 Finance and Supply Chain machine with the deployed D365 Sales Sandbox environment from the LCS environment details page. Finally I’ve enabled the Dual Write Configuration also from the LCS environment details page. 👍

In Power Platform Admin Center, Environment, Dynamics 365 Apps two solutions were already deployed. Dynamics 365 Dual Write Core and Dynamics 365 Dual Write Application Core. Because the environment was a sales prototype I’ve added the Dynamics 365 Dual Write Human Resource, Dynamics 365 Dual Write Finance, Dynamics 365 HR Common Tables (!), Dynamics 365 Dual Write Global Address Book and Dynamics 365 Dual Write Supply Chain Solution from the App Source. 👍

In Dynamics 365 Finance & Supply Chain at the Data Management Workspace I’ve imported the Core Solution and Supply Chain Solution. The table mappings have been populated successfully and I’ve choosen to synchronize only one legal entity (company) with Sales. 👍

The basic table mappings (e.g. Legal Entities, Customer Groups, Currencies, Units, Size, Colors, etc.) including initial synchronization from FO to Sales were successful. I’ve also enabled synchronization between CustomersV3 and Accounts👍

In Dynamics 365 Sales it was possible to create a new account from type customer, link it to the corresponding legal entity and assign a customer group. The customer account from Dynamics 365 Sales was successfully synchronized into FO within seconds and became a customer. 👍

Vice versa, from Dynamics 365 Finance Supply Chain to Dynamics 365 Sales did not work. As soon as a new records in a synchronized table was create a Dual Write error message came up. No matter if it was a customer, product, etc. 🤬

Unable to write data to entity accounts
Authentication failed with error
Failed to authenticate for https://__crm4.dynamics.com/api/data/v9.0/accounts
For information on troubleshooting see
https://go.microsoft.com/fwlink/?linkid=2244045
Unable to get access token 

Solution Step-by-Step

Microsoft has cut off CHE connections from accessing tenant information. I found some blog posts from other folks dealing with Business Events and a Microsoft documentation to setup Onebox environments. Following the instructions I’ve done the following:

App Registration

I’ve created an App Registration in EntraID. I’ve added the URL of the D365 FO Environment as response URL from type Web as well as the URL including /oauth

I gave API permissions to User.Read, User.Read.All, Dynamics ERP AX.FullAccess and LCS user_impersonation.

Self-Signed Certificate via PowerShell

Following the documentation I’ve create a simple self-signed certification via PowerShell on the Tier1 VM.

$cername = "myselfcert"

$cert = New-SelfSignedCertificate -Subject "CN=$certname" -CertStoreLocation "Cert:\CurrentUser\My" -KeyExportPolicy Exportable -KeySpec Signature -KeyLength 2048 -KeyAlgorithm RSA -HashAlgorithm SHA256

Export-Certificate -Cert $cert -FilePath "C:\Users\Admin051a5b362b\Desktop\$certname.cer"

Add to root-authorities

The export generates a .cer file. By double clicking the file you can install the file on the computer. I’ve done this twice. As local machine and choosen the place to be the root certificate authorities. The same with installation as user and also selected the installation to be placed in the root certificate authorities.

web.config and wif.config

The web.config file can be found at K:\AosService\WebRoot directory. I’ve made a copy before editing and changed the following lines. The spn: is the application ID from the app registration. The thumbprint can be found in the .cer file on the Details tab.

<add key="Aad.Realm" value="spn:<your application ID>" />
<add key="Infrastructure.S2SCertThumbprint" value="<certificate thumbprint>" />
<add key="GraphApi.GraphAPIServicePrincipalCert" value="<certificate thumbprint>" />

In the wif.config I’ve also added the application ID

<?xml version="1.0"?>
<system.identityModel>
  <identityConfiguration>
    <securityTokenHandlers>
      <securityTokenHandlerConfiguration>
        <audienceUris>
       <!-- WARNING: MUST be first element; updated at web role instance startup -->
          <add value="spn:00000015-0000-0000-c000-000000000000" />
          <add value="spn:MY_APP_ID_HERE" />

Application User in Dynamics 365 Power Platform

In the Power Platform Admin Center, on the environment page, under settings in groups users I’ve added an application user. I’ve assigned System Administrator Role like the already existing Finance and Operations Service account.

EntraID Application in FO

Finally to avoid any additional problems I’ve also create a new record in Dynamics 365 Finance Supply Chain at the EntraID Applications page.

Finally the synchronization from Dynamics 365 Finance Supply Chain to Dynamics 365 Sales was working. Customers, Products, Sales Orders, Invoices etc. can be created in FO and be found Sales. 💚

Dual Write Installation error missing dependencies

Since the original Dual Write Orchestration packages has been replaced by a pack of smaller packages, its needed to setup the packages in the correct order. You can deploy a Power Platform environment using the Dynamics 365 template from within LCS.

Also from the Environment Full Details page, you can trigger the installation of Dual Write solution and initial configure the Dual Write solution. You will end up with Dual Write Core and Dual Write Application Core Solutions installed. To have the full Dual Write Experience you have to install the other Packages as well.

Dynamics 365 Dual Write Packages from App Source

You might run into an installation error when deploying Dual-Write packages from App Source.

Error details
How to troubleshoot
To fix this problem retry installation. For directions on how to do this see here.

msdyn_Dynamics365SupplyChainExtendedAnchor
NotProvided
Solution manifest import: FAILURE: The following solution cannot be imported: Dynamics365SupplyChainExtended. Some dependencies are missing. The missing dependencies are : <MissingDependencies><MissingDependency canResolveMissingDependency="True"><Required type="1" schemaName="cdm_worker" displayName="Worker" solution="HCMCommon (2.2.0.3)" /><Dependent type="10" schemaName="msdyn_transferorder_receivingcontactpersonnel" displayName="msdyn_transferorder_receivingcontactpersonnel" parentSchemaName="cdm_worker" parentDisplayName="Worker" /></MissingDependency></MissingDependencies> , ProductUpdatesOnly : False
Dual Write installation error, dependencies Worker missing

There is also an additional required package that is not labeled “Dual Write” but required, the Dynamics 365 HR Common Tables package:

Dynamics 365 HR Common Tables solution required for Dual Write

Here is an order of installation that worked for me (Apr. 2025)

  • Dual Write Human Resource solution
  • Dual Write Finance Solution
  • Dynamics 365 HR Common Tables
  • Dual Write Global Address Book
  • Dual Write Supply Chain

Custom Connector as C# Sandbox for PowerAutomate Flow

Ever wanted to habe a Code Sandbox to run a script in Flow? I had this issue to calculate an SHA1 hash value which is not possible with builtin flow functions. Obvious solution would be to put it in an Azure Function. There is a solution by Valentin Gasenko to create a custom connector and utilize the Code feature.

You may create a custom connector that connects to nowhere😉 with a fake method and place C# code there. It has some limitations to an Azure Function e.g. you can’t install packages etc. but it might help for many other issues.

OpenAPI Definiton

Create a new OpenAPI Definition Swagger file that defines a method you would like to use in your flow. Here is an example for an API with a method called executeScript that takes a string as input and returns a string as output.

{
  "openapi": "3.0.0",
  "info": {
    "title": "Script Execution Service",
    "version": "1.0.0",
    "description": "A simple REST API that executes a script and returns text output."
  },
  "paths": {
    "/ExecuteScript": {
      "get": {
        "summary": "Executes a script and returns text output",
        "operationId": "executeScript",
        "parameters": [
          {
            "name": "input",
            "in": "query",
            "description": "The script input as a string",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful execution",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "output": {
                      "type": "string",
                      "description": "The output of the executed script"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid input provided"
          }
        }
      }
    }
  }
}

Create a custom connector in PowerAutomate

In PowerAutomate create a new custom connector. You may have to lookup the custom connector link by clicking on “… More” on the left pane.

Enable Custom Connector in PowerAutomate

Create a new custom connector by importing the OpenAPI definition file. Provide name and description if you like. Make sure to set the Host to valid URL. It doesn’t matter if there is no real host with this name. I use fakeapi.local in my example.

Create a custom connector that connects to nowhere

Place C# code

Go to the Code section and enable code by selection the slider. Choose the method you want to use. In my example it’s the executeScript Method. Copy the C# code you want to execute in the code editor window below. This is an example code that reads the input parameter from the request and returns it in a Hello statement.

public class Script : ScriptBase
{
  public override async Task ExecuteAsync()
  {
    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
    string url = this.Context.Request.RequestUri.PathAndQuery;
    string parsedUrl = url.Split('?')[1];

    var paramsCollection = HttpUtility.ParseQueryString(parsedUrl);
    string value = paramsCollection["input"];

    response.Content = CreateJsonContent("{\"message\": \"Hello "+value+"\"}");
    return response;
  }
}
Place C# script in the custom connectors code section

Save and Test

You have to select “Create Connector” before testing. If your code is not working you will get an error here. If the creation was successful you can test your connector.

Test C# sandbox in PowerAutomate

Use C# Sandbox in your Flow

Simply create a new flow or use an existing one. You we’ll find the connector under the custom connectors. In my example it has a single action to execute the code to which I pass the value of the variable Name.

Include C# sandbox in PowerAutomate Flow
C# code executed in PowerAutomate Flow

Like in the connector test scenario, it executes the C# script and returns Hello and the provided value.

Order Change: Notify customers using Business Events and Flow

The combination of Dynamics 365 Finance and Supply Chain Management Cloud ERP and Microsoft Flow helps to automate many tasks. For example, you can easily notify a customer about changes regarding the confirmed shipping date.

Concept

  • Configure a Blob Storage Endpoint for Business Events
  • Create a Change Based alert for ShippingDateConfirmed
  • Add a flow that triggers on new events
  • Read Email from sales order and notify customer

Configure a Business Event Endpoint

Business events in Dynamics 365 FSCM can be used to notify external systems. It supports different endpoint types like Azure Event Hub, HTTPS web hook and Blob Storage Account. I personally prefer to use a storage account because it’s a very cheap and easy to use, understand and support cloud infrastructure.

In Entra ID admin Portal (Azure Active Directory) create a new app registration. Note the client ID and create a new secret. Note the application secret as well.

In order to use a Blob Container for Business Events you need some resources. First, of course a storage account with a public endpoint. Copy the Storage Account Connection String. On the menu on the left side select Storage browser. Navigate to the Blob Storage and create a new container.

Azure Storage Account for storing business events in a blob container

Next, create a key vault to store the connection string. When creating the key vault make sure to use Vault Access Policies. At the key vault create a new secret and place the connection string there.

Azure Key Vault with Vault Access Policies

In the Key Vault switch to Access Policies and create a new one. Assign the registered app the rights to list and get secrets.

Assign List and Get secrets permissions to the service principal

In Dynamics 365 Finance and Supply Chain Management open the Business Event Catalog (System Administration > Setup > Business Events). Switch to the Enpoint tab and create a new Blob Endpoint. In the dialog provide

  • a meaningful name
  • the name of the Blob container
  • client ID from the app registration
  • client secret
  • the key vaults URI (from the key vaults overview pane)
    e.g. https://yourkeyvault.vault.azure.net/
  • the name of the secret that holds the connection string

Switch to the Business Event Catalog and filter the Business Event ID entries containing the term “Alert”. Make sure you select the BusinessEventsAlertEvent and click on Activate. In the dialog select the legal entity and the recently created blob endpoint.

Business Events Catalog in Dynamics 365 Finance and Supply Chain Management

Test Business Event Endpoint configuration for Alerts

Make sure you have a batch job handling change based alerts in Dynamics 365 Finance and Supply Chain. If you don’t have such a batch job, create on from System Administration > Periodic Tasks > Alerts > Change Based Alerts. Change the recurrence to no end date and provide a time interval e.g 10 minutes.

In Dynamics 365 FSCM go to an existing sales order or create one. In the top menu switch to Options and select Create custom alert.

Create a change based alert for sales orders in Dynamics 365 Finance Supply Chain Management

In the alert dialog choose the Confirmed Ship Date from the field drop down. This will change the alert trigger to Has Changed. Make sure to activate the Send Externally Option as well. Save the alert rule.

Create a change based alert for sales orders in Dynamics 365 Finance Supply Chain Management

Change the confirmed ship date in the sales order. Depending on the time interval for change based alerts batch job you will get notified that the value has been changed.

Alert notification that the shipping date confirmed has been changed

Switch to the Azure Portal and go to your storage account. From the Storage Browser, select the Blob Storage and the container you created for the business events. There you should see at least one entry named as GUID.

Azure storage account with business events

Download and open the file in a text editor. I should contain the JSON for the business event. You will find the Sales Order Number in KeyValue1 and the legal entity in the DataAreaId property. You can use this values to lookup the sales order in D365.

Business Event JSON text

Create a flow to notify the customer

Go to Power Automate and create a new flow that triggers when a blob entry is created or modified. Check if the event was a shipping data change and send an email to the customer. The flow may look like this.

Flow in Power Automate to handle business events

The first action Get Blob Content is used to download the event file itself. The next action will parse the event JSON string. Since the blob file has no file extension, it is necessary to provide the content as string() to the Parser. The schema can be generated by example. E.g. copy the JSON string from the test file and flow will generate the schema.

Parse JSON action for Dynamics 365 Business Events

Because the blob storage account may be used by different business events in the future it is advised to add a condition to check if the alert is triggered by the shipping date.

Condition if change based alert was triggered by changing the shipping date

Next use the DataAreaId and KeyFieldValue1 to lookup the Sales Order in Dynamics 365 FSCM by combining both values seperated with a comma e.g. demf,001234

Lookup sales order in Dynamics 365 Finance and Supply Chain from flow

Add a second condition to check if there is an Email address provided in the sales header. If so use the Send Email action to notify the customer. If required you may work on the FALSE condition and lookup the customer instead to find an email address.

Send email with the updated shipping date to the customer

The final email may look like this

Email with the new shipping date

*.Wildcard Select in Synapse View on customized table can shift results set to wrong column

Combining views and wildcard selects on customized tables in Synapse may cause unforeseen problems. For example, I’ve created a view that combines all fields one table with additional fields from a joined table.

SELECT table1.*, table2.field1, table2.field2, table3.field3
from
table1 left outer join table2 on
table1.id = table2.id and table1.dataareaid = table2.dataareaid

In Synapse Workspace I’ve added a SQL Database called “Dynamics” and create the view. PowerBI Users would use the views from the Dynamics database instead of loading and joining raw tables by themselves.

A customization was made on table1. An additional field was added. The new field was synced to Synapse. Querying table1 in Synapse returned all its fields. Executing the SQL query on which the view is based als returned all the fields from table1 and the joined table2. However, the view itself in the Dynamics database in Synapse did not show the new field in the returned column headers.

The Lake Database in Synapse returned correct dataset but the view used its original field definition. So the data was shifted 1 field to the right and all values after the customized field were in the wrong column. For example, the value 1 from the new field was returned in the column Partition. The value 2024 from the Partition was returned as Field1. The value from Field1 was returned in Field2.

A quick and simple fix is to rerun the ALTER VIEW statement with the original code.

Insert Dynamics 365 FSCM OData via Excel VBA

If you have the need to insert data into Dynamics 365 Finance and Supply Chain Management via Excel but don’t want to use the Addin you can do this task manually via VBA Code. Here is an example how to create a new customer via CustomerV3 OData entity.

App Registration

You have to register a new application in Entra ID. Allow API access to Dynamics 365 FSCM Entities. Create an application secret and note the value somewhere. Next you have to register the App ID (Client ID) in Dynamics 365 FSCM in the Entra ID Application form.

Microsoft Entra ID application registration in Dynamics 365 Finance and Supply Chain Management

Authentication

OData in Dynamics 365 FSCM uses OAuth for authentication. You have to request an access token first and use it later for the communication with D365. In Excel create a VBA function that request an access token based on the Application Registration.

Function CreateAccessToken() As String
  Dim tenantId As String
  Dim clientId As String
  Dim secret As String
  Dim scope As String

'PROVIDE YOUR DATA HERE
  tenantId = ""
  clientId = ""
  secret = ""
  scope = "https://YOUR_D365FO_URL_dynamics.com/.default"

  Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")

  strURL = "https://login.microsoft.com/" & tenantId & "/oauth2/v2.0/token"
  strData = "tenant_id=" & tenantId & "&client_id=" & clientId & "&client_secret=" & secret & "&grant_type=client_credentials&scope=" & scope & ""

  objHTTP.Open "POST", strURL, False
  objHTTP.send (strData)
  strResponse = objHTTP.responseText
  Set objHTTP = Nothing

  Dim posAccessToken As Integer
  posAccessToken = InStr(1, strResponse, "access_token", vbTextCompare)
  posAccessToken = posAccessToken + 14

  Dim token As String
  token = Right(strResponse, Len(strResponse) - posAccessToken)
  token = Left(token, Len(token) - 2)

  CreateAccessToken = token
End Function

Data Entry Form

Create a form in Excel to provide the required data. In my example there is no AccountNum because it is generated in Dynamics 365 FSCM from a Number Sequence. Add a button and link it to a VBA Macro.

CustomerV3 mandatory fields in Excel

Call the CustomerV3 Entity from VBA

To create a new customer create an HTTP POST request to the CustomerV3 OData Entity. Provide the required fields as JSON String. Here is an example:

Sub CreateCustomerV3()

  Dim url As String
  Dim http As Object
  Dim data As String
  Dim response As String

  Dim token As String
  token = CreateAccessToken

  url = "https://YOUR_D365FO_ENV.dynamics.com/data/CustomersV3"

  Set http = CreateObject("MSXML2.ServerXMLHTTP.6.0")

  Dim name As String
  Dim cur As String
  Dim grp As String
  Dim cmp As String

  name = Cells(3, 3).Value
  cur = Cells(4, 3).Value
  grp = Cells(5, 3).Value
  cmp = Cells(6, 3).Value

  data = "{""OrganizationName"" : "" " & name & " "",""SalesCurrencyCode"": """ & cur & """,""CustomerGroupId"": """ & grp & """,""dataAreaId"" : """ & cmp & """}"

  http.Open "POST", url, False
  http.setRequestHeader "Authorization", "Bearer " & token
  http.setRequestHeader "Content-Type", "application/json"
  http.send data

  response = http.responseText

  'Only for debugging
  Cells(10, 5).Value = response
End Sub