Modernizing C/AL Code with .NET Interoperability Techniques

Leveraging .NET from C/AL in Dynamics NAV/Business Central### Introduction

Dynamics NAV and Business Central developers often need functionality not available natively in C/AL — file handling beyond simple text, advanced cryptography, complex date/time calculations, JSON processing, Excel manipulation, network communication, or platform-specific services. Fortunately, C/AL (and its successor AL) can interoperate with the .NET Framework (or .NET Core/.NET 5+ depending on the environment) to extend application capabilities. This article explains how to call .NET from C/AL, typical use cases, practical examples, compatibility considerations, performance and security implications, deployment strategies, and migration guidance toward AL and modern Business Central extensions.


Why use .NET from C/AL?

  • Access to rich libraries: The .NET ecosystem offers mature libraries for tasks C/AL lacks or handles poorly (e.g., JSON, HTTP clients, XML, cryptography, Excel automation, image processing).
  • Reusability: Leverage existing .NET assemblies developed in-house or third-party components.
  • Performance: For CPU- or I/O-intensive operations, well-optimized .NET code can be faster than equivalent C/AL workarounds.
  • Platform services: Interact with OS-level resources, network services, or native APIs through .NET wrappers.

Environments: NAV Classic, NAV RTC, and Business Central

  • In classic NAV ⁄2013 and up to NAV 2018, C/AL runs on the Windows platform and supports direct .NET interoperability using DotNet variables.
  • In Business Central on-premises (modern NAV/BC), .NET interop is supported in server-side code but depends on the runtime (.NET Framework vs .NET Core/.NET 5+). For SaaS Business Central, direct arbitrary .NET interop is restricted — extensions must use allowed APIs or rely on Azure/External web services.
  • AL (the newer language) continues support for some .NET interop patterns via platform-specific APIs or by creating .NET helper assemblies called from the server where permitted.

How .NET interop works in C/AL: basics

  1. Declare a DotNet variable in C/AL using the full assembly-qualified type name or selecting from the object browser.
    • Example types: System.Text.StringBuilder, System.Net.Http.HttpClient, Microsoft.Office.Interop.Excel.Application.
  2. Instantiate objects using CREATE and then call methods/properties directly.
  3. Manage disposal where applicable (use IDisposable via DotNet variable methods like Dispose when available).
  4. Handle exceptions — .NET exceptions are surfaced as C/AL runtime errors; use TRY…CATCH for graceful handling.

Example (pseudocode-like C/AL snippet):

DotNetText := DotNet.Text.StringBuilder; DotNetText := DotNetText.StringBuilder(); DotNetText.Append('Hello, .NET from C/AL'); Message(DotNetText.ToString()); 

Common use cases and code examples

1) JSON processing

C/AL’s native JSON support (later versions) improved, but .NET libraries (Newtonsoft.Json) remain popular. Example pattern:

  • Add DotNet variable for Newtonsoft.Json.Linq.JObject
  • Parse JSON string and extract fields with JObject.Parse()
2) HTTP and REST calls

Use System.Net.Http.HttpClient for richer HTTP functionality than C/AL’s HttpClient in older NAV versions. Example steps:

  • Create HttpClient, set headers, call GetAsync/PostAsync, read response.
3) File and ZIP manipulation

System.IO.Compression.ZipArchive simplifies compressing/decompressing files compared to manual approaches.

4) Excel automation
  • For on-premise Windows servers, Microsoft.Office.Interop.Excel can automate Excel for advanced tasks — note: server-side Office automation is not recommended by Microsoft for scalability and stability.
  • Prefer libraries like EPPlus or closed-source assemblies that support server use.
5) Cryptography and hashing

Use System.Security.Cryptography for secure hashing (SHA256), encryption, and signing.

6) Email (SMTP) and attachments

System.Net.Mail.SmtpClient (or MailKit in modern .NET) can send complex emails with attachments, HTML bodies, and authentication.


Example: Using System.Net.Http.HttpClient (C/AL style)

Pseudocode:

HttpClient := DotNet.System.Net.Http.HttpClient; Response := HttpClient.GetStringAsync('https://api.example.com/data').Result; Message(Response); 

Notes:

  • Async methods may need .Result or .GetAwaiter().GetResult() to block synchronously in C/AL.
  • Be careful with blocking calls on the NAV server thread pool.

Exception handling and debugging

  • Wrap .NET calls in C/AL TRY…CATCH blocks.
  • Inspect exception.Message and exception.StackTrace when debugging.
  • Use telemetry/logging on the server to capture .NET errors for postmortem analysis.

Performance considerations

  • Creating many short-lived .NET objects can be expensive; reuse instances where safe (e.g., a shared HttpClient).
  • Beware of blocking async operations; prefer truly synchronous methods or handle async properly where supported.
  • Keep heavy processing off peak transactional paths — consider background tasks or external services for CPU-heavy work.

Security and permissions

  • In on-premise deployments, .NET code runs under the NAV/BC service account — ensure it has minimal required permissions on file system, network, and other resources.
  • Avoid storing secrets in code; use secure storage (Windows DPAPI, Azure Key Vault) and inject credentials at runtime.
  • For SaaS Business Central, direct .NET interop is heavily restricted; use sanctioned APIs, Azure functions, or web services as alternatives.

Deployment strategies

  • For third-party or custom .NET assemblies: deploy DLLs to NAV Server Add-ins folder and add assembly references in C/AL where needed.
  • Ensure versioning compatibility: bind to specific assembly versions and test behavior across NAV/BC cumulative updates and .NET runtime changes.
  • For SaaS scenarios: shift .NET-dependent logic to Azure Functions or REST microservices, called from AL or C/AL via HttpClient.

Migration notes: moving from C/AL + .NET to AL and Extensions

  • AL extensions for Business Central (especially cloud) restrict direct .NET usage. Plan to:
    • Replace .NET calls with platform APIs where available (Base Application or standard libraries).
    • Move complex .NET logic into external services (Azure Functions, Web APIs) and call them securely.
    • For on-premise extensions, consider using .NET add-ins but be mindful of maintainability and future cloud compatibility.

Best practices checklist

  • Reuse long-lived objects when appropriate (e.g., single HttpClient).
  • Handle exceptions and log detailed errors.
  • Avoid server-side Office automation; prefer libraries designed for server use.
  • Keep security principle of least privilege for service accounts and file access.
  • For cloud/SaaS, prefer external services instead of direct .NET interop.
  • Document assembly dependencies and deployment steps clearly.

Conclusion

Using .NET from C/AL unlocks powerful capabilities for Dynamics NAV/Business Central developers, enabling access to modern libraries and OS-level services. For on-premise solutions, direct interop remains a practical tool. For Business Central SaaS and future-proofing, design .NET-dependent logic as external services and rely on AL/platform APIs where possible. Proper handling of performance, security, and deployment ensures robust integration between C/AL and the .NET ecosystem.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *