Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

FlintsLabs.D365.ODataClient

A fluent, strongly typed OData client for Microsoft Dynamics 365 Finance and Operations and Microsoft Dataverse.

.NET 8.0 .NET 10.0 NuGet License: MIT

Version 2 is a breaking, fail-closed release. High-level reads and mutations no longer convert HTTP, authentication, transport, timeout, protocol, or serialization failures into null, empty collections, zero, or empty strings. Applications can now distinguish a successful empty query from an unavailable or rejected request.

Highlights

  • Fluent D365Query<T> API with LINQ-to-OData translation.
  • Azure AD / Microsoft Entra ID client credentials, Azure Managed Identity, and ADFS client credentials.
  • Named clients for multiple F&O and Dataverse endpoints.
  • Typed exceptions with HTTP status, D365 error details, request ID, retry guidance, and mutation outcome.
  • Explicit raw HTTP responses through ID365Client.SendAsync.
  • Bounded, opt-in retries for reads only and one token refresh after an actual HTTP 401.
  • Validated OData pagination with no partial-list returns.
  • [OdataKey] support for key-based update and delete expressions.
  • Safe OData literal formatting and URI encoding, including LINQ coalesce (??).
  • Shared token cache and single-flight refresh for parallel calls through one service provider.

Compatibility

Package Target frameworks D365 endpoints
2.2.1 .NET 8 and .NET 10 Security update: validated HTTPS, same-origin API requests, no automatic redirects; existing authentication selectors retained
2.2.0 .NET 8 and .NET 10 F&O OData and Dataverse Web API with fluent or configuration-driven Azure AD/Managed Identity; existing ADFS client-credential deployments
2.1.0 .NET 8 and .NET 10 F&O OData and Dataverse Web API with Azure AD client credentials or Managed Identity; existing ADFS client-credential deployments
2.0.0 .NET 8 and .NET 10 F&O OData, Dataverse Web API, and existing ADFS client-credential deployments

Installation

dotnet add package FlintsLabs.D365.ODataClient --version 2.2.1

Security Notice

Published version 2.2.0 accepts any server certificate on its registered D365 API and ADFS authentication HTTP clients. An active attacker on the network path could intercept tokens, client credentials, or application data. HTTPS alone does not verify peer identity with that version.

Version 2.2.1 removes this bypass and restores platform certificate-chain, hostname, and validity checks. Applications must upgrade their installed package; publishing this fix does not update existing deployments. Private-CA/on-premises deployments must configure trust on the application host and present a valid certificate for the requested hostname; do not bypass validation. Azure AD and Managed Identity token acquisition use MSAL's separate HTTP transport.

The 2.2.1 security changes also:

  • Require an absolute HTTPS API endpoint and, when using ADFS, an absolute HTTPS TokenEndpoint. Invalid configuration fails before requests are sent. API base URLs must not contain query strings; endpoints must not contain user information or fragments.
  • Restrict every API request, including raw SendAsync, to the configured HTTPS origin (host and port). Relative, root-relative, and same-origin absolute URLs remain supported; a different endpoint requires a separately registered named D365 client. Unsafe request URLs and AddHeader("Host", ...) overrides throw D365ProtocolException before token acquisition or HTTP send (NotSent for mutations).
  • Disable automatic redirects on both named HTTP clients, including 307/308 redirects that could otherwise forward POST bodies. Raw calls return the original 3xx response; high-level calls throw D365HttpException; ADFS token acquisition fails. Configure the final HTTPS URL rather than relying on redirects.
  • Remove the unused Microsoft.AspNetCore.WebUtilities dependency affected by GHSA-x33c-w48q-qrgc.

These rules apply to both Debug and Release and do not change the Fluent authentication selectors or add a Client Secret fallback. With OrganizationUrl set, Resource remains the OAuth audience (which can be an ADFS URN); the HTTPS rule applies to the effective network endpoint.

See Security and logging before production deployment. Never commit client secrets or log D365Response.RawBody / D365Exception.ResponseBody without application-level redaction.

Quick Start

Define a model. Use Guid for an Edm.Guid key; a C# string key is emitted as an OData string literal and is therefore quoted.

using System.Text.Json.Serialization;
using FlintsLabs.D365.ODataClient.Attributes;

public sealed class EgrHead
{
    [OdataKey]
    [JsonPropertyName("rvl_egrheadid")]
    public Guid Id { get; set; }

    [JsonPropertyName("rvl_wmsstatus")]
    public bool? WmsStatus { get; set; }
}

Register a Dataverse client:

using FlintsLabs.D365.ODataClient.Enums;
using FlintsLabs.D365.ODataClient.Extensions;

builder.Services.AddD365ODataClient(d365 => d365
    .UseAzureAD()
    .WithOrganizationUrl(
        "https://contoso.api.crm5.dynamics.com/api/data/v9.2")
    .WithResource("https://contoso.api.crm5.dynamics.com")
    .WithTenantId(builder.Configuration["D365:TenantId"]!)
    .WithClientId(builder.Configuration["D365:ClientId"]!)
    .WithClientSecret(builder.Configuration["D365:ClientSecret"]!)
    .WithScope("https://contoso.api.crm5.dynamics.com/.default")
    .WithBooleanFormatting(D365BooleanFormatting.Literal));

Inject the root client and issue a read:

using FlintsLabs.D365.ODataClient.Services;

public sealed class EgrRepository(ID365Client dataverse)
{
    public Task<EgrHead?> FindAsync(
        Guid id,
        CancellationToken cancellationToken)
    {
        return dataverse
            .Entity<EgrHead>("rvl_egrheads")
            .Where(head => head.Id == id)
            .FirstOrDefaultAsync(cancellationToken);
    }
}

null now means the server returned a successful, valid collection response with no matching row. HTTP 404, 401, 500, network errors, invalid JSON, and malformed OData envelopes throw instead.

Configuration

Azure AD for F&O

When OrganizationUrl is omitted, Resource + "/data/" is used as the OData base URL.

builder.Services.AddD365ODataClient(d365 => d365
    .UseAzureAD()
    .WithResource("https://contoso.operations.dynamics.com")
    .WithTenantId(configuration["D365:TenantId"]!)
    .WithClientId(configuration["D365:ClientId"]!)
    .WithClientSecret(configuration["D365:ClientSecret"]!));

If WithScope(...) is not supplied, Azure AD uses Resource + "/.default".

Azure Managed Identity for F&O

Use the System-assigned identity attached to the Azure workload:

builder.Services.AddD365ODataClient(d365 => d365
    .UseSystemAssignedManagedIdentity()
    .WithResource("https://contoso.operations.dynamics.com"));

Or select an attached User-assigned identity by its application (client) ID:

builder.Services.AddD365ODataClient(d365 => d365
    .UseUserAssignedManagedIdentity(managedIdentityClientId)
    .WithResource("https://contoso.operations.dynamics.com"));

Managed Identity can also be selected through FromConfiguration() in version 2.2.0. There is no fallback from Managed Identity to a client secret. If WithScope(...) is omitted, the token resource is Resource + "/.default".

The identity must be attached to the hosting Azure workload, and its application (client) ID must be registered and mapped to the intended D365 F&O user. For a User-assigned identity, pass the client ID, not its object/principal ID or Azure resource ID.

ADFS

The existing ADFS form-post flow is retained. Confirm the exact token endpoint and client-credential support with the owner of the on-premises deployment.

builder.Services.AddD365ODataClient(d365 => d365
    .UseADFS()
    .WithTokenEndpoint("https://fs.contoso.local/adfs/oauth2/token")
    .WithClientId(configuration["D365:ClientId"]!)
    .WithClientSecret(configuration["D365:ClientSecret"]!)
    .WithResource("https://ax.contoso.local")
    .WithOrganizationUrl(
        "https://ax.contoso.local/namespaces/AXSF/")
    .WithGrantType("client_credentials"));

appsettings.json

{
  "D365": {
    "AuthType": "AzureAD",
    "TenantId": "00000000-0000-0000-0000-000000000000",
    "ClientId": "00000000-0000-0000-0000-000000000000",
    "ClientSecret": "load-this-from-a-secret-provider",
    "Resource": "https://contoso.api.crm5.dynamics.com",
    "OrganizationUrl": "https://contoso.api.crm5.dynamics.com/api/data/v9.2",
    "Scope": "https://contoso.api.crm5.dynamics.com/.default",
    "BooleanFormatting": "Literal",
    "Retry": {
      "MaxReadRetries": 2,
      "BaseDelay": "00:00:00.250",
      "MaxDelay": "00:00:10",
      "UseJitter": true
    }
  }
}
builder.Services.AddD365ODataClient(
    builder.Configuration,
    "D365");

User-assigned Managed Identity configuration does not require a client secret:

{
  "D365Dataverse": {
    "AuthType": "ManagedIdentity",
    "ManagedIdentityClientId": "00000000-0000-0000-0000-000000000000",
    "Resource": "https://contoso.api.crm5.dynamics.com",
    "OrganizationUrl": "https://contoso.api.crm5.dynamics.com/api/data/v9.2",
    "Scope": "https://contoso.api.crm5.dynamics.com/.default",
    "BooleanFormatting": "Literal"
  }
}
builder.Services.AddD365ODataClient(
    "D365Dataverse",
    builder.Configuration,
    "D365Dataverse");

Omit ManagedIdentityClientId to use System-assigned Managed Identity. AuthType accepts only the names AzureAD, ADFS, and ManagedIdentity (case-insensitive); invalid, empty, or numeric values fail during registration. If AuthType is absent, the legacy Azure AD/ADFS detection remains in effect.

Named clients

builder.Services.AddD365ODataClient(
    "Finance",
    configuration,
    "D365:Finance");
builder.Services.AddD365ODataClient(
    "Sales",
    configuration,
    "D365:Sales");

var factory = serviceProvider.GetRequiredService<ID365ClientFactory>();
var finance = factory.GetClient("Finance");
var sales = factory.GetClient("Sales");

ID365ClientFactory and each named root client are singleton-scoped within their service provider. Create a fresh .Entity<T>(...) query for each parallel operation; a mutable D365Query<T> instance is not thread-safe.

Reads

var rows = await client
    .Entity<EgrHead>("rvl_egrheads")
    .Where(head => head.WmsStatus == false)
    .Select(head => new { head.Id, head.WmsStatus })
    .OrderBy(head => head.Id)
    .PageSize(250)
    .ToListAsync(cancellationToken);

var count = await client
    .Entity<EgrHead>("rvl_egrheads")
    .Where(head => head.WmsStatus == false)
    .LongCountAsync(cancellationToken);

LongCountAsync requires a valid non-negative 64-bit @odata.count. CountAsync performs a checked conversion to int and throws on overflow. Pagination validates every next link and throws without returning a partial list if any page fails.

Update and Delete

With [OdataKey], a key-only equality expression becomes the OData entity key:

var updated = await client
    .Entity<EgrHead>("rvl_egrheads")
    .Where(head => head.Id == headId)
    .UpdateAsync(
        new { rvl_wmsstatus = false },
        cancellationToken);

var deleted = await client
    .Entity<EgrHead>("rvl_egrheads")
    .Where(head => head.Id == headId)
    .DeleteAsync(cancellationToken);

Composite keys are supported by annotating every key property and supplying every key as equality joined with &&. The compatibility fallback remains available:

await client
    .Entity<EgrHead>("rvl_egrheads")
    .AddIdentity("rvl_egrheadid", headId)
    .UpdateAsync(
        new { rvl_wmsstatus = false },
        cancellationToken);

High-level mutations throw for every non-2xx status, including DELETE 404. Successful no-content responses are valid for untyped mutations.

Create and Responses

var response = await client
    .Entity<EgrHead>("rvl_egrheads")
    .AddHeader("Prefer", "return=representation")
    .AddAsync<EgrHead>(
        new { rvl_wmsstatus = false },
        cancellationToken);

Console.WriteLine(response.StatusCode);
Console.WriteLine(response.RequestId);
Console.WriteLine(response.Value?.Id);

A typed POST requires a non-empty JSON response body. If D365 accepted the mutation but the response body is missing or cannot be deserialized, the exception carries MutationOutcome = SucceededOrAccepted; do not blindly POST again.

Failure Handling

using FlintsLabs.D365.ODataClient.Exceptions;
using FlintsLabs.D365.ODataClient.Models;

try
{
    await client
        .Entity<EgrHead>("rvl_egrheads")
        .Where(head => head.Id == headId)
        .UpdateAsync(new { rvl_wmsstatus = false }, cancellationToken);
}
catch (D365HttpException exception)
{
    logger.LogWarning(
        "D365 rejected request: HTTP {Status}; code={Code}; request={RequestId}",
        exception.StatusCode,
        exception.D365ErrorCode,
        exception.RequestId);
}
catch (D365TransportException exception)
    when (exception.MutationOutcome == D365MutationOutcome.Unknown)
{
    // Query by the exact business/correlation key before deciding to retry.
}
catch (D365OperationCanceledException exception)
    when (exception.MutationOutcome == D365MutationOutcome.Unknown)
{
    // Cancellation after send does not prove the mutation was rolled back.
}

Do not interpret IsTransient as permission to retry a mutation. Use MutationOutcome and application-specific reconciliation.

Raw HTTP

SendAsync is the explicit raw-status API. It returns every HTTP response that reaches the client, including 4xx and 5xx; transport, timeout, and cancellation still throw because no HTTP response exists.

var response = await client.SendAsync(
    HttpMethod.Get,
    "rvl_egrheads?$top=1",
    cancellationToken: cancellationToken);

if (!response.IsSuccessStatusCode)
{
    response.EnsureSuccessStatusCode();
}

Use the fluent query methods for fail-closed deserialization and the raw API only when the caller intentionally owns status handling.

Retry and Cancellation

Automatic retry is disabled by default. Opt in only for safe reads:

builder.Services.AddD365ODataClient(d365 => d365
    // Authentication and endpoint configuration omitted.
    .ConfigureRetry(retry =>
    {
        retry.MaxReadRetries = 2;
        retry.BaseDelay = TimeSpan.FromMilliseconds(250);
        retry.MaxDelay = TimeSpan.FromSeconds(10);
        retry.UseJitter = true;
    }));

Only GET and HEAD may retry transient transport/timeouts or HTTP 408, 429, 500, 502, 503, and 504. POST, PATCH, and DELETE are not automatically retried for ambiguous failures. All async terminal methods accept CancellationToken.

Documentation

Development

dotnet restore
dotnet test FlintsLabs.D365.ODataClient.Tests/FlintsLabs.D365.ODataClient.Tests.csproj \
  -c Release \
  --filter "Category!=Integration"
dotnet build samples/FlintsLabs.D365.ODataClient.V2.Examples/FlintsLabs.D365.ODataClient.V2.Examples.csproj -c Release
dotnet list FlintsLabs.D365.ODataClient/FlintsLabs.D365.ODataClient.csproj package --vulnerable --include-transitive

The test project targets both .NET 8 and .NET 10; omit -f to test both, or use -f net8.0 / -f net10.0 separately. CI runs the non-integration suite on Windows and Linux for both frameworks on pull requests and pushes to main/codex/**, and builds the examples. TLS and redirect tests use local HTTPS servers and in-memory test CA trust; they do not modify the machine trust store or require Azure/D365 credentials. Configure the CI matrix jobs as required branch checks if they must block merging; adding the workflow alone does not enable branch protection.

Live integration tests are opt-in through D365_RUN_INTEGRATION_TESTS=true and require local configuration. Normal build and package workflows do not contact D365.

Publishing (Maintainers)

The publish workflow uses NuGet Trusted Publishing with GitHub OIDC. Configure a NuGet policy for publish-nuget.yml, scoped to this package, and set the NUGET_USER repository variable to the NuGet profile name that created the policy. No stored NuGet API key is required.

After Windows and Linux CI passes for the release commit on main, push its version tag. To publish an existing tag using the current workflow (for example, after a publishing failure), dispatch the workflow from main with release_tag set to the existing tag. The workflow checks out that tag and verifies the project version before building. The tag is not moved.

License

MIT. See LICENSE in the repository.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages