### Install .NET Core Global Tool Source: https://github.com/centeredge/yardarm/blob/main/docs/generating/README.md Install the Yardarm command-line interface as a global tool. This command is used for managing SDK generation from the terminal. ```sh dotnet tool install --global Yardarm.CommandLine --version 0.3.0-beta0001 yardarm help generate ``` -------------------------------- ### Basic Dependency Injection Setup Source: https://github.com/centeredge/yardarm/blob/main/docs/consuming/dependency-injection.md This snippet shows the minimal configuration required to register Yardarm SDK APIs using dependency injection. Ensure the appropriate Yardarm extension (e.g., Yardarm.MicrosoftExtensionsHttp) is used during SDK generation. ```csharp public void ConfigureServices(IServiceCollection services) { // Other services are registered here services.AddXXXApis() // AddXXXApis name will vary based on the SDK name, and returns an IApiBuilder .AddAllApis(); } ``` -------------------------------- ### Example Yardarm SDK Project Configuration Source: https://github.com/centeredge/yardarm/blob/main/docs/generating/yardarm-sdk.md This snippet shows a basic .csproj file for a Yardarm SDK project. It specifies the SDK to use and includes an OpenAPI specification file, which can be in .yaml or .json format. ```xml netstandard2.0 ``` -------------------------------- ### Example Service Using Yardarm API Source: https://github.com/centeredge/yardarm/blob/main/docs/consuming/mocking.md This C# code defines a service that depends on an IMyApi interface, which would typically be generated by Yardarm. ```csharp public class MyService { private readonly IMyApi api; public MyService(IMyApi api) { _api = api; } public async Task DoSomethingAsync(CancellationToken cancellationToken = default) { var request = new MyOperationJsonRequest { Body = new MyRequestBody(); }; var response = await _api.MyOperationAsync(request, cancellationToken); // Process response here... } } ``` -------------------------------- ### Yardarm SDK Multi-targeting Configuration Source: https://github.com/centeredge/yardarm/blob/main/docs/generating/yardarm-sdk.md This example demonstrates how to configure a Yardarm SDK project to target multiple .NET frameworks. Note that Yardarm does not directly support net4x targets, but they can be included via netstandard2.0. ```xml netstandard2.0;net6.0 ``` -------------------------------- ### Manual Registration of Yardarm API Client Source: https://github.com/centeredge/yardarm/blob/main/docs/consuming/dependency-injection.md Provides an example of manually registering a Yardarm API client with Microsoft.Extensions.DependencyInjection when not using the automatic integration. This includes registering type serializers, authenticators, and the HttpClient itself. ```cs public static IServiceCollection AddApiServices(this IServiceCollection services) { services.TryAddSingleton(TypeSerializerRegistry.Instance); // For a simple, static set of authenticators. services.TryAddSingleton(new Authenticators()); // Or, for authenticators configured from appsettings.json in ASP.NET Core. // Note: Only choose one or the other, not both. services.TryAddSingleton(serviceProvider => { var options = serviceProvider.GetRequiredService>().Value; return new Authenticators { // Configure from options here. } }); // This assumes you are using the Microsoft.Extensions.Http NuGet package. // Repeat this step for each API interface in the SDK you intend to consume. if (!services.Any(s => s.ServiceType == typeof(IMyApi))) { var builder = services.AddHttpClient((serviceProvider, httpClient) => { var options = serviceProvider.GetRequiredService>().Value; // This could also be a constant instead of using IOptions to acquire from configuration. // Use IOptionsSnapshot if you desire options that dynamically update at runtime. httpClient.BaseAddress = options.MyBaseUri; }); // Make additional calls to register middleware on the HttpClient, if desired. // This can also be used to add Polly policies, such as retries and circuit breakers, // via the Microsoft.Extensions.Http.Polly NuGet package. builder.AddHttpMessageHandler(); } } ``` -------------------------------- ### Run Yardarm via Docker Source: https://github.com/centeredge/yardarm/blob/main/docs/generating/README.md Execute Yardarm commands using a Docker container. This is useful for consistent environments and avoiding local installations. ```sh docker run -it ghcr.io/centeredge/yardarm:0.3.0-beta0001 yardarm help generate ``` -------------------------------- ### Simple Response Handling with .AsXXX() Source: https://github.com/centeredge/yardarm/blob/main/docs/consuming/handling-responses.md Use .AsXXX() methods to cast a response to an expected status code. This method throws a StatusCodeMismatchException if the status code does not match. Get the strongly-typed body using GetBodyAsync(). ```csharp MyOperationJsonRequest request = new MyOperationJsonRequest(); // Returns a generic response using var response = await api.MyOperationAsync(request); // Throws StatusCodeMismatchException if the response is not a MyOperationOkResponse MyOperationOkResponse okResponse = response.AsOk(); // GetBodyAsync is available for any response known to return content, strongly typed to the schema var body = await okResponse.GetBodyAsync(); ``` -------------------------------- ### Generate DLL for net6.0 with System.Text.Json and DI Source: https://github.com/centeredge/yardarm/blob/main/docs/generating/README.md Generates a DLL and related files targeting net6.0, utilizing System.Text.Json and DI support. Ensure the output directory path is correctly specified. ```sh yardarm generate -i my-spec.yaml -n MySpec -v 1.0.0 -f net6.0 -o output/directory/ -x Yardarm.SystemTextJson Yardarm.MicrosoftExtensionsHttp ``` -------------------------------- ### MSBuild Project Configuration Source: https://github.com/centeredge/yardarm/blob/main/docs/generating/README.md Use this MSBuild project configuration to generate an SDK. Ensure your OpenAPI specification file is in the same directory. ```xml netstandard2.0;net6.0 ``` -------------------------------- ### Generate DLL with Newtonsoft.Json and DI Source: https://github.com/centeredge/yardarm/blob/main/docs/generating/README.md Generates a DLL and related files using Newtonsoft.Json and DI support. Specify the output directory with a trailing slash. ```sh yardarm generate -i my-spec.yaml -n MySpec -v 1.0.0 -o output/directory/ -x Yardarm.NewtonsoftJson Yardarm.MicrosoftExtensionsHttp ``` -------------------------------- ### Generate NuGet Package for multiple targets with System.Text.Json and DI Source: https://github.com/centeredge/yardarm/blob/main/docs/generating/README.md Generates a NuGet package and symbols package for net6.0 and netstandard2.0, using System.Text.Json and DI support. The output path determines whether it's a directory or file. ```sh yardarm generate -i my-spec.json -n MySpec -v 1.0.0 -f net6.0 netstandard2.0 --nupkg output/directory/ -x Yardarm.SystemTextJson Yardarm.MicrosoftExtensionsHttp ``` -------------------------------- ### Generate NuGet Package with Newtonsoft.Json and DI Source: https://github.com/centeredge/yardarm/blob/main/docs/generating/README.md Creates a NuGet package and symbols package with Newtonsoft.Json and DI support. The output path can be a directory or a file name. ```sh yardarm generate -i my-spec.json -n MySpec -v 1.0.0 --nupkg output/directory/ -x Yardarm.NewtonsoftJson Yardarm.MicrosoftExtensionsHttp ``` -------------------------------- ### Include Additional C# Files in SDK Generation Source: https://github.com/centeredge/yardarm/blob/main/docs/generating/README.md Use the --include option to add custom C# files to the generated SDK project. These files will be compiled with the generated code and can be embedded in the PDB if --embed is also used. ```bash yardarm generate -i my-spec.yaml -n MySpec -v 1.0.0 -o output/directory/ --include file1.cs file2.cs ``` -------------------------------- ### Unit Test with Moq Mocked API Source: https://github.com/centeredge/yardarm/blob/main/docs/consuming/mocking.md This C# unit test demonstrates how to use Moq to mock the IMyApi interface. It sets up a specific response for the MyOperationAsync method and passes the mocked API to the service under test. ```csharp [Fact] public async Task MyTest() { // Headers are optional, leave this off for responses that don't use special headers var headers = new HttpResponseHeaders(); headers.Add("X-My-Header", "value"); // Leave this off for responses that don't have a body var body = new MyResponseBody(); var api = new Mock(); api .Setup(m => m.MyOperationAsync(It.IsAny(), It.IsAny())) .ReturnsAsync(new MyOperationOkResponse(body, headers)); var myService = new MyService(api.Object); await myService.DoSomethingAsync(); // More assertions here } ``` -------------------------------- ### Advanced Dependency Injection Configuration Source: https://github.com/centeredge/yardarm/blob/main/docs/consuming/dependency-injection.md This snippet demonstrates advanced customization options for Yardarm SDK integration, including authentication, HTTP client settings, message handlers, and API-specific configurations. It allows for fine-grained control over how HTTP requests are made and processed. ```csharp public void ConfigureServices(IServiceCollection services) { // Other services are registered here services.AddXXXApis() // AddXXXApis name will vary based on the SDK name, and returns an IApiBuilder .ConfigureAuthenticators(authenticators => { // Apply any global authentication rules here. // There is also an overload which provides an IServiceProvider parameter. }) .ConfigureHttpClient(client => { // Apply global configuration to the HttpClient, such as the BaseAddress or timeouts // There is also an overload which provides an IServiceProvider parameter. // For simply setting the BaseAddress, there is also a ConfigureBaseAddress method. }) .ConfigurePrimaryHttpMessageHandler(() => { // Configure or substitute the primary HttpMessageHandler. // There are also overloads which provides an IServiceProvider or accepts the type // of the handler as a generic type parameter. return new HttpClientHandler(); }) .AddHttpMessageHandler(() => { // Add a DelegatingHandler to the stack which is applied to all APIs within the SDK. // There are also overloads which provides an IServiceProvider or accepts the type // of the handler as a generic type parameter. return new MyDelegatingHandler(); }) .RedactLoggedHeaders(new[] {"Authorization"}) // Redact one or more headers from logging .AddApi(builder => { // This adds a specific API from the SDK (IApiType) along with its concrete implementation (ApiType). // The builder is an IHttpClientBuilder which is used to further customize behaviors for // this specific API. // Any builder.ConfigureHttpClient calls are executed after the global configurations. // Any builder.ConfigurePrimaryHttpMessageHandler call will completely replace the global configuration. // Any builder.AddHttpMessageHandler calls will add further message handlers, in addition to the global configuration. // Any builder.RedactLoggedHeaders call will completely replace the global configuration. }) .AddAllOtherApis((type, builder) => { // Adds all other APIs which have not been manually registered above. // The type parameter is the IApiType of the API being added. // The builder parameter allows further customization of the HttpClient in the same way as AddApi above. }); // .AddAllApis((type, builder) => { }) may also be used to add all APIs from the SDK. // The AddAllApis method will throw an InvalidOperationException if any APIs are manually registered. } ``` -------------------------------- ### Injecting Yardarm API Client into a Service Source: https://github.com/centeredge/yardarm/blob/main/docs/consuming/dependency-injection.md Demonstrates how to inject a Yardarm-generated API client (IMyApi) into a service class using constructor injection. The HttpClient is managed automatically by the DI container. ```cs public class MyService { private readonly IMyApi api; public MyService(IMyApi api) { _api = api; } public async Task DoSomethingAsync(CancellationToken cancellationToken = default) { // Call methods on _api here, all handling of HttpClient is automatic. // Default authenticators are received from DI, but may overridden per-request. } } ``` -------------------------------- ### Download OpenAPI Specs Dynamically for Yardarm SDK Source: https://github.com/centeredge/yardarm/blob/main/docs/generating/yardarm-sdk.md Override the `CollectOpenApiSpecs` target to dynamically download OpenAPI specification files from a URL. The downloaded file is then added to the project as an `OpenApiSpec` item. ```xml netstandard2.0 ``` -------------------------------- ### Yardarm SDK Configuration with Extensions Source: https://github.com/centeredge/yardarm/blob/main/docs/generating/yardarm-sdk.md Configure Yardarm SDK by specifying the Sdk and including custom extensions. The JsonMode and DependencyInjectionMode properties control serialization and DI behavior. ```xml netstandard2.0 Newtonsoft.Json None ``` -------------------------------- ### Include Additional C# Files in Yardarm SDK Source: https://github.com/centeredge/yardarm/blob/main/docs/generating/yardarm-sdk.md Use the `` item to include additional C# files from other directories into the SDK generation process. This feature is available from Yardarm SDK version 0.7.0 onwards. ```xml netstandard2.0 ``` -------------------------------- ### Yardarm SDK Project Properties Configuration Source: https://github.com/centeredge/yardarm/blob/main/docs/generating/yardarm-sdk.md Configure various aspects of the Yardarm SDK generation, including JSON mode, dependency injection, date/time handling, unknown discriminator handling, and HTTP version settings. ```xml netstandard2.0 SomeOtherAssemblyName Some.Other.Namespace 5.6.7 false false false true Key.snk ClassLibDotNetStandard your_name your_company tag1;tag2 This is a long description Newtonsoft.Json None NodaTime ReturnNull 2.0 RequestVersionOrLower ``` -------------------------------- ### Handling Same Schema for Different Response Codes Source: https://github.com/centeredge/yardarm/blob/main/docs/consuming/handling-responses.md Employ switch expressions to conveniently extract the body from responses that share the same schema but have different status codes. ```csharp MyOperationJsonRequest request = new MyOperationJsonRequest(); // Returns a generic response using var response = await api.MyOperationAsync(request); var body = response switch { MyOperationOkResponse okResponse => await okResponse.GetBodyAsync(), MyOperationCreatedResponse createdResponse => await createdResponse.GetBodyAsync(), _ => throw new Exception("...") }; ``` -------------------------------- ### Advanced Response Handling with Type Checking Source: https://github.com/centeredge/yardarm/blob/main/docs/consuming/handling-responses.md Utilize type checking (e.g., switch statements) to handle different response types, including error responses. This allows for reading bodies from various status codes. ```csharp MyOperationJsonRequest request = new MyOperationJsonRequest(); // Returns a generic response using var response = await api.MyOperationAsync(request); switch (response) { case MyOperationOkResponse okResponse: var okBody = await okResponse.GetBodyAsync(); // do things break; case MyOperationNotFoundResponse notFoundResponse: var notFoundBody = await notFoundResponse.GetBodyAsync(); // do things break; case MyOperationUnknownResponse unknownResponse: var body = await unknownResponse.GetBodyAsync(); // do things break; } ``` -------------------------------- ### Working with Unknown Status Codes Source: https://github.com/centeredge/yardarm/blob/main/docs/consuming/handling-responses.md Use the XXXUnknownResponse type to handle status codes not defined in the OpenAPI specification. The GetBodyAsync method can deserialize any type, useful for unexpected errors like 503 or 504. ```csharp MyOperationJsonRequest request = new MyOperationJsonRequest(); // Returns a generic response using var response = await api.MyOperationAsync(request); if (response is MyOperationUnknownResponse unknownResponse) { if (unknownResponse.StatusCode == HttpStatusCode.Forbidden) { var body = await unknownResponse.GetBodyAsync(); // Do something with the body here. } else { throw new Exception("..."); } } ``` -------------------------------- ### Accessing Other Response Properties Source: https://github.com/centeredge/yardarm/blob/main/docs/consuming/handling-responses.md Access properties like StatusCode, IsSuccessStatusCode, and the raw HttpResponseMessage to inspect response details. Note that checking the type is often preferred over checking the status code directly. ```csharp MyOperationJsonRequest request = new MyOperationJsonRequest(); // Returns a generic response using var response = await api.MyOperationAsync(request); // Access the status code if (response.StatusCode == HttpStatusCode.Created) { // Note: in many cases, testing for the type MyOperationOkResponse is preferable. // However, if you don't need the body or the headers, this may be simpler. } // Determine if the status code was a success or failure code. if (!response.IsSuccessStatusCode) { throw new Exception("..."); } // Access the raw HttpResponseMessage. if (response.Message.Content.Headers.ContentType.MediaType == "application/json") { } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.