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"

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:

Mirror Dynamics 365 Finance SCM Entity Database in Fabric

There are many ways to analyze Dynamics 365 Finance and Supply Chain data in Fabric. One way is to replicate the Entity Export database. Then load it into a Lake House and combine it with additional data for reporting. Here is a video that shows the complete process from scratch:

Considerations

Entity Export to Azure SQL

Exporting entities in Dynamics 365 Finance and Supply Chain to your own Azure SQL DB has been around for a long time. There are some considerations and limitations when using your BYOD (Bring Your Own Database) feature with Fabric:

  • Sizing: 100+ DTUs are required. Free and small Basic versions are not supported.
  • Networking: Public Endpoint and allow Azure Services
  • Security: System Assigned Managed Identity ON
  • Table: Column store tables are not supported
  • Table: Primary Index required

*.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.

Analyze Dynamics 365 Finance / SCM Data in Synapse (Video)

Load Dynamics 365 F/SCM in Synapse and visualize in PowerBI

Synapse link for Dataverse is the replacement for Export to Datalake which has been deprecated in 2023. Although it is called link for Dataverse, it can be used to access Dynamics 365 Finance and Supply Chain tables (and CE data from dataverse as well).

Synapse link for Dataverse

SQL Track Changes has to be enabled in D365 F/SCM. Creates, Updates and Deletes are written to a storage account in CSV format. Synapse is running a spark pool that converts the CSVs into Deltalake format which relies on the (Open-Standard) Parquet format. As result you can see and query the F/SCM tables in the lake like it were tables in a relational database.

Synapse Workspace with Dynamics 365 Finance and Supply Chain data

Good news, Synpase has a serverless SQL pool and a public SQL endpoint. You can find the SQL endpoint from the Manage Icon (down left) > SQL Pools > Select your pool > Workspace SQL Endpoint.

You can create databases in this SQL pool and create views based on the tables in the datalake. For example join CustTable and DirPartyTable and provide a view that contains customer data with a name and address.

Create views in Synapse Workspace

You can use the development workspace in Synapse web based workspace but you could also use other tools to connect e.g. SQL Server Management Studio. Tables in the datalake and views in another database can be accessed.

SQL Endpoint for Synapse Workspace

PowerBI has a built-in connector for Synapse Workspace. You can easily load data from the tables and also from the views.

PowerBI Synapse connector

6 ways to aggregated a value from a related table in PowerBI

Aggregating values from a related table is a common task in PowerBI. However, there are many ways how to achieve this goal. Here are a few examples:

Note: I'm using an Adventure Works Lite Demo DB and using SalesOrderHeader + SalesOrderDetail to aggregate the LineAmount from the details.

1) Aggregate at data source

If you have the option to push aggregation logic to the data source you should do so. Especially if the data source is SQL Server because its designed to execute queries and perform aggregations in a very effective way.

select h.SalesOrderID, sum(d.LineTotal) as SumLineTotals 
from SalesLT.SalesOrderHeader as h
left outer join SalesLT.SalesOrderDetail as d
on h.SalesOrderID = d.SalesOrderID
group by h.SalesOrderID

2) Join in Power Query

Load both tables using PowerQuery. Select the SalesOrderHeader table. From Home tab, select Merge Queries. Join both tables via SalesOrderID and select LEFT OUTER JOIN as join type.

Navigate the joined table but select Aggregate instead of Expand. Aggregate the LineTotals from the SalesOrderDetails.

3) Calculated Column in Power Query (M)

You can also use PowerQuery to sum up values from another table. Note “Rename” is the name of the prev. Step in my PowerQuery.

= Table.AddColumn(Rename, "LineTotalsPQ", 
each let no = [SalesOrderID] 
in List.Sum(
Table.SelectRows(#"SalesLT SalesOrderDetail", each [SalesOrderID] = no)[LineTotal]
))

4) Calculated Column in Data Model (DAX)

Create a new column at the SalesOrderHeader in the data model using SUMX function.

Col_SumLineTotal = SUMX(
FILTER('SalesLT SalesOrderDetail',
'SalesLT SalesOrderDetail'[SalesOrderID] = 
EARLIER('SalesLT SalesOrderHeader'[SalesOrderID])),
'SalesLT SalesOrderDetail'[LineTotal])

5) Measure

Make sure you have an active 1:n relation from SalesOrderHeader to SalesOrderDetails via SalesOrderID. Create a new measure on the SalesOrderHeader using DAX.

M_SumLineAmount = SUM('SalesLT SalesOrderDetail'[LineTotal])

Add a table visual to the report and place the SalesOrderID and the measure from the SalesOrderHeader table.

6) Visual

Make sure you have an active 1:n relation from SalesOrderHeader to SalesOrderDetails via SalesOrderID. Add a table visual and place the SalesOrderID from the SalesOrderHeader table. Add the LineAmount from the SalesOrderLines and choose to aggregate as Sum.

Version Control for PowerBI with Git

When working on PowerBI projects for a longer time or supporting a customer, version control would be a desireable feature. In many cases PowerBI files are stored on file share or SharePoint. At this moment (August 2023) there is no integrated version control feature in PowerBI Desktop. But we can use featues from different software products to build a version control strategy for PowerBI.

Version Control for PowerBI with Git

There is a preview feature call “Save as PowerBI project” in PowerBI Desktop. This will split the PowerBI report into multiple files that contain the model definition, the report layout and some more files. Now that we have multiple files in a project folder, one can come up with the idea to put these files under a version control system.

You can use Git as version control system on your local PC or wherever the PowerBI reports are developed. Git has a local repository and can be connected to central repository. In Azure DevOps you can setup projects using Git as version control system. Connect your local PowerBI Git repository with Azure DevOps to manage your PowerBI report development.

Here you can read the original post from Microsoft: https://powerbi.microsoft.com/en-us/blog/deep-dive-into-power-bi-desktop-developer-mode-preview/

I’ve made a video that shows you how to setup version control and connect PowerBI with DevOps:

Data I/O Cheat Sheet for Dynamics 365 F/SCM

There are many ways how to access, import and export data in Dynamics 365 Finance & Supply Chain Management. Find here a one page PDF summary of 12 common ways. Every solution has it pros and cons.