Skip to main content

AsyncApi–Share your message contracts in a language agnostic manner–Part 2

Yesterday I introduced the AsyncApi specification as a way to share message contracts in a language neutral way. Let’s continue today by looking how we can generate a C# messagecontract based on your AsyncAPI specification file.

Here is the example specification file again that I shared yesterday:

asyncapi: 2.3.0
info:
title: Mail Service
version: 1.0.0
description: This service is in charge of asynchronous mail sending
channels:
mailqueue:
publish:
message:
$ref: '#/components/messages/SendMailCommand'
subscribe:
message:
$ref: '#/components/messages/MailSentEvent'
servers:
development:
url: development.example.be
protocol: amqp
description: Development RabbitMQ server
acceptatie:
url: acceptance.example.be
protocol: amqp
description: Acceptance RabbitMQ server
components:
messages:
SendMailCommand:
payload:
type: object
properties:
subject:
type: string
format: string
description: Subject of the email
from:
type: string
format: email
description: Emailaddress of the sender
to:
type: string
format: email
description: Emailaddress of the receiver
body:
type: string
format: string
description: Body of the email
MailSentEvent:
payload:
type: object
properties:
subject:
type: string
format: string
description: Subject of the email
from:
type: string
format: email
description: Emailaddress of the sender
to:
type: string
format: email
description: Emailaddress of the receiver
view raw message.yaml hosted with ❤ by GitHub

To transform this specification file to a data contract, we can use the Async API generator. The generator uses templates to specify what must be generated.

There is a list of official generator templates, unfortunately C# is not part of this list. Thanks to the community a csharp compatible template exists; https://github.com/jonaslagoni/asyncapi-quicktype-template

Let’s try that one!

Install the generator

First install the generator through NPM:

npm install -g @asyncapi/generator

You can optionally pre-install the quicktype template:

npm install -g @lagoni/asyncapi-quicktype-template

Generate C# Message contracts

Now we can generate the C# message contracts:

ag message.yaml @lagoni/asyncapi-quicktype-template -o output --param "quick
typeLanguage=csharp"

You can check the full list of available parameters for this template here: https://github.com/quicktype/quicktype/blob/e6cc44fdfcb75c3f3ed3e12f69f15a0c863a1a05/src/quicktype-core/language/CSharp.ts#L115

This will generate 2 message contracts:

// <auto-generated />
//
// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
//
// using MailSentEventNameSpace;
//
// var mailSentEvent = MailSentEvent.FromJson(jsonString);
namespace MailSentEventNameSpace
{
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public partial class MailSentEvent
{
/// <summary>
/// Emailaddress of the sender
/// </summary>
[JsonProperty("from", NullValueHandling = NullValueHandling.Ignore)]
public string From { get; set; }
/// <summary>
/// Subject of the email
/// </summary>
[JsonProperty("subject", NullValueHandling = NullValueHandling.Ignore)]
public string Subject { get; set; }
/// <summary>
/// Emailaddress of the receiver
/// </summary>
[JsonProperty("to", NullValueHandling = NullValueHandling.Ignore)]
public string To { get; set; }
}
public partial class MailSentEvent
{
public static MailSentEvent FromJson(string json) => JsonConvert.DeserializeObject<MailSentEvent>(json, MailSentEventNameSpace.Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this MailSentEvent self) => JsonConvert.SerializeObject(self, MailSentEventNameSpace.Converter.Settings);
}
internal static class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters =
{
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
},
};
}
}
// <auto-generated />
//
// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
//
// using SendMailCommandNameSpace;
//
// var sendMailCommand = SendMailCommand.FromJson(jsonString);
namespace SendMailCommandNameSpace
{
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public partial class SendMailCommand
{
/// <summary>
/// Body of the email
/// </summary>
[JsonProperty("body", NullValueHandling = NullValueHandling.Ignore)]
public string Body { get; set; }
/// <summary>
/// Emailaddress of the sender
/// </summary>
[JsonProperty("from", NullValueHandling = NullValueHandling.Ignore)]
public string From { get; set; }
/// <summary>
/// Subject of the email
/// </summary>
[JsonProperty("subject", NullValueHandling = NullValueHandling.Ignore)]
public string Subject { get; set; }
/// <summary>
/// Emailaddress of the receiver
/// </summary>
[JsonProperty("to", NullValueHandling = NullValueHandling.Ignore)]
public string To { get; set; }
}
public partial class SendMailCommand
{
public static SendMailCommand FromJson(string json) => JsonConvert.DeserializeObject<SendMailCommand>(json, SendMailCommandNameSpace.Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this SendMailCommand self) => JsonConvert.SerializeObject(self, SendMailCommandNameSpace.Converter.Settings);
}
internal static class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters =
{
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
},
};
}
}

Generate documentation

The generator templates are quite versatile. So can you also use it to generate documentation in HTML or Markdown format.
ag message.yaml @asyncapi/html-template -o output
Here is how the generated html output looks like:

Popular posts from this blog

Kubernetes–Limit your environmental impact

Reducing the carbon footprint and CO2 emission of our (cloud) workloads, is a responsibility of all of us. If you are running a Kubernetes cluster, have a look at Kube-Green . kube-green is a simple Kubernetes operator that automatically shuts down (some of) your pods when you don't need them. A single pod produces about 11 Kg CO2eq per year( here the calculation). Reason enough to give it a try! Installing kube-green in your cluster The easiest way to install the operator in your cluster is through kubectl. We first need to install a cert-manager: kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.14.5/cert-manager.yaml Remark: Wait a minute before you continue as it can take some time before the cert-manager is up & running inside your cluster. Now we can install the kube-green operator: kubectl apply -f https://github.com/kube-green/kube-green/releases/latest/download/kube-green.yaml Now in the namespace where we want t...

Azure DevOps/ GitHub emoji

I’m really bad at remembering emoji’s. So here is cheat sheet with all emoji’s that can be used in tools that support the github emoji markdown markup: All credits go to rcaviers who created this list.

.NET 9 - Goodbye sln!

Although the csproj file evolved and simplified a lot over time, the Visual Studio solution file (.sln) remained an ugly file format full of magic GUIDs. With the latest .NET 9 SDK(9.0.200), we finally got an alternative; a new XML-based solution file(.slnx) got introduced in preview. So say goodbye to this ugly sln file: And meet his better looking slnx brother instead: To use this feature we first have to enable it: Go to Tools -> Options -> Environment -> Preview Features Check the checkbox next to Use Solution File Persistence Model Now we can migrate an existing sln file to slnx using the following command: dotnet sln migrate AICalculator.sln .slnx file D:\Projects\Test\AICalculator\AICalculator.slnx generated. Or create a new Visual Studio solution using the slnx format: dotnet new sln --format slnx The template "Solution File" was created successfully. The new format is not yet recognized by VSCode but it does work in Jetbr...