Dynamics 365 Business Central: Manage environments via Admin Center API

Dynamics 365 Business Central

Hi, Readers.
A few months ago we have talked about how to install AppSource Apps via Admin Center API. And recently I saw a question, is it possible to use the Admin Center API to manage the environment in Cloud.

Yes, in this post, we’ll try it out together. (The authenticates section of the post is consistent with how to install AppSource Apps via Admin Center API)

The tools needed for this test:

Authenticate.ps1: This sample authenticates to Azure Active Directory (AAD) an obtains an access token.

Environments.ps1: This file contains examples of API calls that can be used to manage environments for a customer.

In short, there are only two steps needed to do this. The first is Authentication and the second is Managing Environment.

Authentication

Pre-requisites:
・Microsoft Azure App Registrations (If you don’t already have one, get a subscription to Microsoft Azure)

1. Sign into Azure Portal.

2. Enter App registrations in search, and then choose the related link.

3. Choose New registration.

4. Enter Name and select who can use this application or access this API, then choose Register.
For Example:
Name: Business Central App Install API
Who can use this application or access this API: Accounts in this organizational directory only.

5. Choose a Add a Redirect URI in the Overview page.

6. Choose Add a platform.

7. Choose Mobile and desktop applications.

8. Add http://localhost in Custom redirect URIs, then choose Configure.

Successfully updated

9. Choose API permissions, then choose Add a permission.

10. Choose Dynamics 365 Business Central.

11. Choose Delegated permissions.

12. Select all permissions, then choose Add permissions.

13. Choose Manifest, set “allowPublicClient”: true, then choose Save.

14. Back to the overview

Now you can update Parameters in Authenticate.ps1.

For example:

15. Run Windows PowerShell ISE by the administrator, then run Install-Module AzureAD command.

Add-Type -Path “C:\Program Files\WindowsPowerShell\Modules\AzureAD\2.0.2.130\Microsoft.IdentityModel.Clients.ActiveDirectory.dll” # Install-Module AzureAD to get this

Choose Yes.

Completed.

Note: After the download is complete, you need to update the path to the folder. Otherwise, it will report an error.

New version is 2.0.2.130.(2021/04/16)

The required settings are all complete.
For example:

# This sample authenticates to Azure Active Directory (AAD) an obtains an access token.
# The access token can be used for authenticating to Business Central APIs.


# Parameters
$aadAppId = "3263173a-0507-4ef5-9f25-ca4a5c47ebec"        # partner's AAD app id
$aadAppRedirectUri = "http://localhost"                   # partner's AAD app redirect URI
$aadTenantId = "d8f36038-1f93-4543-affc-5dc92b6ee871"    # customer's tenant id


# Load Microsoft.IdentityModel.Clients.ActiveDirectory.dll
Add-Type -Path "C:\Program Files\WindowsPowerShell\Modules\AzureAD\2.0.2.130\Microsoft.IdentityModel.Clients.ActiveDirectory.dll" # Install-Module AzureAD to get this


# Get access token
$ctx = [Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext]::new("https://login.microsoftonline.com/$aadTenantId")
$redirectUri = New-Object -TypeName System.Uri -ArgumentList $aadAppRedirectUri
$platformParameters = New-Object -TypeName Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters -ArgumentList ([Microsoft.IdentityModel.Clients.ActiveDirectory.PromptBehavior]::Always)
$accessToken = $ctx.AcquireTokenAsync("https://api.businesscentral.dynamics.com", $aadAppId, $redirectUri, $platformParameters).GetAwaiter().GetResult().AccessToken
Write-Host -ForegroundColor Cyan 'Authentication complete - we have an access token for Business Central, and it is stored in the $accessToken variable.'

# Peek inside the access token (this is just for education purposes; in actual API calls we'll just pass it as one long string)
$middlePart = $accessToken.Split('.')[1]
$middlePartPadded = "$middlePart$(''.PadLeft((4-$middlePart.Length%4)%4,'='))"
$middlePartDecoded = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($middlePartPadded))
$middlePartDecodedPretty = (ConvertTo-Json (ConvertFrom-Json $middlePartDecoded))
Write-Host "Contents of the access token:"
Write-Host $middlePartDecodedPretty

16. Run all commands in Windows PowerShell ISE.

Enter the sign in information.

Choose Accept (承諾).

If you see the message “Authentication complete – we have an access token for Business Central, and it is stored in the $accessToken variable.” and there are no errors, it means the Authentication is successful.

Note: If the App registrations is not set sufficiently, the following permission error may occur.

“0” 個の引数を指定して “GetResult” を呼び出し中に例外が発生しました: “AADSTS650057: Invalid resource. The client has requested access to a resource which is not listed in the requested permissions in the client’s application registration. Client app ID: 3263173a-0507-4ef5-9f25-ca4a5c47ebec(Business Central App Install API). Resource value from request https://api.businesscentral.dynamics.com. Resource app ID: 996def3d-b36c-4153-8607-a6fd3c01b89f. List of valid resources from app registration: 00000003-0000-0000-c000-000000000000.

Test Video:

Managing Environments

Once the Authentication is complete, the rest is relatively simple.
You can refer to the commands in Environments.ps1 to view and create the environments.

For example: Get, Create, Copy and Delete.
Get list of environments:

# Get list of environments
$response = Invoke-WebRequest `
    -Method Get `
    -Uri    "https://api.businesscentral.dynamics.com/admin/v2.3/applications/businesscentral/environments" `
    -Headers @{Authorization=("Bearer $accessToken")}
Write-Host (ConvertTo-Json (ConvertFrom-Json $response.Content))

Get an environment:

# Get list of environments
$newEnvironmentName = "SandboxUS"
$response = Invoke-WebRequest `
    -Method Get `
    -Uri    "https://api.businesscentral.dynamics.com/admin/v2.3/applications/businesscentral/environments/$newEnvironmentName" `
    -Headers @{Authorization=("Bearer $accessToken")}
Write-Host (ConvertTo-Json (ConvertFrom-Json $response.Content))

Create a new environment:

# Create new environment
$newEnvironmentName = "MyNewSandboxViaAPI"
$response = Invoke-WebRequest `
    -Method Put `
    -Uri    "https://api.businesscentral.dynamics.com/admin/v2.3/applications/businesscentral/environments/$newEnvironmentName" `
    -Body   (@{
                 EnvironmentType = "Sandbox"
                 CountryCode     = "JP"
              } | ConvertTo-Json) `
    -Headers @{Authorization=("Bearer $accessToken")} `
    -ContentType "application/json"

Copy production environment to a sandbox environment:

# Copy production environment to a sandbox environment
$environmentName = "Production"
$newEnvironmentName = "MyNewSandboxAsACopy"
$response = Invoke-WebRequest `
    -Method Post `
    -Uri    "https://api.businesscentral.dynamics.com/admin/v2.3/applications/businesscentral/environments/$environmentName" `
    -Body   (@{
                 EnvironmentName = $newEnvironmentName
                 Type            = "Sandbox"
              } | ConvertTo-Json) `
    -Headers @{Authorization=("Bearer $accessToken")} `
    -ContentType "application/json"

Delete an environment:

# Delete an environments
$newEnvironmentName = "TestSandbox"
$response = Invoke-WebRequest `
    -Method Delete `
    -Uri    "https://api.businesscentral.dynamics.com/admin/v2.3/applications/businesscentral/environments/$newEnvironmentName" `
    -Headers @{Authorization=("Bearer $accessToken")}

The Create, Copy, and Delete operations are asynchronous. The response objects are returned before the underlying operation has completed. The final results of the operation are reflected in the ‘status’ field of the environment that the operations affect. In practice this means that polling of the ‘Get Environments’ endpoints must be done to determine if the given operation was successful.

Others:
Get support settings:

# Get support settings
$environmentName = "MyNewSandboxAsACopy"
$response = Invoke-WebRequest `
    -Method Get `
    -Uri    "https://api.businesscentral.dynamics.com/admin/v2.3/support/applications/businesscentral/environments/$environmentName/supportcontact" `
    -Headers @{Authorization=("Bearer $accessToken")}
Write-Host (ConvertTo-Json (ConvertFrom-Json $response.Content))

Get storage (database and file) used by an environment in KB:

# Get storage (database and file) used by an environment in KB
$environmentName = "Production"
$response = Invoke-WebRequest `
    -Method Get `
    -Uri    "https://api.businesscentral.dynamics.com/admin/v2.3/applications/businesscentral/environments/$environmentName/usedstorage" `
    -Headers @{Authorization=("Bearer $accessToken")}
Write-Host (ConvertTo-Json (ConvertFrom-Json $response.Content))

Get storage (database and file) across all environments:

# Get storage (database and file) across all environments
$response = Invoke-WebRequest `
    -Method Get `
    -Uri    "https://api.businesscentral.dynamics.com/admin/v2.3/environments/usedstorage" `
    -Headers @{Authorization=("Bearer $accessToken")}
Write-Host (ConvertTo-Json (ConvertFrom-Json $response.Content))

Get all tenant quotas:

# Get all tenant quotas
$response = Invoke-WebRequest `
    -Method Get `
    -Uri    "https://api.businesscentral.dynamics.com/admin/v2.3/environments/quotas" `
    -Headers @{Authorization=("Bearer $accessToken")}
Write-Host (ConvertTo-Json (ConvertFrom-Json $response.Content))

Find more about Business Central Administration Center API from MS docs.

END

Hope this will help.

Thanks for reading.

ZHU

コメント

Copied title and URL