Download Business Central Source Code Country Wise with PowerShell

 # Install BcContainerHelper (could be you need to run this as Administrator):

# Install-Module BcContainerHelper -force

# Configuration

$Countries = @('w1', 'in')  # List of countries

$Versions = @('26', '27')   # List of major versions (e.g., '24.0', '25.1', or just '25')

$Destination = 'C:\_Source\Microsoft\Artifacts'

$bcartifactsCacheFolder = 'c:\bcartifacts.cache\'

$openInCode = $false


foreach ($Country in $Countries) {

    foreach ($Version in $Versions) {

        Write-Host "--- Fetching: Country [$($Country.ToUpper())] | Version [$($Version)] ---" -ForegroundColor Cyan

        

        try {

            # 1. Get Artifact URL for specific version and country

            $ArtifactUrl = Get-BCArtifactUrl -version $Version -country $Country -select Latest

            

            # 2. Download Artifact

            $ArtifactPath = Download-Artifacts -artifactUrl $ArtifactUrl -includePlatform

            

            foreach ($path in $ArtifactPath) {

                Write-Host "Handling Path: $($path)" -ForegroundColor Green

                

                $AllSources = Get-ChildItem -Path $path -Recurse -Filter "*.source.zip"

                

                # Logic to maintain clean folder hierarchy: Destination\Country\Version

                $CountryFolder = join-path $Destination $Country

                $VersionSubFolder = join-path $CountryFolder $path.Substring($bcartifactsCacheFolder.Length)


                foreach ($source in $AllSources) {

                    $AppName = $source.Name.Replace('.Source.zip', '')

                    $DestinationFolder = join-path $VersionSubFolder $AppName


                    if (-not (Test-path $DestinationFolder)) {

                        Write-Host "Extracting $($source.name)..." -ForegroundColor Gray

                        Expand-Archive -Path $source.FullName -DestinationPath $DestinationFolder -Force

                    }

                }

                

                if ($openInCode) { code $VersionSubFolder }

            }

        }

        catch {

            Write-Warning "Could not find or download artifact for Country: $Country, Version: $Version"

        }

    }

}


Write-Host "All tasks completed!" -ForegroundColor Yellow

start $Destination

Continue Reading...

Understanding OAuth and App Registration for Secure API Access in Business Central

 

Introduction: The Importance of OAuth in Modern API Security

  • [02:37 ~ 04:07]
    In the evolving landscape of cloud services and APIs, OAuth has become a critical authorization framework enabling secure, delegated access to resources. This session, presented by Aaron John Kaufman, a seasoned technical consultant in the Dynamics NAV/Business Central ecosystem, focuses on the transition to OAuth in Microsoft environments and its significance. The urgency stems from Microsoft’s impending deadline to move to OAuth by October 1st, emphasizing the need to understand and implement OAuth properly to maintain secure access to Business Central APIs and related services.

  • Key Vocabulary and Concepts:

    • OAuth (Open Authorization): A standard protocol allowing third-party applications limited access to HTTP services without exposing user credentials.
    • Access Token: A security token issued by an authorization server granting access rights to a client application.
    • App Registration: The process of registering an application in Azure Active Directory to enable OAuth interactions.
    • Resource Server: The server hosting protected data or APIs (e.g., Business Central).
    • Client Application: External app requesting access to resources on behalf of a user.
    • Azure Active Directory (Azure AD): Microsoft’s cloud-based identity and access management service acting as the authorization server.

Section 1: The OAuth Ecosystem and Its Roles

  • [06:04 ~ 10:37]
    OAuth orchestrates interactions among four key roles:
  1. Resource Server: Holds data (Business Central exposing APIs).
  2. Client Application: External app requesting resource access.
  3. Resource Owner: End-user who owns the data and grants access.
  4. Authorization Server: Azure Active Directory, managing app registrations, permissions, and token issuance.
  • Process Overview:

    • The client app must be registered in Azure AD and request user consent.
    • The user authenticates and grants permissions.
    • Azure AD issues an access token to the client app.
    • The client app uses the token to call Business Central APIs, which validate and authorize the request.
  • Important Distinctions:

    • App Registration defines the application’s identity, redirect URIs, secrets, and required API permissions.
    • Service Principal (Enterprise Application): An instance of an app registration representing the app in a specific Azure AD tenant, storing granted permissions.
  • Single Tenant vs. Multi-Tenant:

    • Single Tenant: App and service principal live within one Azure AD tenant.
    • Multi-Tenant: App registration remains in the home tenant, but service principals are created in other tenants upon consent, allowing cross-tenant access.

Section 2: App Registration and Permissions

  • [10:37 ~ 19:40]
    App registration in Azure AD involves specifying:

  • Application metadata (name, logo, publisher).

  • Redirect URIs to handle OAuth callbacks.

  • Secrets (passwords) or certificates used for authentication.

  • API permissions: required permissions (declared by app registration) vs. granted permissions (stored at service principal level after consent).

  • Permissions Types:

    • Scopes (Delegated Permissions): Allow an app to act on behalf of a user.
    • Application Roles: Allow app-only access without a user context (service-to-service).
  • The Business Central app registration exposes APIs with scopes like user_impersonation and application roles like api.readwrite.all.

  • Permissions must be explicitly granted, either by user consent or admin consent, depending on the permission type and organizational policies.


Section 3: The Consent Flow and Security Considerations

  • [31:06 ~ 36:08]

  • Consent Flow: When an application requests access to user data, users or admins must grant consent.

    • User consent: Grants permission for individual user resources.
    • Admin consent: Grants permission for the entire organization, removing consent prompts for all users.
  • Applications can request consent dynamically or pre-register required permissions statically in Azure AD.

  • Security nuances:

    • Secrets (passwords) in app registrations act as credentials but have limited lifetime (max 24 months, often recommended shorter).
    • Certificates are recommended over secrets for enhanced security as they do not travel over the network.
    • Tokens (access and refresh) must be carefully managed to avoid leaks.
    • Tokens are JSON Web Tokens (JWTs), base64 encoded, and signed to ensure integrity and authenticity.

Section 4: The OAuth Authorization Flows Explained

  • [43:08 ~ 48:45]
    Two primary OAuth flows relevant to Business Central:
  1. Authorization Code Grant Flow:

    • Used for delegated access where a user logs in interactively.
    • User authenticates via a browser, grants permissions, and an authorization code is returned via a redirect URI.
    • The app exchanges this code for an access token to call APIs on behalf of the user.
    • Requires a redirect URI and often a client secret if the app is confidential (web apps).
    • Suitable for web apps and apps with user interaction.
  2. Client Credentials Flow:

    • Used for app-only access without user interaction (service-to-service).
    • The app authenticates directly with its client ID and secret or certificate.
    • Receives an access token representing the app itself, not a user.
    • Requires pre-consent by an admin to grant application permissions.
    • Commonly used for background jobs, Azure Functions, or external portals integrating with Business Central.

Section 5: Deep Dive into Authorization Code Grant Flow

  • [48:53 ~ 59:56]

  • The detailed flow involves two key Azure endpoints:

    • /authorize endpoint for user login and consent (browser-based).
    • /token endpoint for exchanging the authorization code for an access token (API call).
  • The redirect URI is crucial as it is the location where Azure AD sends the authorization code after login. This URI must be controlled by the client application to securely receive the code.

  • The authorization code is short-lived (valid for 10 minutes).

  • The token request includes the client ID, secret, authorization code, redirect URI, and scope.

  • The access token received contains all necessary claims including user identity, tenant ID, scope, and expiration.

  • Tokens are JWTs that can be decoded to inspect claims but are cryptographically signed to prevent tampering.


Section 6: Configuring App Registration in Azure Portal – Demo Insights

  • [01:03:18 ~ 01:19:48]
  • Demo walkthrough of creating an app registration named “bc tag days 22 demo” with:
    • Single tenant option chosen due to simplicity and lack of verified publisher status.
    • Redirect URI configured for a web app (localhost for demo purposes).
    • Creation of client secret for confidential client authentication.
  • Explanation of confidential vs. public clients:
    • Web apps (confidential clients) can keep secrets securely on the server.
    • Desktop/mobile apps (public clients) cannot keep secrets and rely on other safeguards.
  • Demonstrated user login flow, consent prompt, capturing authorization code from redirect URI, exchanging it for access token, and using the token to call Business Central API successfully.
  • Emphasized importance of precise redirect URI matching in the token exchange step.

Section 7: Client Credentials Flow and Application Users

  • [01:20:32 ~ 01:27:52]
  • Demonstrated adding application permissions (e.g., api.readwrite.all) to app registration and granting admin consent.
  • Obtained access token using client credentials flow with client ID and secret.
  • Highlighted the need to create an application user in Business Central linked to the app registration for the token to be accepted by Business Central.
  • Explained that this user is not a regular user but a service principal representing the app.
  • Recommended best practices:
    • Use certificates over secrets for production environments due to security advantages.
    • Avoid storing secrets in code or insecure places.
  • Mentioned ongoing work to automate app registration and permission management using AL code and Graph API.

Section 8: Managing Tokens and Permission Types

  • [01:35:50 ~ 01:39:08]
  • Access tokens typically expire after about 60 minutes; refresh tokens valid up to 90 days allow seamless token renewal without user interaction.
  • However, tenant policies (e.g., forced interactive login every two weeks) can invalidate refresh tokens, complicating unattended background processes.
  • Tokens should be stored only in memory or securely, avoiding persistent storage in setup tables to minimize security risk.
  • Dynamic permissions (requested at runtime) differ from static permissions (pre-registered in app registration), providing flexibility and least privilege access.

Section 9: Q&A and Best Practices

  • [01:29:23 ~ 01:37:05]
  • Recommended multiple app registrations for multi-customer or multi-tenant scenarios to isolate access and reduce risk in case of secret leaks.
  • Dynamic permissions allow requesting only the necessary scopes at runtime, giving granular control and user choice.
  • Reusing app registrations is acceptable when multiple applications require similar permissions and are under the same control.
  • Certificate-based authentication is the preferred secure method for confidential clients over client secrets.
  • Microsoft’s MSAL (Microsoft Authentication Library) simplifies OAuth handling in code, abstracting much of the complexity.

Conclusion: Key Takeaways and Implications

  • OAuth is essential for secure, delegated API access in Microsoft Business Central and other cloud services, driven by compliance and security needs.
  • Understanding the OAuth roles, app registration, permission models, and authorization flows is critical to correctly implementing OAuth integrations.
  • Proper management of app registrationsservice principalspermissions, and tokens ensures secure access control and user experience.
  • The authorization code grant flow is best for user-interactive scenarios, while the client credentials flow suits backend, service-to-service access.
  • Security best practices emphasize certificates over secrets, least privilege through scoped permissions, and careful token lifecycle management.
  • Tools and libraries, such as MSAL, and automation via AL code and Graph API, can simplify complex OAuth integrations.
  • Organizations should plan for token renewal, consent management, and multi-tenant scenarios to ensure robust and scalable OAuth implementations.

Advanced Bullet-Point Summary

  • OAuth Overview & Importance

    • OAuth enables secure, delegated access to APIs without sharing user credentials.
    • Microsoft mandates OAuth for Business Central by October 1st, driven by security concerns.
    • Tokens must be handled securely; even Microsoft’s own token storage has vulnerabilities.
  • OAuth Roles and Architecture

    • Four roles: Resource Server (Business Central), Client Application, Resource Owner (User), Authorization Server (Azure AD).
    • App registrations define app identity and permissions; service principals instantiate apps per tenant with granted permissions.
    • Single vs. Multi-tenant apps determine app reach across directories.
  • App Registration Details

    • Contains metadata, redirect URIs, secrets/certificates, declared permissions.
    • Permissions: Required (declared) vs. Granted (after consent).
    • Supports exposing APIs with scopes and roles for fine-grained access control.
  • Consent Management

    • User consent grants access for individual accounts; admin consent can cover entire organizations.
    • Admin consent necessary for application roles (app-only access).
    • Consent flow complexity and security considerations underscore importance of understanding OAuth.
  • OAuth Flows

    • Authorization Code Grant: User-interactive, obtains delegated access tokens, involves browser redirect and secret exchange.
    • Client Credentials: Non-interactive, app-only access, requires admin consent, suited for background services.
  • Tokens and Security

    • Access tokens are JWTs containing user, tenant, and permission claims, signed for integrity.
    • Tokens expire ~60 minutes; refresh tokens extend access but depend on tenant policies.
    • Secrets act as passwords; certificates recommended for higher security.
  • Demo Learnings

    • App registration setup includes choosing tenant type, redirect URIs, secret creation.
    • Confidential clients require secrets; public clients do not.
    • Demonstrated token retrieval, decoding, and API call with bearer token.
  • Best Practices & Real-World Scenarios

    • Prefer multiple app registrations for multi-customer environments to limit blast radius of leaks.
    • Use dynamic scopes for minimal necessary permissions.
    • Automate app registration and secret management when possible.
    • Leverage MSAL and libraries to abstract OAuth complexity.
  • Challenges and Considerations

    • Managing token expiration and refresh in background jobs.
    • Handling multi-tenant app permissions and service principal creation.
    • Balancing ease of use with strong security controls.
Continue Reading...

Troubleshooting and Debugging Microsoft Dynamics 365 Business Central in a SaaS Environment

 

Introduction: The Importance of Troubleshooting in Business Central SaaS Environments

  • [00:28 ~ 02:25] This chapter focuses on troubleshooting Microsoft Dynamics 365 Business Central in a Software as a Service (SaaS) environment, emphasizing tools and techniques to diagnose and resolve issues efficiently.
  • The session is led by experts Kalman Perez and Nikolai Dobrev, marking their first joint presentation on this critical topic.
  • Key vocabulary and concepts introduced include telemetryin-client toolssnapshot debuggingprofiling, and database performance analysis. These form the foundation of troubleshooting in cloud-hosted Business Central environments and are essential for administrators and developers aiming to maintain robust system performance and reliability.
  • The significance lies in the growing use of Business Central SaaS by enterprises globally, where seamless troubleshooting directly impacts user experience, system uptime, and developer productivity.

Section 1: Telemetry and Its Role in Troubleshooting

  • [02:52 ~ 04:41] Telemetry is presented as the cornerstone for understanding system behavior in SaaS environments. It captures event data and operational metrics across Business Central tenants.
  • Although a detailed session is scheduled separately, telemetry allows users to gather information about system events and performance metrics remotely.
  • Power BI app has been introduced in the latest release to visualize telemetry data, making it easier to interpret complex information through dashboards.
  • Telemetry is essential for proactive troubleshooting, enabling administrators to identify issues before they impact end users.

Section 2: In-Client Troubleshooting Tools – Connectivity and Diagnostics

  • [04:05 ~ 07:07] Beyond telemetry, Business Central’s in-client tools offer powerful diagnostics directly accessible via the web client interface.
  • connectivity check tool verifies the communication status between the user’s browser and the Business Central tenant, diagnosing issues like login failures or CDN outages.
  • The connectivity check is accessible by appending /connectivity to the tenant URL or environment-specific URLs, providing immediate diagnostic feedback.
  • The Help and Support page within the client consolidates troubleshooting resources such as:
    • Last known errors
    • Known issues database
    • Page inspection tools
    • Performance analysis via the in-client profiler
    • Report problem feature to collect metadata and session IDs
  • A crucial tip is to always note the server session ID, as it aids in correlating client-side issues with backend logs.

Section 3: Page Inspector and Extension Impact Analysis

  • [06:33 ~ 08:49] The Page Inspector tool reveals detailed metadata about pages, including:
    • Table fields and their originating extensions
    • Active page filters
    • Performance contributions (timing) of each extension on page load
  • Extensions can be analyzed for their behavior; for example, a custom extension may introduce actions that cause errors or hangs.
  • An illustrative scenario shows an extension with two actions: one benign (“prepare press”) and one problematic (“do harm”), demonstrating how to detect the root cause of page malfunctions.
  • This diagnostic approach helps isolate custom code causing performance degradation or functional errors.

Section 4: Database Analysis – Logs, Locks, and Missing Indexes

  • [08:14 ~ 11:30] Database interactions are critical in Business Central, and troubleshooting often involves analyzing:
    • Database logs to detect locks or blocked operations
    • Table information pages that provide statistics such as record counts, table sizes, and index sizes
    • Wait statistics pages which show how long the system waits for various database operations
  • A key feature is the missing indexes analyzer, which reviews query patterns and suggests indexes to improve query performance.
  • Example: In a test environment, no missing indexes were reported, but production environments often benefit significantly from these recommendations.
  • Database locks are especially important to monitor, as they can cause hangs or failures when multiple sessions attempt conflicting operations.

Section 5: Event Recording and Permissions Debugging

  • [10:51 ~ 13:41] When event subscribers fail to trigger, the Event Recorder tool aids debugging by capturing a chronological list of fired events during a user scenario.
  • The event recorder helps verify whether the expected event has fired, assisting developers in pinpointing why their code doesn’t execute as intended.
  • The Effective Permissions page enables granular inspection of user permissions on objects and permission sets, crucial when users encounter access or execution errors.
  • Troubleshooting scheduled tasks is possible through the Scheduled Tasks overview, showing background jobs’ recurrence, timeouts, and related object IDs.

Section 6: Reporting and Exporting Data for Analysis

  • [13:00 ~ 15:11] Business Central allows exporting report data without publishing reports via the request page and an “export to Excel” feature.
  • This capability enables troubleshooting of report data and layouts without affecting live reports, facilitating data validation and error isolation.

Section 7: Debugging Enhancements in Visual Studio Code

  • [14:28 ~ 18:23] Debugging in Business Central has been enhanced with:
    • Visibility into database locks during debugging frames, helping developers understand concurrency issues.
    • New settings to exclude temporary records or try functions from breakpoints, reducing noise during debugging sessions.
    • The ability to specify a startup company during debugging launch, streamlining multi-company development scenarios.
  • These improvements enhance developer productivity by providing more granular control and richer diagnostic data.

Section 8: Snapshot Debugging – A Non-Intrusive Debugging Alternative

  • [17:45 ~ 27:09] Snapshot debugging is introduced as a production-safe debugging tool, akin to a video recorder for the call stack rather than intrusive breakpoints.
  • It records stack frames and variables at predefined Snap Points, capturing the execution context without halting production workloads.
  • Workflow includes setting snap points in Visual Studio Code, starting the snapshot session, performing the scenario, stopping the session, and downloading a snapshot file for offline debugging.
  • Key configuration options include:
    • Specifying a session ID or user ID to attach to particular sessions
    • Adjusting snapshot verbosity to balance detail and file size
    • Defining profiling types to collect performance data alongside debugging info
  • Snap points differ from traditional breakpoints as they must be planned ahead, being the sole points where data is collected.
  • Limitations include a maximum session time of 10 minutes and user notifications when snapshot debugging occurs, ensuring security and transparency.
  • The snapshot file contains GDPR-compliant data, necessitating careful handling.
  • A live demo illustrated capturing an API error scenario, retrieving the snapshot, and using Visual Studio Code to navigate through snap points and evaluate variables, highlighting the power of this tool for production troubleshooting.
  • Snapshot debugging supports error-triggered stopping points even without explicit snap points, ensuring error contexts are captured.

Section 9: Profiling Techniques – Instrumentation and Sampling

  • [32:53 ~ 42:59] Profiling is essential for performance tuning; two major profiling techniques are discussed:
    • Instrumentation-based profiling: Introduced a year ago, it records complete stack frames and execution times of procedures, including full time (total execution including callees) and self time (execution exclusive of callees). It is detailed but resource-intensive and produces large files.
    • Sampling-based profiling: Introduced more recently, it periodically samples stack frames at intervals (default 100ms), providing a less intrusive overview with lower overhead but less complete data. It may miss some calls but is effective for general performance insights.
  • Profiling data is visualized in Visual Studio Code using a CPU profile editor based on Google’s Chromium output format, offering:
    • Top-down views showing call stacks and timings
    • Bottom-up views showing callees and callers for each function
    • Support for sorting and filtering using a simple query language to pinpoint performance bottlenecks
  • Profiles can also be viewed in third-party tools like Firefox Profiler or Chrome/Edge DevTools, though some Business Central-specific metadata might not be fully represented.
  • The in-client profiler remains the easiest tool for end users, providing quick insights. Developers seeking granular data should use Visual Studio Code with snapshot and sampling profiles.
  • Profiling helps identify slow operations and optimize Business Central applications by focusing effort on the most time-consuming code paths.

Conclusion: Key Takeaways and Implications for Business Central Troubleshooting

  • The session provides a comprehensive toolkit for troubleshooting Business Central SaaS environments, combining telemetry, in-client diagnostics, advanced debugging, and profiling.
  • Understanding telemetry and leveraging the Power BI app enables proactive monitoring and issue detection.
  • The in-client tools offer immediate, user-friendly diagnostics for connectivity, permissions, database health, and page performance.
  • Snapshot debugging emerges as a game-changing approach for production troubleshooting, balancing data richness with minimal impact on live systems.
  • Profiling techniques, both instrumentation and sampling, empower developers to optimize performance by revealing detailed execution patterns.
  • These tools collectively reduce downtime, improve developer efficiency, and enhance user experience in cloud-hosted Business Central deployments.
  • The ongoing evolution of these diagnostics reflects Microsoft’s commitment to supporting complex enterprise environments where rapid, precise troubleshooting is paramount.

Advanced Bullet-Point Notes Summary

  • Telemetry captures operational events and performance metrics; new Power BI app visualizes this data for better insights.
  • Connectivity check tool diagnoses network and login issues between browsers and Business Central tenants.
  • Help & Support page consolidates troubleshooting resources: error info, page inspection, profiling, metadata collection, session IDs.
  • Page Inspector reveals extension sources, applied filters, and extension performance contributions on pages.
  • Custom extensions can be analyzed for errors causing hangs or failures.
  • Database tools include logs for locks, table statistics, wait times, and missing index suggestions to improve query speed.
  • Event Recorder helps verify if subscribed events have fired during scenarios.
  • Effective Permissions page diagnoses user permission issues on objects and permission sets.
  • Scheduled Tasks overview shows background job details, including recurrence and timeouts.
  • Reports can be exported to Excel from request pages without publishing, aiding data troubleshooting.
  • Debugging enhancements include visibility of database locks during debug, options to exclude temporary records and try functions, and startup company selection.
  • Snapshot debugging records stack frames and variables non-intrusively on production; requires planning snap points; limited to 10-minute sessions; GDPR data caution.
  • Snapshot debugging workflow: set snap points → start session → perform scenario → stop session → download snapshot → debug offline.
  • Profiling via instrumentation (detailed, resource-heavy) and sampling (lighter, less complete) reveals execution times and bottlenecks.
  • Visual Studio Code CPU profile editor supports top-down and bottom-up views with filtering and source navigation.
  • Profiles can also be opened in Firefox Profiler or browser dev tools with some limitations.
  • In-client profiler is accessible to end users; Visual Studio Code profiling suits developers needing depth.
  • Overall, combined tools improve troubleshooting accuracy, reduce downtime, and enhance performance tuning for Business Central SaaS environments.
Continue Reading...