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

PowerBI development with Claude Code

Combining PowerBI and Claude Code can help to speed up report development. I’ve recorded a 4 part mini-series to demonstrate the usage of Claude Code in report project. This is not about vibe coding reports, but to delegate boring coding and modeling tasks.

Part 1: Use PowerBI Project Files with Claude Code in VSCode, create the initial Claude.md file and let Claude generate a source database documentation:

Part 2: Use Claude Code to modify the data model. Generate a date dimension table and use the planning mode:

Part 3: Create a reusable skill for a date dimension table and test it in another report

Part 4: Generate DAX Measures from requiremet prompt to summarize the Totals and Year-by-year comparison without telling Claude Code which formulars to use:

PowerBI Write-Back with User Data Functions

PowerBI is great for data analysis and visualization. It also supports What-If simulations, but lacks the ability to save analysis results in a structured way. In combination with Fabric User Data Functions you can implement a simple Write-Back to a data source in Fabric (e.g. database, lakehouse).

I’ve implemented a small demo application in Fabric. The workspace contains a SQL database, a User Data Function and a PowerBI report.

The database holds an Adventure Works demo dataset. It contains two additional tables (Carrier and CarrierSelected). The Carrier tables hols package delivery providers and the price for a package to be delivered. The CarrierSelected has only 1 record with the selected carrier.

CarrierPricePerQty
UPS12
DHL13
DPD7
Post11

PowerBI creates a table that flags the selected carrier. I’m using two measures to get the actual selected carrier and price. If nothing is seleced, the price is from the record flagged as selected, otherwise the selected (aka. clicked) record in the table visual.

Active Carrier =
VAR SelectedCarrier = SELECTEDVALUE(Carrier[Carrier])
VAR DefaultCarrier =
CALCULATE(
SELECTEDVALUE(Carrier[Carrier]),
Carrier[Status] = "Selected"
)
RETURN
IF(ISBLANK(SelectedCarrier), DefaultCarrier, SelectedCarrier)
Active PricePerQty =
VAR SelectedPrice = SELECTEDVALUE(Carrier[PricePerQty])
VAR DefaultPrice =
CALCULATE(
SELECTEDVALUE(Carrier[PricePerQty]),
Carrier[Status] = "Selected"
)
RETURN
IF(ISBLANK(SelectedPrice), DefaultPrice, SelectedPrice)

The actual price is used to calculate the shipping costs by multiplying the SalesOrderDetails.Qty with the package price. Selecting a different carrier immediately updates the price.

The magic happens when clicking on the “Write back to SQL” button. This is a blank button with the Action enabled and a linked data function. It takes the value from the “Active Carrier” measure and passes it as parameter to the data function.

The User Data Function is an artifact in the Fabric workspace. It can uses connections to data sources in fabric. In my case it connects to the SQL database. The function has a string input parameter “carrier”. The code deletes the existing entry in the CarrierSelection table and inserts the new one.

import fabric.functions as fn
import uuid
udf = fn.UserDataFunctions()
@udf.connection(argName="sqlDB",alias="AdventureWorksL")
@udf.function()
def write_one_to_sql_db(sqlDB: fn.FabricSqlConnection, carrier: str) -> str:
connection = sqlDB.connect()
cursor = connection.cursor()
delete_carrier = "DELETE FROM [SalesLT].[CarrierSelection]"
cursor.execute(delete_carrier)
insert_description_query = "INSERT INTO [SalesLT].[CarrierSelection] VALUES (?)"
cursor.execute(insert_description_query, carrier)
connection.commit()
cursor.close()
connection.close()
return "The carrier was updated"

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:

MCP for Dataverse with Claude Desktop

The power of MCP (Model Context Protocol) allows you to connect an AI application like Copilot oder Claude to an Application, in a way that the AI application can work with the connected system in the background. For example, the MCP impementation for Microsoft Dataverse allows an AI application to query and manipulate records in the Dataverse. Sounds simple but here is the magic:

  • Query dataverse in natural language ๐Ÿ’ฌ e.g. “Find me all german customers”
  • Chat in your natural language no matter how Dataverse was setup in the background, e.g. talk in English ๐Ÿ‡ฌ๐Ÿ‡ง and let AI work an a German ๐Ÿ‡ฉ๐Ÿ‡ช dataverse installation
  • Let the AI investigate the database structure ๐Ÿ”. If you dont provide information how tables are related it will find out by its own,

MCP for SQL with Claude Desktop

LLMs like ChatGTP, Copilot, Gemini, Claude etc. are very convenient for lot of tasks like coding, generating and optimizing documents and data analysis. With an MCP (Model Context Protocol) Server that connects to a SQL database you can use your AI to perform business intelligence tasks without the need of a classic BI Tool like PowerBI.

I’ve made a short video that shows Claude Desktop connecting to an Azure SQL Database (Adeventure Works) and performs data analysis and visualization:

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

VSCode AL: Download Symbols Authorization has failed

A colleague developing for On-Prem Business Central using VS Code ran into an Authentication error downloading symbols. Although he provided his domain user and password the authentication failed.

Authorization has failed or the credentials have expired. The credential cache has been cleaned. Any access to reach Business Central would require new authorization.

Symptoms

  • Business Central On-Prem installation on Domain Joined Server
  • Authentication Windows
  • Visual Studio Code installed on a non-domain joined Windows 11 client (WORKGROUP)
  • Work Account (Azure AD / Entra ID User) logged on on in Windows 11
  • Open URL in Browser asks for User + Password but works correctly ๐Ÿค”
  • AL: Download Symbols reports an error

Solution: RunAs

A workaround that solved the issue was to use the RunAs command and provide the domain user + password.

runas /user:AD_DOMAIN\AD_USER "C:\PATH_TO_VSCODE.EXE"
Download Symbols Successful

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. ๐Ÿ’š