Hive BDC: e-invoicing for Dynamics AX and D365 F&O

Balsoft Data Connector: send and receive e-invoices (XRechnung, ZUGFeRD) for Microsoft Dynamics 365 F&O, AX 2012 and AX 2009.

Installation · one day

  1. Download the setup (130 MB, signed by Balsoft)
  2. Install service and dashboard
  3. Dynamics module installed by Balsoft
  4. Send a test document as XRechnung
  5. Go-live

D365 F&O · AX 2012 · AX 2009

Hive BDC

Outgoing and incoming invoices in one flow

Hive BDC turns a posted sales invoice into a German e-invoice in XRechnung or ZUGFeRD format. Order confirmations, quotations, collection letters, purchase orders and payment advices go out as the PDF your ERP prints. Each document can be mailed to the recipient and filed in SharePoint, ShareFlex, DocuWare or the DMS you already use. In the other direction Hive BDC takes your vendors' e-invoices from a mailbox, a folder or your DMS (for example SharePoint) and over Peppol, reads XRechnung and ZUGFeRD in CII and UBL, checks them against EN 16931 and compares the totals. Hive BDC then creates a pending vendor invoice, a purchase order invoice or an invoice journal in Dynamics.

A Windows service does the work in the background, a dashboard shows what went out and what came in and holds the settings. On the ERP side, Hive BDC includes a module for Dynamics, which Balsoft installs for you.

Supported systems

Standards

XRechnung 3.0.2ZUGFeRD 2.5.2EN 16931

How Hive BDC works

Two directions, one product. Outgoing invoices leave Dynamics as XRechnung or ZUGFeRD, incoming e-invoices land in Dynamics as vendor invoices. Both run as batch jobs, nobody has to touch a file.

Accounts receivable (AR): how an e-invoice goes out of Dynamics AX 2009, AX 2012 and D365 F&O on-premises (LBD)

From the posted invoice in Dynamics to the customer's mailbox and your archive, without anyone touching it.

Receivables (AR)EN 16931 XRechnung 3.0.2 ZUGFeRD 2.5.2
DynamicsDynamicsSales orderSO-10234PostSales invoiceSample Ltd.1.190,00 €AX 2012AX 2009ERP moduleExport batchHive BDCHive BDCDashboardConnectedSERVICERunningv1.15.1LICENSEValidEXPORTS6TodayRECENT EXPORTSDocument IDTypeFormat7000001234SalesInvoicexrechnungAB0004711SalesConfirmationpdfAN0000815SalesQuotationpdfHive BDC DashboardCustomer mailboxMicrosoft 365DMSArchiveSharePointShareFlexDocuWared.velopM-FilesELOenaiowindreamDoxisnscaleOther DMSSales invoiceINV-10234Sample Ltd.1.190,00 €E-INVOICE · EN 16931<Invoice></Invoice>
01

The invoice is posted in Dynamics

What it does

Accounts receivable (AR): XRechnung and ZUGFeRD

Sales invoices become e-invoices according to EN 16931, checked before they leave, including credit notes, cash discounts and settlement house data.

Accounts payable (AP)

Your vendors' e-invoices arrive by mail, folder, DMS (for example SharePoint) or Peppol. Hive BDC reads XRechnung and ZUGFeRD (CII and UBL), checks them and creates a pending vendor invoice, a purchase order invoice or an invoice journal.

PDF documents

Order confirmations, quotations, collection letters, purchase orders and payment advices are sent as the PDF your ERP prints.

Smaller PDFs

With Compress PDF on, each PDF is made smaller once before it goes out: fonts keep only the letters used, and images placed above 300 ppi go to 200 ppi. Pages look the same. A ZUGFeRD invoice from AX 2009 went from 945 KB to 138 KB.

Mail through Microsoft 365

Recipient, subject and text come from the ERP. Documents are sent from your own mailbox and kept in its sent items.

SharePoint, DocuWare and other DMS

Documents go straight into a SharePoint library, also with ShareFlex, with metadata columns filled from the document. DocuWare, d.velop, ELO, M-Files, enaio, windream and other DMS read the finished files from the output folder (local, network share or a synced cloud folder) with their folder import or their own connector.

Runs on your servers

Document content never goes to Balsoft or another service, only to the recipients and the SharePoint site you set up.

Test systems stay internal

Documents from a test or development system go to your test recipients, never to a customer or vendor.

E-invoice formats

Which format a customer receives is set in the ERP, per invoice: XRechnung as XML, or ZUGFeRD as a PDF with the same XML inside. Both follow EN 16931 and are checked before they leave.

XRechnung

3.0.2

For the public sector (with Leitweg-ID) and every recipient who processes XML.

Format
XML, UN/CEFACT CII syntax
Standard
EN 16931 with the German CIUS
Specification ID
urn:cen.eu:en16931:2017#compliant#urn:xeinkauf.de:kosit:xrechnung_3.0
File
One XML file per invoice
Tested with
KoSIT validator 1.6.3, configuration 2026-08-31 (XRechnung 3.0.2)

ZUGFeRD

2.5.2 / Factur-X 1.09.2

For recipients who want a readable PDF and machine-readable data in one file.

Format
PDF/A-3b with the XML attached
Profile
XRECHNUNG: the same XRechnung 3.0.2 XML as on the left
Inside the PDF
xrechnung.xml, Factur-X XMP metadata, sRGB output intent, fonts embedded
Source
The invoice PDF your ERP prints
Tested with
Mustang 2.26 with the ZUGFeRD 2.5.2 rules and the PDF/A-3 check (veraPDF), KoSIT validator for the XML

What the e-invoice carries

  • Invoices, credit notes and corrected invoices (type codes 380, 381 and 384)
  • Leitweg-ID for public-sector buyers (BT-10)
  • Order, contract, project, delivery note and tender references (BT-11 to BT-17)
  • Cash discounts (Skonto), also in several stages, in the machine-readable XRechnung form
  • VAT per rate and category, so 19 % and 7 % on one invoice
  • Bank details, delivery date and remittance information
  • Item numbers, GTIN and country of origin per line
  • Settlement house identifiers, for example for Aktivbank

Every invoice runs through a check of the EN 16931 and XRechnung business rules before it is written. Each finding is logged with its official rule ID, for example BR-DE-15, so missing data can be fixed in the ERP.

All other documents (order confirmations, quotations, collection letters, purchase orders, payment advices) go out as the PDF your ERP prints.

Hive BDC follows new versions of both standards. XRechnung 4.0, based on the revised EN 16931, is expected in spring 2027; XRechnung 3.0.2 stays valid until at least 31 July 2027. Updates arrive through the dashboard.

E-invoicing by Dynamics version

Licence and source code

Licence

EUR 10,000

per year, plus VAT

  • Support and updates included
  • Licence file valid for 12 months, a new one comes with each yearly invoice
  • Installed from the dashboard, no restart needed
Read the licence terms

Source code

The complete source code of Hive BDC is public on GitHub. Your IT, auditors and partners can check exactly what runs on your server before you install it.

Source available, not open source: running, copying or changing the software needs a licence from Balsoft.

View source code on GitHub

System requirements

What you need to install and use Hive BDC. Your Balsoft consultant goes through it with you and installs the ERP part.

Dynamics

  • Dynamics 365 Finance & Supply Chain Management in the cloud.
  • The Hive BDC module in the ERP, delivered and installed by Balsoft.
  • A batch server that runs the Hive BDC export jobs.

Azure

  • An Azure Service Bus namespace or a storage account in your Azure subscription; Dynamics 365 and Hive BDC exchange the documents through it.
  • Balsoft sets up the connection; the credentials stay in your Key Vault.

Microsoft 365 (for sending by mail)

  • Mail: an Entra ID app registration with Mail.Send and the sending mailbox. Balsoft provides a script that sets it up and limits it to that mailbox.
  • HTTPS access from the server to login.microsoftonline.com and graph.microsoft.com.

Licence

  • A licence file from Balsoft, bound to your Microsoft 365 tenant. It unlocks e-invoices, PDF documents and SharePoint.
  • The dashboard warns before it expires. Documents are never lost: without a valid licence they wait in the export folder.

SharePoint or another DMSOptional

  • Only when documents should also be filed. Hive BDC runs without it.
  • SharePoint: an app registration with Sites.ReadWrite.All, or Sites.Selected on the target site.
  • DocuWare, d.velop, ELO, M-Files and other DMS: Hive BDC writes the finished files to an output folder (local, network share or a cloud folder synced to the server), and the DMS reads them with its folder import or its own connector.

Downloads

Version 1.15.1, released 27 November 2026, about 130 MB, Windows x64

Hive BDC Setup

Version 1.15.1, released 27 November 2026, about 130 MB, Windows x64

One file with everything you install: the Windows service and its dashboard. The file is signed by Balsoft GmbH; Windows shows Balsoft GmbH as the publisher. Installed systems update themselves from the dashboard.

Download Setup 1.15.1

SHA-256 checksum:
d059b0a5ce15a657a9b4b5537ac03cf7496b685b950e2f9d896d761393320800

Installation and user guides

PDF, in English. The German version is on the German page.

  • Microsoft Dynamics AX 2012PDF, 5.8 MB
  • Dynamics 365 Finance and OperationsComing soon
  • Microsoft Dynamics AX 2009PDF, 6.3 MB

Microsoft 365 setup for mail and SharePoint

For your IT administrator. Only needed if Hive BDC mails documents or files them in SharePoint.

Setup guide

Hive BDC signs in to Microsoft 365 with two app registrations in your tenant: one may send as a single mailbox, the other may write only to the SharePoint sites you name. Two PowerShell scripts set them up in Azure Cloud Shell in a few minutes. They ask before changing anything and never create or store a secret. The guide walks through every step.

Setup guide, PDF, 0.4 MB

Run it in Azure Cloud Shell

Each app is set up in two steps in Azure Cloud Shell (PowerShell) of your tenant: first the app registration, then its permissions. The steps can be done by different administrators. Each script shows the tenant and asks before it changes anything; add -WhatIf for a dry run.

The source of both scripts is also public in the Hive BDC repository on GitHub.

1Create the app registration

Creates "Hive BDC SharePoint" without any permission and prints its client ID. Needs Application Administrator.

Azure Cloud Shell
Invoke-WebRequest https://balsoft.de/downloads/hive-bdc/New-HiveBDCSharePointApp.ps1 -OutFile New-HiveBDCSharePointApp.ps1./New-HiveBDCSharePointApp.ps1
New-HiveBDCSharePointApp.ps1
<#.SYNOPSIS    Step 1 of 2 for SharePoint: creates the app registration "Hive BDC SharePoint", without any permission..DESCRIPTION    Run in Azure Cloud Shell (PowerShell). It shows the tenant and asks first, skips the app    if it already exists, creates its service principal, and prints the IDs plus the    command for step 2, Grant-HiveBDCSharePointAccess.ps1, which assigns Sites.Selected and the site access.    Role: Application Developer or Application Administrator. No client secret is    created; the script prints how. -WhatIf shows the plan only..EXAMPLE    ./New-HiveBDCSharePointApp.ps1#>#Requires -Version 5.1[CmdletBinding(SupportsShouldProcess = $true)]param(    [ValidateLength(3, 120)]    [string] $AppName = 'Hive BDC SharePoint',    [ValidatePattern('^[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$')]    [string] $TenantId,    # Do not ask before changing the tenant.    [switch] $Force)$ErrorActionPreference = 'Stop'function Write-Step { param([string] $Text) Write-Host "`n== $Text" -ForegroundColor Cyan }function Write-Ok { param([string] $Text) Write-Host "   [ok]   $Text" -ForegroundColor Green }function Write-Skip { param([string] $Text) Write-Host "   [have] $Text" -ForegroundColor DarkGray }function Write-Note { param([string] $Text) Write-Host "   $Text" -ForegroundColor Gray }# Only Cloud Shell has no browser to sign in with; there a device code is the way in.# Elsewhere the browser is used, because many tenants block sign-in by code.$isCloudShell = [bool]$env:ACC_CLOUD -or ("$env:AZUREPS_HOST_ENVIRONMENT" -like '*cloud-shell*')$useDeviceCode = $isCloudShell# Runs az and returns its JSON output; a failed command stops the script.function Invoke-Az {    $output = & az @args --only-show-errors --output json    if ($LASTEXITCODE -ne 0) { throw "'az $($args[0]) $($args[1])' failed (exit code $LASTEXITCODE), see above." }    $text = ($output | Out-String).Trim()    if (-not $text) { return }    $parsed = $text | ConvertFrom-Json    return $parsed   # return, not the pipeline, so a JSON array arrives as its items}function Get-AzCliAccount {    $ErrorActionPreference = 'Continue'   # 'not signed in' arrives on stderr    $text = (& az account show --output json 2>$null | Out-String).Trim()    if ($LASTEXITCODE -eq 0 -and $text) { return $text | ConvertFrom-Json }}if ($WhatIfPreference) { Write-Host 'DRY RUN - nothing will be changed.' -ForegroundColor Yellow }# -- 1. sign-in -----------------------------------------------------------------------Write-Step '1/2 Sign-in'if (-not (Get-Command az -ErrorAction SilentlyContinue)) {    throw 'Azure CLI (az) was not found. Run this script in Azure Cloud Shell (PowerShell).'}$account = Get-AzCliAccountif (-not $account -or ($TenantId -and $account.tenantId -ne $TenantId)) {    $login = @('login', '--allow-no-subscriptions', '--only-show-errors', '--output', 'none')    if ($TenantId) { $login += @('--tenant', $TenantId) }    if ($useDeviceCode) { $login += '--use-device-code' }    & az @login    if ($LASTEXITCODE -ne 0) { throw 'az login failed.' }    $account = Get-AzCliAccount}$tenantId = $account.tenantId$tenantName = (@((Invoke-Az rest --method GET --url 'https://graph.microsoft.com/v1.0/organization?$select=displayName').value) |    Select-Object -First 1).displayNameWrite-Note "tenant:  $tenantName ($tenantId)"Write-Note "account: $($account.user.name)"if (-not $Force -and -not $WhatIfPreference) {    $answer = Read-Host "   Create '$AppName' in '$tenantName'? (y/n)"    if ($answer -notmatch '^(y|yes|j|ja)$') { Write-Note 'Stopped. Nothing was changed.'; return }}# -- 2. app registration and service principal ----------------------------------------Write-Step "2/2 App registration '$AppName'"$apps = @(Invoke-Az ad app list --display-name $AppName | Where-Object { $_.displayName -eq $AppName })if ($apps.Count -gt 1) { throw "There are $($apps.Count) app registrations named '$AppName'. Remove the extra ones, or use -AppName." }$reg = $apps | Select-Object -First 1if ($reg) { Write-Skip "app registration exists (appId $($reg.appId))" }elseif ($PSCmdlet.ShouldProcess($AppName, 'Create the app registration')) {    $reg = Invoke-Az ad app create --display-name $AppName --sign-in-audience AzureADMyOrg    Write-Ok "created the app registration (appId $($reg.appId))"}if (-not $reg) { Write-Note 'Dry run ends here: the app does not exist yet.'; return }$appId = $reg.appId$sp = Invoke-Az ad sp list --spn $appId | Select-Object -First 1if ($sp) { Write-Skip "service principal exists ($($sp.id))" }elseif ($PSCmdlet.ShouldProcess($appId, 'Create the service principal')) {    for ($attempt = 1; -not $sp; $attempt++) {   # a new app needs a few seconds to replicate        try { $sp = Invoke-Az ad sp create --id $appId }        catch { if ($attempt -ge 4) { throw }; Start-Sleep -Seconds 10 }    }    Write-Ok "created the service principal ($($sp.id))"}# -- next -----------------------------------------------------------------------------$grant = "./Grant-HiveBDCSharePointAccess.ps1 -AppId $appId -SiteUrl https://<tenant>.sharepoint.com/sites/<site>"Write-Host "`nDONE, the app has no permissions yet" -ForegroundColor YellowWrite-Host "  Tenant ID  $tenantId"Write-Host "  Client ID  $appId"Write-Note ''Write-Note 'Step 2, assign the permissions:'Write-Note "  $grant"Write-Note 'Client secret (shown once, enter it straight into the Hive BDC dashboard):'Write-Note "  az ad app credential reset --id $appId --append --display-name HiveBDC --years 2 --query password -o tsv"
2Assign the permissions

Grants Sites.Selected with admin consent and gives the app write access to the sites you name, and to no other. Use the client ID from step 1. Needs Global Administrator (or Privileged Role Administrator) and SharePoint Administrator.

Azure Cloud Shell
Invoke-WebRequest https://balsoft.de/downloads/hive-bdc/Grant-HiveBDCSharePointAccess.ps1 -OutFile Grant-HiveBDCSharePointAccess.ps1./Grant-HiveBDCSharePointAccess.ps1 -AppId <client-id> -SiteUrl https://contoso.sharepoint.com/sites/Invoices
Grant-HiveBDCSharePointAccess.ps1
<#.SYNOPSIS    Step 2 of 2 for SharePoint: gives the Hive BDC SharePoint app write access to the sites    you name, and to no other..DESCRIPTION    Run in Azure Cloud Shell (PowerShell) after New-HiveBDCSharePointApp.ps1.    Steps, each skipped when already in place:      1. Azure CLI: show the tenant and the app, and ask before changing anything.      2. Entra ID: Microsoft Graph application permission Sites.Selected with admin consent.         Sites.Selected alone opens no site at all.      3. SharePoint: write access on each -SiteUrl. This needs the delegated permission         Sites.FullControl.All, which an Azure CLI sign-in does not carry, so it signs in         once more through Microsoft's public client "Microsoft Graph Command Line Tools"         (the one Connect-MgGraph uses): in a browser on a PC, by code in Cloud Shell. No         PowerShell module needed. If the tenant blocks sign-in by code, run this script on         your own computer instead of Cloud Shell.    -AllSites grants Sites.ReadWrite.All (every site) instead and skips step 3.    Roles: Privileged Role Administrator or Global Administrator for the consent, and    SharePoint Administrator who is a member of each site. -WhatIf shows the plan only.    Another site later: run it again with that site..EXAMPLE    ./Grant-HiveBDCSharePointAccess.ps1 -AppId 11111111-2222-3333-4444-555555555555 -SiteUrl https://contoso.sharepoint.com/sites/Invoices#>#Requires -Version 5.1[CmdletBinding(SupportsShouldProcess = $true)]param(    # Application (client) ID printed by New-HiveBDCSharePointApp.ps1.    [Parameter(Mandatory = $true)]    [ValidatePattern('^[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$')]    [string] $AppId,    # Sites Hive BDC uploads to; a library or folder URL is reduced to its site.    [ValidatePattern('^https://[^/\s]+\.sharepoint\.(com|us|de|cn)(/\S*)?$')]    [string[]] $SiteUrl = @(),    [switch] $AllSites,    [ValidatePattern('^[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$')]    [string] $TenantId,    # Do not ask before changing the tenant.    [switch] $Force)$ErrorActionPreference = 'Stop'if (-not $AllSites -and $SiteUrl.Count -eq 0) { throw 'Name the sites with -SiteUrl, or use -AllSites.' }$GraphAppId = '00000003-0000-0000-c000-000000000000'   # Microsoft Graph, same in every tenant$GraphV1 = 'https://graph.microsoft.com/v1.0'$RoleName = if ($AllSites) { 'Sites.ReadWrite.All' } else { 'Sites.Selected' }function Write-Step { param([string] $Text) Write-Host "`n== $Text" -ForegroundColor Cyan }function Write-Ok { param([string] $Text) Write-Host "   [ok]   $Text" -ForegroundColor Green }function Write-Skip { param([string] $Text) Write-Host "   [have] $Text" -ForegroundColor DarkGray }function Write-Note { param([string] $Text) Write-Host "   $Text" -ForegroundColor Gray }# Only Cloud Shell has no browser to sign in with; there a device code is the way in.# Elsewhere the browser is used, because many tenants block sign-in by code.$isCloudShell = [bool]$env:ACC_CLOUD -or ("$env:AZUREPS_HOST_ENVIRONMENT" -like '*cloud-shell*')$useDeviceCode = $isCloudShell# Runs az and returns its JSON output; a failed command stops the script.function Invoke-Az {    $output = & az @args --only-show-errors --output json    if ($LASTEXITCODE -ne 0) { throw "'az $($args[0]) $($args[1])' failed (exit code $LASTEXITCODE), see above." }    $text = ($output | Out-String).Trim()    if (-not $text) { return }    $parsed = $text | ConvertFrom-Json    return $parsed   # return, not the pipeline, so a JSON array arrives as its items}# One Microsoft Graph call through 'az rest'. The body goes through a file because# Windows PowerShell 5.1 and az.cmd both mangle quotes in JSON arguments.function Invoke-GraphAz {    param([string] $Method, [string] $Path, $Body)    $azArgs = @('rest', '--method', $Method, '--url', "$GraphV1/$Path")    $bodyFile = $null    if ($null -ne $Body) {        $bodyFile = [IO.Path]::GetTempFileName()        [IO.File]::WriteAllText($bodyFile, ($Body | ConvertTo-Json -Depth 8))        $azArgs += @('--body', "@$bodyFile", '--headers', 'Content-Type=application/json')    }    try { return Invoke-Az @azArgs }    finally { if ($bodyFile) { Remove-Item -LiteralPath $bodyFile -ErrorAction SilentlyContinue } }}function Get-AzCliAccount {    $ErrorActionPreference = 'Continue'   # 'not signed in' arrives on stderr    $text = (& az account show --output json 2>$null | Out-String).Trim()    if ($LASTEXITCODE -eq 0 -and $text) { return $text | ConvertFrom-Json }}# The application ids a site permission is granted to, from either property Graph returns.function Get-PermissionAppIds {    param($Permission)    foreach ($property in @('grantedToIdentitiesV2', 'grantedToIdentities')) {        if ($Permission.PSObject.Properties[$property]) {            foreach ($identity in @($Permission.$property)) {                if ($identity -and $identity.PSObject.Properties['application'] -and $identity.application) { $identity.application.id }            }        }    }}# A delegated Microsoft Graph token for Sites.FullControl.All, which Azure CLI cannot get.# It signs in through Microsoft's public client "Microsoft Graph Command Line Tools" (the# one Connect-MgGraph uses) without that module, whose current versions fail on older# PowerShell hosts. With a browser: authorization code with PKCE on a localhost redirect.# Without one (Cloud Shell): a device code, which some tenants block by Conditional Access.# The token stays in memory.$GraphCliClientId = '14d82eec-204b-4c2f-b7e8-296a70dab67e'function ConvertTo-Base64Url { param([byte[]] $Bytes) [Convert]::ToBase64String($Bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_') }function Get-BrowserToken {    param([string] $Tenant, [string] $Scope)    $probe = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::Loopback, 0)    $probe.Start(); $port = $probe.LocalEndpoint.Port; $probe.Stop()    $redirect = "http://localhost:$port/"    $listener = [System.Net.HttpListener]::new()    $listener.Prefixes.Add($redirect)    $listener.Start()    try {        $random = [byte[]]::new(32)        [System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($random)        $verifier = ConvertTo-Base64Url $random        $sha = [System.Security.Cryptography.SHA256]::Create()        $challenge = ConvertTo-Base64Url ($sha.ComputeHash([Text.Encoding]::ASCII.GetBytes($verifier)))        $state = [guid]::NewGuid().ToString('N')        $query = @{            client_id = $GraphCliClientId; response_type = 'code'; redirect_uri = $redirect; scope = $Scope            code_challenge = $challenge; code_challenge_method = 'S256'; state = $state; prompt = 'select_account'        }.GetEnumerator() | ForEach-Object { "$($_.Key)=$([Uri]::EscapeDataString($_.Value))" }        $url = "https://login.microsoftonline.com/$Tenant/oauth2/v2.0/authorize?" + ($query -join '&')        Write-Note 'A browser window opens for the sign-in. If it does not, open this address:'        Write-Note "  $url"        if ($IsMacOS) { & open $url } elseif ($IsLinux) { & xdg-open $url 2>$null } else { Start-Process $url }        $pending = $listener.GetContextAsync()        if (-not $pending.Wait([TimeSpan]::FromMinutes(5))) { throw 'No sign-in within 5 minutes. Run the script again.' }        $context = $pending.Result        $answer = $context.Request.QueryString        $page = [Text.Encoding]::UTF8.GetBytes('<html><body style="font-family:sans-serif">Signed in. You can close this tab and go back to PowerShell.</body></html>')        $context.Response.ContentType = 'text/html; charset=utf-8'        $context.Response.OutputStream.Write($page, 0, $page.Length)        $context.Response.Close()        if ($answer['error']) { throw "Sign-in failed: $($answer['error_description'])" }        if ($answer['state'] -ne $state) { throw 'Sign-in answer did not match this request.' }        $token = Invoke-RestMethod -Method POST -Uri "https://login.microsoftonline.com/$Tenant/oauth2/v2.0/token" -Body @{            grant_type = 'authorization_code'; client_id = $GraphCliClientId; code = $answer['code']            redirect_uri = $redirect; code_verifier = $verifier; scope = $Scope        }        return $token.access_token    }    finally { $listener.Stop(); $listener.Close() }}function Get-DeviceCodeToken {    param([string] $Tenant, [string] $Scope)    $base = "https://login.microsoftonline.com/$Tenant/oauth2/v2.0"    $code = Invoke-RestMethod -Method POST -Uri "$base/devicecode" -Body @{ client_id = $GraphCliClientId; scope = $Scope }    Write-Host "   $($code.message)" -ForegroundColor Yellow    $deadline = (Get-Date).AddSeconds([int]$code.expires_in)    $interval = [int]$code.interval    while ((Get-Date) -lt $deadline) {        Start-Sleep -Seconds $interval        try {            $token = Invoke-RestMethod -Method POST -Uri "$base/token" -Body @{                grant_type = 'urn:ietf:params:oauth:grant-type:device_code'; client_id = $GraphCliClientId; device_code = $code.device_code            }            return $token.access_token        }        catch {            $reason = try { ($_.ErrorDetails.Message | ConvertFrom-Json).error } catch { '' }            if ($reason -eq 'authorization_pending') { continue }            if ($reason -eq 'slow_down') { $interval += 5; continue }            if ($reason -in @('access_denied', 'invalid_grant')) {                throw ('Sign-in with a code was refused; your organisation may block it. Run this script on your own ' +                       'computer instead (PowerShell with Azure CLI), where the sign-in opens a browser.')            }            throw        }    }    throw 'The sign-in code expired. Run the script again.'}if ($WhatIfPreference) { Write-Host 'DRY RUN - nothing will be changed.' -ForegroundColor Yellow }# -- 1. sign-in -----------------------------------------------------------------------Write-Step '1/3 Sign-in'if (-not (Get-Command az -ErrorAction SilentlyContinue)) {    throw 'Azure CLI (az) was not found. Run this script in Azure Cloud Shell (PowerShell).'}$account = Get-AzCliAccountif (-not $account -or ($TenantId -and $account.tenantId -ne $TenantId)) {    $login = @('login', '--allow-no-subscriptions', '--only-show-errors', '--output', 'none')    if ($TenantId) { $login += @('--tenant', $TenantId) }    if ($useDeviceCode) { $login += '--use-device-code' }    & az @login    if ($LASTEXITCODE -ne 0) { throw 'az login failed.' }    $account = Get-AzCliAccount}$tenantId = $account.tenantId$tenantName = (@((Invoke-GraphAz GET 'organization?$select=displayName').value) | Select-Object -First 1).displayNameWrite-Note "tenant:  $tenantName ($tenantId)"Write-Note "account: $($account.user.name)"$app = Invoke-Az ad app show --id $AppId$AppName = $app.displayName$appId = $app.appId$sp = Invoke-Az ad sp list --spn $appId | Select-Object -First 1if (-not $sp) { throw "The app $appId has no service principal. Run New-HiveBDCSharePointApp.ps1 first." }Write-Note "app:     $AppName ($appId)"Write-Note "access:  $(if ($AllSites) { 'Sites.ReadWrite.All, every site' } else { 'Sites.Selected, write on the sites below' })"foreach ($url in $SiteUrl) { Write-Note "site:    $url" }if (-not $Force -and -not $WhatIfPreference) {    $answer = Read-Host "   Grant this access in '$tenantName'? (y/n)"    if ($answer -notmatch '^(y|yes|j|ja)$') { Write-Note 'Stopped. Nothing was changed.'; return }}# -- 2. permission and admin consent ---------------------------------------------------Write-Step "2/3 Permission $RoleName"$graphSp = Invoke-Az ad sp show --id $GraphAppId$role = @($graphSp.appRoles | Where-Object { $_.value -eq $RoleName -and $_.allowedMemberTypes -contains 'Application' }) |    Select-Object -First 1# Listing the permission makes it show under "API permissions"; the consent below grants it.$listed = @($app.requiredResourceAccess | Where-Object { $_.resourceAppId -eq $GraphAppId } |    ForEach-Object { $_.resourceAccess } | Where-Object { $_.id -eq $role.id })if ($listed) { Write-Skip "$RoleName is listed" }elseif ($PSCmdlet.ShouldProcess($AppName, "List the permission $RoleName")) {    Invoke-Az ad app permission add --id $appId --api $GraphAppId --api-permissions "$($role.id)=Role" | Out-Null    Write-Ok "listed $RoleName"}$consented = @((Invoke-GraphAz GET "servicePrincipals/$($sp.id)/appRoleAssignments").value |    Where-Object { $_.appRoleId -eq $role.id -and $_.resourceId -eq $graphSp.id })if ($consented) { Write-Skip "$RoleName is consented" }elseif ($PSCmdlet.ShouldProcess($AppName, "Grant admin consent for $RoleName")) {    Invoke-GraphAz POST "servicePrincipals/$($sp.id)/appRoleAssignments" @{        principalId = $sp.id; resourceId = $graphSp.id; appRoleId = $role.id    } | Out-Null    Write-Ok "$RoleName consented"}# -- 3. write access per site ---------------------------------------------------------$failed = @()if ($AllSites) { Write-Step '3/3 Sites (not needed with -AllSites)' }else {    Write-Step '3/3 Write access on the sites'    Write-Note 'Granting a site needs Sites.FullControl.All for your account; sign in once more:'    $scope = 'https://graph.microsoft.com/Sites.FullControl.All'    $graphToken = if ($useDeviceCode) { Get-DeviceCodeToken $tenantId $scope } else { Get-BrowserToken $tenantId $scope }    $headers = @{ Authorization = "Bearer $graphToken" }    foreach ($url in $SiteUrl) {        $uri = [Uri]$url        $segments = @($uri.AbsolutePath.Trim('/').Split('/') | Where-Object { $_ })        $siteRef = if ($segments.Count -ge 2 -and $segments[0] -in @('sites', 'teams')) {            "$($uri.Host):/$($segments[0])/$([Uri]::UnescapeDataString($segments[1]))"        } else { $uri.Host }        try {            $site = Invoke-RestMethod -Headers $headers -Uri "$GraphV1/sites/$siteRef`?`$select=id,webUrl"            $permissions = Invoke-RestMethod -Headers $headers -Uri "$GraphV1/sites/$($site.id)/permissions"            $existing = @($permissions.value | Where-Object { (Get-PermissionAppIds $_) -contains $appId }) | Select-Object -First 1            if ($existing -and @($existing.roles | Where-Object { $_ -in @('write', 'owner', 'fullcontrol') })) {                Write-Skip "$($site.webUrl): $($existing.roles -join ', ')"            }            elseif ($existing) {                if ($PSCmdlet.ShouldProcess($site.webUrl, 'Raise the access to write')) {                    Invoke-RestMethod -Headers $headers -Method PATCH -Uri "$GraphV1/sites/$($site.id)/permissions/$($existing.id)" `                        -Body (@{ roles = @('write') } | ConvertTo-Json) -ContentType 'application/json' | Out-Null                    Write-Ok "$($site.webUrl): raised to write"                }            }            elseif ($PSCmdlet.ShouldProcess($site.webUrl, 'Grant write access')) {                $body = @{ roles = @('write'); grantedToIdentities = @(@{ application = @{ id = $appId; displayName = $AppName } }) }                Invoke-RestMethod -Headers $headers -Method POST -Uri "$GraphV1/sites/$($site.id)/permissions" `                    -Body ($body | ConvertTo-Json -Depth 5) -ContentType 'application/json' | Out-Null                Write-Ok "$($site.webUrl): write"            }        }        catch {            $failed += $url            $detail = if ($_.ErrorDetails.Message) { $_.ErrorDetails.Message } else { $_.Exception.Message }            Write-Warning "$url : $detail"            Write-Note 'Your account needs SharePoint Administrator and has to be a member of this site.'        }    }}# -- next -----------------------------------------------------------------------------Write-Host "`nDONE" -ForegroundColor YellowWrite-Host "  Tenant ID  $tenantId"Write-Host "  Client ID  $appId"if ($failed) { Write-Host "  NOT granted: $($failed -join ', ') (fix the cause above and run again)" -ForegroundColor Red }Write-Note 'Hive BDC dashboard: Settings > Connections > SharePoint, then Test SharePoint.'

Hive BDC runs with a licence from Balsoft. Without one, the dashboard opens but no documents are processed. Get in touch for a licence or a test installation.

Contact us