Sunday, 16 February 2025

Outputting tags/objects using Azure AI

This article presents a way to output tags for an image and output it to the console. Azure AI is used, more specifically the ImageAnalysisClient. The article shows how you can define a way to consume the data for an IAsyncEnumerable, so you can use await foreach to consume the data. I would recommend this approach for many services in Azure Ai (and similar) where there is no support out of the box for async enumerable and hide away the deails in a helper extension method as shown in this article.



  public static async void ExtractImageTags()
  {
      string visionApiKey = Environment.GetEnvironmentVariable("VISION_KEY")!;
      string visionApiEndpoint = Environment.GetEnvironmentVariable("VISION_ENDPOINT")!;

      var credentials = new AzureKeyCredential(visionApiKey);
      var serviceUri = new Uri(visionApiEndpoint);

      var imageAnalysisClient = new ImageAnalysisClient(serviceUri, credentials);
      await foreach (var tag in imageAnalysisClient.ExtractImageTagsAsync("Images/Store.png"))
      {
          Console.WriteLine(tag);
      }           
  }
  

The code creates an ImageAnalysisClient, defined in the Azure.AI.Vision.ImageAnalysis Nuget package. I got two environment variables here to store the key and endpoint. Note that not all Azure Ai features are available in all regions. If you just want to test out some Azure Ai features, you can first off just test it out at US East region, as that region will have most likely all features you want to test, then you can just a more local region if you are planning to do more workloads using Azure Ai.

Then we use an await foreach pattern here to extract the image tags asynchronously. This is a custom extension method I created so I can output the tags asynchronously using await foreach and also specify a wait time between each new tag being outputted, defaulting to 200 milliseconds here.

The extension method looks like this:


using Azure.AI.Vision.ImageAnalysis;

namespace UseAzureAIServicesFromNET.Vision;

public static class ImageAnalysisClientExtensions
{

    /// <summary>
    /// Extracts the tags for image at specified path, if existing.
    /// The results are returned as async enumerable of strings. 
    /// </summary>
    /// <param name="client"></param>
    /// <param name="imagePath"></param>
    /// <param name="waitTimeInMsBetweenOutputTags">Default wait time in ms between output. Defaults to 200 ms.</param>
    /// <returns></returns>
    public static async IAsyncEnumerable<string?> ExtractImageTagsAsync(this ImageAnalysisClient client, 
    	string imagePath, int waitTimeInMsBetweenOutputTags = 200)
    {
        if (!File.Exists(imagePath))
        {
            yield return default(string); //just return null if a file is not found at provided path
        }
        using FileStream imageStream = new FileStream(imagePath, FileMode.Open);
        var analysisResult = 
        	await client.AnalyzeAsync(BinaryData.FromStream(imageStream), VisualFeatures.Tags | VisualFeatures.Caption);
        yield return $"Description: {analysisResult.Value.Caption.Text}";
        foreach (var tag in analysisResult.Value.Tags.Values)
        {
            yield return $"Tag: {tag.Name}, Confidence: {tag.Confidence:F2}";        
            await Task.Delay(waitTimeInMsBetweenOutputTags);
        }
    }

}


The console output of the tags looks like this:

In addition to tags, we can also output objects in the image in a very similar extension method:


/// <summary>
/// Extracts the objects for image at specified path, if existing.
/// The results are returned as async enumerable of strings. 
/// </summary>
/// <param name="client"></param>
/// <param name="imagePath"></param>
/// <param name="waitTimeInMsBetweenOutputTags">Default wait time in ms between output. Defaults to 200 ms.</param>
/// <returns></returns>
public static async IAsyncEnumerable<string?> ExtractImageObjectsAsync(this ImageAnalysisClient client,
string imagePath, int waitTimeInMsBetweenOutputTags = 200)
{
    if (!File.Exists(imagePath))
    {
        yield return default(string); //just return null if a file is not found at provided path
    }
    using FileStream imageStream = new FileStream(imagePath, FileMode.Open);
    var analysisResult =
    	await client.AnalyzeAsync(BinaryData.FromStream(imageStream), VisualFeatures.Objects | VisualFeatures.Caption);
    yield return $"Description: {analysisResult.Value.Caption.Text}";
    foreach (var objectInImage in analysisResult.Value.Objects.Values)
    {
            yield return $"""
Object tag: {objectInImage.Tags.FirstOrDefault()?.Name} Confidence: {objectInImage.Tags.FirstOrDefault()?.Confidence}, 
Position (bbox): {objectInImage.BoundingBox}
""";
        await Task.Delay(waitTimeInMsBetweenOutputTags);
    }
}           
             

The code is nearly identical, we set the VisualFeatures of the image to extract and we read out the objects (not the tags). The console output of the objects looks like this:

Monday, 27 January 2025

Kinesisk nyttår i .NET

新年快乐

Det nærmer seg Kinesisk nyttår i 2025 ! Dette skjer 29. januar i år. I denne artikkelen vil metoder for å regne ut Kinesisk nyttår i .NET presenteres. Det er en del utregninger, heldigvis har .NET en hjelpeklasse for nettopp dette. Xīn nián kuài lè Xīn - Nytt nián - År kuài lè - Godt/lykkelig Uttale er ca slik: "Xin nien quai løe"




Regne ut Kinesisk nyttår


I denne artikkelen skal vi se på hvordan vi kan regne ut Kinesisk nyttår i .NET ! Vi kan regne ut Kinesisk nyttår i .NET på en intrikat måte. Det er definert som den andre nymånen etter vintersolverv. Nyttår faller dermed vanligvis mellom 21. januar og 20. februar og vil derfor variere fra år til år. I .NET har vi en klasse som heter ChineseLunisolarCalendar som en kan regne over til vår gregorianske kalender, som vi har hatt i Vesten siden
1582. Noen land, som Russland, Serbia og Etiopia bruker den julianske kalenderen i visse religiøse sammenhenger. Obs ! Denne klassen kan regne ut maks frem til og med år 2100 kinesisk nyttår, som jo er et stykke frem i tid. Men om 76 år må nok kildekoden her endres ! Kanskje en "V2" av denne klassen? La oss se på selve utregningen i .NET


ChineseCalendarUtils.cs


/// <summary>
/// Provides methods to calculate the date of Chinese New Year.
/// </summary>
public class ChineseNewYearCalculator
{
    /// <summary>
    /// Gets the date of Chinese New Year for a given year.
    /// </summary>
    /// <param name="year">The Gregorian year.</param>
    /// <returns>The date of Chinese New Year as a <see cref="DateTime"/>.</returns>
    public static DateTime GetChineseNewYear(int year)
    {
        System.Globalization.ChineseLunisolarCalendar chinese = new ChineseLunisolarCalendar();
        DateTime chineseNewYear = chinese.ToDateTime(year, 1, 1, 0, 0, 0, 0);
        return chineseNewYear;
    }
}


Her bruker vi ChineseLunisolarCalendar og vi bruker metoden ToDateTime for 1. januar for spesifisert år. Dette gjør en transformasjon som gir oss kinesisk nyttår regnet ut i vår gregorianske kalender i Vesten.

Neste 10 år med Kinesisk nyttår

Year Date Animal
2025 January 29 Snake
2026 February 17 Horse
2027 February 6 Goat
2028 January 26 Monkey
2029 February 13 Rooster
2030 February 3 Dog
2031 January 23 Pig
2032 February 11 Rat
2033 January 31 Ox
2034 February 19 Tiger


Kinesisk tolvårssyklus

Den kinesiske tolvårssyklusen stammer fra en myte (det er ikke stedfestet hvor eller når denne kongen levde, i og med at det er en myte, men det stemmer fra veldig gammelt av Kina), hvor Jadekongen Yù Huáng Dà Dì
(玉皇大帝) inviterte alle dyr i kongeriket til et løp som gikk på tvers av en elv. De 12 første dyrene som krysset elven, skulle få et år kalt opp etter dem i den kinesiske 12 års Zodiac syklusen. En utregning av Kinesisk år, altså det dyret som året er "tilegnet" blir da en enkel modulo 12 utregning, som vist under.

ChineseCalendarUtils.cs


string GetChineseZodiac(int year)
{
	string[] zodiacAnimals =
	{
		"Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake",
		"Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"
	};

	int index = (year - 4) % 12;
	return zodiacAnimals[index];
}





Jadekongen Yù Huáng Dà Dì (玉皇大帝) og hans Zodiac-hjul (DALL-e 3 generert kunst)

Saturday, 18 January 2025

Monitoring User Secrets inside Blazor

This article shows how you can add User Secrets for a Blazor app, or other related .NET client technology supporting them. User secrets are stored on the individual computer, so one do not have to expose them to others. They can still be shared between different people if they are told what the secrets are, but is practical in many cases where one for example do not want to expose the secrets such as a password, by checking it into
source code repositories. This is due to the fact as mentioned that the user secrets are as noted saved on the individual computer.

User secrets was added in .NET Core 1.0, already released in 2016. Not all developers are familiar with them. Inside Visual Studio 2022, you can right click on the Project of a solution and choose Manage User Secrets. When you choose that option, a file called secrets.json is opened. The file location for this file is shown if you hover over the file. The file location is saved here:

  
    %APPDATA%\Microsoft\UserSecrets\<user_secrets_id>\secrets.json
  
  
You can find the id here, the user_secrets_id, inside the project file (the .csproj file).
Example of such a setting below:
  
  <Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <UserSecretsId>339fab44-57cf-400c-89f9-46e037bb0392</UserSecretsId>
  </PropertyGroup>

</Project>

  

Let's first look at the way we can set up user secrets inside a startup file for the application. Note the usage of reloadOnChange set to true. And adding the user secrets as a singleton service wrapped inside IOptionsMonitor.

Program.cs



builder.Configuration.Sources.Clear();
builder.Configuration
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true, reloadOnChange: true)
        .AddUserSecrets(Assembly.GetEntryAssembly()!, optional:false, reloadOnChange: true)
        .AddEnvironmentVariables();

builder.Services.Configure<ModelSecrets>(builder.Configuration.GetSection("ModelSecrets"));
builder.Services.AddSingleton<IOptionsMonitor<ModelSecrets>>, OptionsMonitor<ModelSecrets>>();



The Model secrets class looks like the following.



namespace StoringSecrets
{
    public class ModelSecrets
    {
        public string ApiKey { get; set; } = string.Empty;
    }
}


Home.razor.cs

Let's then look how we can fetch values from the user secrets. The code file for a file Home.razor is put in a file of its own, Home.razor.cs


using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Options;

namespace ToreAurstadIt.StoringSecrets.Components.Pages
{
    public partial class Home
    {
        [Inject]
        public required IOptionsMonitor<ModelSecrets> ModelSecretsMonitor { get; set; }

        public ModelSecrets? ModelSecrets  { get; set; }

        protected override async Task OnInitializedAsync()
        {
            ModelSecrets = ModelSecretsMonitor.CurrentValue;
            ModelSecretsMonitor.OnChange(updatedSecrets =>
            {
                ModelSecrets = updatedSecrets;
                InvokeAsync(StateHasChanged);

            });
            await Task.CompletedTask;
        }
    }
}

Note that IOptionsMonitor<ModelSecrets> is injected here and that in the OnInitializedAsync method, the injected value uses the OnChange method and and action callback then sets the value of the ModelSecrets and calls InvokeAsync method with StateHasChanged. We output the CurrentValue into the razor view of the Blazor app.

Home.razor



@page "/"

<PageTitle>Home</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

Your user secret is: 
<div>
    @ModelSecrets?.ApiKey
</div>


The secret.json file looks like this:

secrets.json



{
  "ModelSecrets": {
    "ApiKey": "SAMPLE_VALUE_UPDATE_9"
  }
}


A small app shows how this can be done, by changing the user secrets file and then reloading the page, changes should be immediately seen: