Skip to content

Conversation

EraYaN
Copy link
Contributor

@EraYaN EraYaN commented Oct 2, 2025

Quite some small changes in this PR, felt like a waste to split them up. Commit f814598 could be expanded to include even more versions of .NET if so desired.

8a7edb2 - Update documentation and samples

0bfc7f8 - Support multi targetting
This makes it so that when you have both net8 and net9 (for example) the csproj includes both. This makes sure that consumers of your package will get to use the newest transitive dependencies.

c3b74e5 - Expose ContentHeaders on ApiResponse, to access ContentDisposition for example with file downloads.
Very useful for downloading files, you can now access details and many more headers about the actual Content.

f35af99 - Include full response object in ApiException
This gives adds a lot of convenience to debugging using a generated API client.

c56afb2 - Add support for other Accept header values or full arrays when multiple options are present.
This uses the correct (array) for the Accept header for non json responses.

a98c339 - Make TokenProvider not contain state so subclassing actually works correctly with JIT requested tokens (for long lived ApiClients)
This allows the ApiClient to use say client credentials and an OAuth flow to requests and cache tokens appropriately without knowing the tokens before hand.

Example implementation
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using ApiTest.Shared;
using Calcasa.Api;
using Calcasa.Api.Client;
using Duende.IdentityModel.Client;
using Microsoft.Extensions.Options;

public class ServiceOAuthTokenProvider : TokenProvider<OAuthToken>
{
    private readonly string ClientId;
    private readonly string ClientSecret;
    private readonly string TokenUrl;
    private readonly HttpClient AuthClient;
    private ConcurrentDictionary<string, (TokenResponse Token, DateTime ExpiresOn)> Tokens;

    public ServiceOAuthTokenProvider(IOptions<CalcasaApiOptions> options)
    {
        Tokens = [];
        ClientId = options.Value.ClientId;
        ClientSecret = options.Value.ClientSecret;
        TokenUrl = options.Value.TokenUrl;
        AuthClient = new HttpClient();
    }

    public override ValueTask<OAuthToken> GetAsync(string header = "", CancellationToken cancellation = default)
    {
        var data = Tokens.GetValueOrDefault(header);

        if (data.Token != null)
        {
            if (!data.Token.IsError || data.ExpiresOn > DateTime.UtcNow)
            {
                return ValueTask.FromResult(new OAuthToken(data.Token.AccessToken));
            }
        }

        var request = new ClientCredentialsTokenRequest
        {
            Address = TokenUrl,
            ClientId = ClientId,
            ClientSecret = ClientSecret,
            ClientCredentialStyle = ClientCredentialStyle.AuthorizationHeader, // Recommended as opposed to secrets in body.
        };

        data.Token = AuthClient.RequestClientCredentialsTokenAsync(request).Result;

        if (data.Token.IsError)
        {
            throw new ApplicationException("Could not refresh token: [" + data.Token.ErrorType + "] " + data.Token.Error + "; " + data.Token.ErrorDescription);
        }
        else
        {
            data.ExpiresOn = DateTime.UtcNow.AddSeconds(data.Token.ExpiresIn);
            Tokens.AddOrUpdate(header, (h) => data, (h, oldData) => data);

            return ValueTask.FromResult(new OAuthToken(data.Token.AccessToken));
        }
    }
}

74ab0ef - Fix DateOnly parsing, DateTimeStyles are not supported in TryParseExact
This fixes the calls to TryParseExact so they actually work, the DateTimeStyles besides None are not supported when say parsing the string "2025-07-01" which is absolutely in the given formats array. (It hits this case)

PR checklist

  • Read the contribution guidelines.
  • Pull Request title clearly describes the work in the pull request and Pull Request description provides details about how to validate the work. Missing information here may result in delayed response from the community.
  • Run the following to build the project and update samples:
    ./mvnw clean package || exit
    ./bin/generate-samples.sh ./bin/configs/*.yaml || exit
    ./bin/utils/export_docs_generators.sh || exit
    
    (For Windows users, please run the script in WSL)
    Commit all changed files.
    This is important, as CI jobs will verify all generator outputs of your HEAD commit as it would merge with master.
    These must match the expectations made by your contribution.
    You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example ./bin/generate-samples.sh bin/configs/java*.
    IMPORTANT: Do NOT purge/delete any folders/files (e.g. tests) when regenerating the samples as manually written tests may be removed.
  • File the PR against the correct branch: master (upcoming 7.x.0 minor release - breaking changes with fallbacks), 8.0.x (breaking changes without fallbacks)
  • If your PR solves a reported issue, reference it using GitHub's linking syntax (e.g., having "fixes #123" present in the PR description)
  • If your PR is targeting a particular programming language, @mention the technical committee members, so they are more likely to review the pull request.

C# Technical Committee
@mandrean @shibayan @Blackclaws @lucamazzanti @iBicha

@devhl-labs

The generator seems to still support the netstandard1.* targets but none of the dependencies still list those on Nuget. Seems like they are fully abandoned/deprecated.

And has generichost ever supported .NET4.7 and .NET4.8? Seems like System.Text.Json is missing regardless of the changes in this PR.

@EraYaN EraYaN changed the title C# GenericHost udpate to facilitate better Accept header support, DateOnly parsing, multitargetting. exposing more headers and proper JIT tokens C# GenericHost changes to facilitate better Accept header support, DateOnly parsing, multitargetting. exposing more headers and proper JIT tokens Oct 2, 2025
@EraYaN EraYaN changed the title C# GenericHost changes to facilitate better Accept header support, DateOnly parsing, multitargetting. exposing more headers and proper JIT tokens C# GenericHost changes to facilitate better Accept header support, DateOnly parsing, multitargetting, exposing more headers and proper JIT tokens Oct 2, 2025
@EraYaN EraYaN force-pushed the generichost-updates branch 3 times, most recently from afab356 to fdf530c Compare October 2, 2025 12:50
@EraYaN EraYaN force-pushed the generichost-updates branch from fdf530c to fa75fef Compare October 2, 2025 12:53
@EraYaN EraYaN force-pushed the generichost-updates branch from fa75fef to 8a7edb2 Compare October 2, 2025 12:58
@wing328
Copy link
Member

wing328 commented Oct 6, 2025

thanks for the PR

can you please review the build failure when you've time?

@EraYaN
Copy link
Contributor Author

EraYaN commented Oct 6, 2025

I had forgotten that the nullable reference types are supposed to be in a conditional block. And collection expressions are also unavailable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants