Monday, May 27, 2024

.NET 9 and ASP.NET Core: Built-in Support for OpenAPI Document Generation

With .NET 9, ASP.NET Core now has built-in support for OpenAPI document generation in both controller-based and minimal APIs. For as long as I can remember, ASP.NET Core has been using Swagger to generate the Open API document. Now we have Microsoft.AspNetCore.OpenApi package, and technically we can get rid of using Swagger. The new package still doesn't support a rich UI like Swagger UI, and that's something to look forward to.

Now let's see how this works.

Install the package: Microsoft.AspNetCore.OpenApi, note: it has to be the latest preview as of today and that is 9.0.0-preview.4.24267.6 (or any newer version than this).
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net9.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.0-preview.4.24267.6" />
  </ItemGroup>

</Project>
Now we can create a simple API something like follows:
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

builder.Services.AddOpenApi();

WebApplication app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
}

app.MapGet("/hello", () => "Hello world!")
    .WithDescription("Returns Hello");

app.Run();
You can access the OpenAPI document at: https://localhost:<port>/openapi/v1.json
OpenAPI Document
Read the following documentation to learn all the different customization options:

Hope this helps.

Happy Coding.

Regards,
Jaliya

Wednesday, May 22, 2024

C# 13.0: params Improvements

It's another exciting time of the year when Microsoft Build is happening, a lot of exciting announcements.

In this post, let's have a look at a C# 13.0 feature that is now available with the latest Visual Studio 2022 Version 17.11 Preview 1.

C# 13.0 is supported on .NET 9. To try this feature, make sure you are using the preview language version.
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net9.0</TargetFramework>
    <LangVersion>preview</LangVersion>
  </PropertyGroup>

</Project>
Prior to C# 13.0, when we are using params, the parameter must be a single-dimensional array, something like follows:
void DoSomething(params string[] items)
{
    
// do something with items
}
And we can call it as follows:
DoSomething("apple", "orange"); // comma separated list
DoSomething(["apple", "orange"]); // array
DoSomething(); // empty, the length of the params list is zero
With C# 13.0, params parameter type can be any recognized collection type, like List<T>, Span<T>, IEnumerable<T>, etc. You can even use your own collection types if they follow special rules.

So from C# 13.0, the following is totally valid.
void DoSomething(params IEnumerable<string> items)
{
    
// do something with items
}
That's pretty cool.

If you still haven't registered for Microsoft Build 2024, you are still not late. Register now for free and access all the exciting content.

Happy Coding.

Regards,
Jaliya

Tuesday, May 14, 2024

C# 12.0: .. Spread Element or Spread Operator

C# 12.0 introduced .. and its terminology is a bit confusing, some call it Spread Element and some call it Spread Operator.

Before going through the correct terminology, first, let's see what it does.

IEnumerable<string> sweetFruits = ["Apple", "Banana", "Mango", "Pineapple"];
IEnumerable<string> sourFruits = ["Orange", "Grapefruit", "Lemon", "Lime"];

IEnumerable<string> fruits = [.. sweetFruits, .. sourFruits];
// Output: Apple, Banana, Mango, Pineapple, Orange, Grapefruit, Lemon, Lime

Here .. is spreading the elements in a collection. We are spreading the sweetFruits and sourFruits, and then combining those to create fruits.

And we can use this feature in different ways.

For an example consider this.

IEnumerable<Employee> employees =
[
    new Employee("John Doe", "Contract"),
    new Employee("Jane Doe", "Permanent")
];

List<Employee> permanentEmployees = employees
    .Where(e => e.Type == "Permanent")
    .ToList();

We can use .. and filter permanentEmployees as follows and not do .ToList().

List<Employee> permanentEmployees =
[
    .. employees.Where(e => e.Type == "Permanent")
];

Now what do we call it? 

There is a nice explanation given in this post: .NET Blog: Refactor your code with C# collection expressions

Spread Element
I personally agree with the explanation and even the feature specification uses the term Spread Element. But there are some places in official .NET documentation (like here: C# 12: Collection Expressions) that refer .. as Spread Operator.

Hopefully, we can get this terminology consistent across.

Hope this helps.

Happy Coding.

Regards,
Jaliya


Update 15/05/2024:

Reached out to .NET team and they are already in the process of addressing inconsistencies, both in the feature spec and the docs. It is going to be called the Spread Element and not Spread Operator.

Also, note that .. is used in three different places in the language: in collection expressions to indicate a spread element, in list patterns to indicate a slice pattern and as the range operator. The only location where it’s an operator is the range operator.

Wednesday, May 1, 2024

Visual Studio: New Durable Functions Project: System.InvalidOperationException: Synchronous operations are disallowed

When creating a new Azure Function App Project and selecting Durable Functions Orchestration, right now the basic functionality is erroring out when the default Http Function is triggered.

Error: System.InvalidOperationException: Synchronous operations are disallowed. Call WriteAsync or set AllowSynchronousIO to true instead.


Unfortunately, this is a known issue (https://github.com/Azure/azure-functions-dotnet-worker/issues/2425) with the templates and hopefully, the templates will get updated soon.

For the time being, you can update the code in the HttpStart function to use CreateCheckStatusResponseAsync as follows.
[Function("Function1_HttpStart")]
public static async Task<HttpResponseData> HttpStart(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestData req,
    [DurableClient] DurableTaskClient client,
    FunctionContext executionContext)
{
    ILogger logger = executionContext.GetLogger("Function1_HttpStart");

    // Function input comes from the request content.
    string instanceId = await client.ScheduleNewOrchestrationInstanceAsync(
        nameof(Function1));

    logger.LogInformation("Started orchestration with ID = '{instanceId}'.", instanceId);

    
// Returns an HTTP 202 response with an instance management payload.
    // See https://learn.microsoft.com/azure/azure-functions/durable/durable-functions-http-api#start-orchestration

    return await client.CreateCheckStatusResponseAsync(req, instanceId);
}
Hope this helps.

Happy Coding.

Regards,
Jaliya