The personal website of Scott W Harden

Status Badges with Maui.Graphics

How to use Microsoft.Maui.Graphics to render status badges

Status badges are popular decorators on GitHub readme pages and project websites. Badgen.net and shields.io are popular HTTP APIs for dynamically generating SVG status badges. In this article we will use the new Microsoft.Maui.Graphics package to generate status badges from a C# console application. This application can be downloaded: BadgeApp.zip


The Badge class contains all the logic needed to render and save a badge as a PNG file.

This code demonstrates a few advanced topics which are worth considering:

using Microsoft.Maui.Graphics;
using Microsoft.Maui.Graphics.Skia;

public class Badge
    readonly string Name;
    readonly string Value;
    readonly SizeF NameSize;
    readonly SizeF ValueSize;

    // Customize these to change the style of the button
    public Color BackgroundLeft = Color.FromArgb("#666");
    public Color BackgroundRight = Color.FromArgb("#08C");
    public Color BackgroundLiner = Colors.White.WithAlpha(.15f);
    public Color FontColor = Colors.White;
    public Color FontShadow = Colors.Black.WithAlpha(.5f);
    public Color OverlayTop = Colors.Black.WithAlpha(0);
    public Color OverlayBottom = Colors.Black.WithAlpha(.25f);

    public Badge(string name, string value)
        Name = name;
        Value = value;
        NameSize = MeasureString(name);
        ValueSize = MeasureString(value);

    public void SavePng(string pngFilePath, float scale = 1)
        float totalWidth = NameSize.Width + ValueSize.Width;
        int imageWidth = (int)totalWidth + 22;
        RectangleF imageRect = new(0, 0, imageWidth, 20);

        int scaledWidth = (int)(imageRect.Width * scale);
        int scaledHeight = (int)(imageRect.Height * scale);
        BitmapExportContext bmp = SkiaGraphicsService.Instance.CreateBitmapExportContext(scaledWidth, scaledHeight);
        ICanvas canvas = bmp.Canvas;
        canvas.Scale(scale, scale);

        // left background
        canvas.FillColor = BackgroundLeft;
        canvas.FillRoundedRectangle(imageRect, 5);

        // right background
        float bg2x = 10 + NameSize.Width;
        canvas.ClipRectangle(bg2x, 0, bmp.Width, bmp.Height);
        canvas.FillColor = BackgroundRight;
        canvas.FillRoundedRectangle(imageRect, 5);

        // vertical line
        canvas.StrokeColor = BackgroundLiner;
        canvas.DrawLine(bg2x, 0, bg2x, bmp.Height);

        // background overlay shadow
        var pt = new LinearGradientPaint() { StartColor = OverlayTop, EndColor = OverlayBottom };
        canvas.SetFillPaint(pt, new Point(0, 0), new Point(0, bmp.Height));
        canvas.FillRoundedRectangle(imageRect, 5);

        // draw text backgrounds
        canvas.FontSize = 12;
        float offsetY = 14;
        float offsetX1 = 5;
        float offsetX2 = 15;
        float shadowOffset = 1;

        // text shadow
        canvas.FontColor = FontShadow;
        canvas.DrawString(Name, offsetX1 + shadowOffset, offsetY + shadowOffset, HorizontalAlignment.Left);
        canvas.DrawString(Value, offsetX2 + NameSize.Width + shadowOffset, offsetY + shadowOffset, HorizontalAlignment.Left);

        // text foreground
        canvas.FontColor = FontColor;
        canvas.DrawString(Name, offsetX1, offsetY, HorizontalAlignment.Left);
        canvas.DrawString(Value, offsetX2 + NameSize.Width, offsetY, HorizontalAlignment.Left);

        // save the output

    SizeF MeasureString(string text, string fontName = "Arial", float fontSize = 12)
        var fontService = new SkiaFontService("", "");
        using SkiaSharp.SKTypeface typeFace = fontService.GetTypeface(fontName);
        using SkiaSharp.SKPaint paint = new() { Typeface = typeFace, TextSize = fontSize };
        float width = paint.MeasureText(text);
        float height = fontSize;
        return new SizeF(width, height);


This simple program is all it takes to render and save a badge.

Badge myBadge = new("Maui", "Graphics");


You can reach into the Badge class and customize styles as desired.

Badge myBadge = new("Maui", "Graphics")
    BackgroundRight = Microsoft.Maui.Graphics.Color.FromArgb("#3cc51d"),

Image Scaling

Microsoft.Maui.Graphics natively supports image scaling. This allows you to create large badges without any loss in quality that would come from creating a small badge and resizing the bitmap.

Badge myBadge = new("Maui", "Graphics");
myBadge.SavePng("demo1.png", scale: 1);
myBadge.SavePng("demo2.png", scale: 2);
myBadge.SavePng("demo5.png", scale: 5);


MeasureString() with Maui.Graphics

How to measure the pixel dimensions of a string using Microsoft.Maui.Graphics

Starting with .NET 6 Microsoft is sunsetting cross-platform support for System.Drawing.Common. Microsoft.Maui.Graphics is emerging as an excellent replacement and it can be used in any app (not just MAUI apps).

Code here demonstrates how I measure the pixel size of a string using Maui.Graphics in a console application.

/* Updated on 2022-02-19 */
using Microsoft.Maui.Graphics; // 6.0.200-preview.13.935
using Microsoft.Maui.Graphics.Skia; // 6.0.200-preview.13.935

// setup a canvas with a blue background
using BitmapExportContext bmp = new SkiaBitmapExportContext(450, 150, 1.0f);
ICanvas canvas = bmp.Canvas;
canvas.FillColor = Colors.Navy;
canvas.FillRectangle(0, 0, bmp.Width, bmp.Height);

// define and measure a string
PointF stringLocation = new(50, 50);
string stringText = "Hello, Maui.Graphics!";
Font font = new();
float fontSize = 32;
SizeF stringSize = canvas.GetStringSize(stringText, font, fontSize);
Rectangle stringRect = new(stringLocation, stringSize);

// draw the string and its outline
canvas.StrokeColor = Colors.White;
canvas.FontColor = Colors.Yellow;
canvas.Font = font;
canvas.FontSize = fontSize - 1; // NOTE: reduce to prevent clipping
    value: stringText,
    x: stringLocation.X,
    y: stringLocation.Y,
    width: stringSize.Width,
    height: stringSize.Height,
    horizontalAlignment: HorizontalAlignment.Left,
    verticalAlignment: VerticalAlignment.Top,
    textFlow: TextFlow.OverflowBounds,
    lineSpacingAdjustment: 0);

// save the result
string filePath = Path.GetFullPath("Issue279.png");
using FileStream fs = new(filePath, FileMode.Create);

Note that in this example GetStringSize() respects font but DrawString() does not.


My Life with a Spiny Leaf Insect

Photographs of the life cycle of a spiny leaf insect raised as a pet

I spent 2016 new years eve celebrating the occasion with a few entomologists. Shortly after watching the ball drop in New York we changed the TV back to David Attenborough’s Life of Insects, and I was amazed at what I saw! There was a short segment on leaf insects and I was impressed by the camouflage of these small creatures. I wanted to see more so I google image-searched and clicked on the websites that came up. One of the websites was an ebay listing for ten leaf insect eggs (for about $10 USD) and I couldn’t avoid that “BUY IT NOW” button. I remember pointing to the TV and announcing to the room, “Aren’t those things cool? I just bought ten.”

WARNING: This listing may have been illegal. Leaf insects are invasive in some parts of the world, and transferring non-native species between countries can be dangerous to the local ecosystem and is often prohibited by law.

It turns out what I purchased was a spiny leaf insect (Extatosoma tiaratum) endemic to Australia. These insects are sexually dimorphic, with males being thinner and capable of flight. Females have false wings but grow larger and can live longer. These insects eat plants and are capable of asexual reproduction (parthenogenesis).


Two weeks later I received an envelope in my mailbox. I opened it and it had a milk cap in it with 10 little egs inside, wrapped in clear tape. I was surprised at the packaging, but unpacked the eggs according to the directions. I put them in a ventilated container on a moist paper towel.

Four months later one of the eggs hatched! I almost gave up on the eggs because nothing happened for so long. I noticed it within several hours of emerging, but one of its legs was dried to the egg shell.

I transferred the insect to an enclosure and gave it access to dry and wet spaces. After a day the egg was still attached to the leg so I gave it a gentle pull and it fell off (the egg, not the leg).


I added some oak branches to the insect’s enclosure and this turned out to be a great choice. Over the next few months the only native plants this leaf insect would eat were oak leaves. I tried every type of plant I found find around my North Florida apartment, but this thing only had a taste for oak. Luckily that plant is everywhere around here, so I had no trouble supplying food throughout its life.


The leaf insect didn’t grow gradually, but instead drastically changed its shape and size abruptly after molting every few weeks. I never observed it molting, so I assume it typically molted at night. After its first molt its legs were shaped much more like leaves, its back was wider and thicker, and its head and tail demonstrated little spines. These photos are of the insect 2-3 months after hatching.


After a few weeks the leaf insect began to outgrow her enclosure so repurposed a 20-gallon aquarium by adding mulch at the bottom (coconut fiber substrate from the pet store) and filling it with oak branches.

The insect loved her new home, but her camouflage was pretty good so it often took a couple minutes of searching to find her in there…

I misted the tank with a spray bottle once a day. Often I’d see the insect drinking the water that beaded on the leaves. Misting would often trigger feeding shortly after.


After 3 months the leaf insect grew considerably! The spikes along her body were more prominent than ever, and facilicated excellent camoflague when walking along branches.

Final Form

These photos were taken after the insect molted for the last time. She’s huge! Her tail has a little hook near the end which I later learned was used to hold onto eggs as they’re deposited.

Egg Laying

I was watching TV one night and I kept hearing these “pinging” sounds. Eventually I figured-out it was coming from the leaf insect, who was laying eggs and flinging them across the tank. They’d hit the glass, bounce off, and land in the mulch. The camouflage of the eggs was spectacular, and aside from spotting an egg here and there I had no idea how many she was actually laying. The leaf insect was 6 months old by now.

Last Photos

The leaf insect lived a little over seven months and these are the last photos I have of her. From what I read females can live for about a year and a half, so suspect mine was not well as she got older. She started to move sluggishly, and one day she was on the bottom of the tank (uncharacteristic behavior previously) and upon closer inspection I realized she wasn’t moving. She had a good life, and I enjoyed sharing my home with this amazing insect for the last several months!

Egg Collection

After the insect died I removed all the branches sifted the substrate to isolate and save the eggs. After removing the branches I was surprised by how much frass the insect left behind! I dumped the substrate on wax paper and sorted it piece by piece. I collected 166 eggs! I read that leaf insects may lay over a thousand eggs over the lifespan. They are designed to resemble seeds and they have a little tasty nub on them that encourages ants to cary them to their nest.

Leaf insects are parthenogenic and are capable of laying fertile eggs without a male (although their offspring will all be female). I tried to incubate these eggs on a moist paper towel like the original eggs I got. I maintained these eggs for about a year, but none ever hatched. Later I read that spiny leaf insects may remain dormant for several years before hatching.

Final Thoughts

Raising this leaf insect was a fantastic experience! I may try it again some day. After this one finished her life cycle I turned its tank into an aquarium used for rearing baby freshwater angelfish. Maybe some day in the future I’ll try to raise leaf insects again!


Rename Image Files by Capture Date with C#

How to rename a folder of JPEGs by the creation date stored in their metadata

I have hundreds of folders containing thousands of photographs I wish to move to a single directory. Images are all JPEG format, but unfortunately they have filenames like DSC_0123.JPG. This means there are many identical filenames (e.g., every folder has a DSC_0001.JPG) and also the sorted list of filenames would not be in chronological order.

JPEG files have an Exif header and most cameras store the acquisition date of photographs as metadata. I wrote a C# application to scan a folder of images and rename them all by the date and time in their header. This problem has been solved many ways (googling reveals many solutions), but I thought I’d see what it looks like to solve this problem with C#. I reached for the MetadataExtractor package on NuGet. My solution isn’t fancy but it gets the job done.

foreach (string sourceImage in System.IO.Directory.GetFiles("../sourceFolder", "*.jpg"))
    DateTime dt = GetJpegDate(sourceImage);
    string fileName = $"{dt:yyyy-MM-dd HH.mm.ss}.jpg";
    string filePath = Path.Combine("../outputFolder", fileName);
    System.IO.File.Copy(sourceImage, filePath, true);
    Console.WriteLine($"{sourceImage} -> {filePath}");

DateTime GetJpegDate(string filePath)
    var directories = MetadataExtractor.ImageMetadataReader.ReadMetadata(filePath);

    foreach (var directory in directories)
        foreach (var tag in directory.Tags)
            if (tag.Name == "Date/Time Original")
                if (string.IsNullOrEmpty(tag.Description))
                string d = tag.Description.Split(" ")[0].Replace(":", "-");
                string t = tag.Description.Split(" ")[1];
                return DateTime.Parse($"{d} {t}");

    throw new InvalidOperationException($"Date not found in {filePath}");
> dotnet run
DSC_0121.JPG -> 2016-09-30 21.51.25.jpg
DSC_0122.JPG -> 2016-10-03 21.42.05.jpg
DSC_0123.JPG -> 2016-10-09 23.04.05.jpg
DSC_0124.JPG -> 2016-10-09 23.05.48.jpg
DSC_0125.JPG -> 2016-11-30 23.07.56.jpg
DSC_0126.JPG -> 2017-01-01 19.16.56.jpg
DSC_0127.JPG -> 2017-01-01 19.17.09.jpg


Managing Secrets in .NET Console Apps

How to use dotnet user-secrets to store and retrieve secrets and set environment variables in .NET applications.

Sometimes your code needs to work with secrets that you don’t want to risk accidentally leaking on the internet. There are many strategies for solving this problem, and here I share my preferred approach. I see a lot of articles about how to manage user secrets in ASP.NET and other web applications, but not many focusing on console or desktop applications.

User Secrets in C# Applications

1. Create a New .NET App

dotnet new console

2. Set the Secrets ID




3. Add Secrets Locally

dotnet user-secrets set username me@example.com
dotnet user-secrets set password mySecretPass123

4. Install the UserSecrets Package

dotnet add package Microsoft.Extensions.Configuration.UserSecrets

💡 CAREFUL: If you accidentally install Microsoft.Extensions.Configuration instead of Microsoft.Extensions.Configuration.UserSecrets you won’t have access to AddUserSecrets()

5. Access Secrets in Code

using Microsoft.Extensions.Configuration;
var config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
string username = config["username"];
string password = config["password"];

NOTE: If a key does not exist its value will be null

Environment Variables

Cloud platforms (GitHub Actions, Azure, etc.) often use environment variables to manage secrets. Using local user secrets to populate environment variables is a useful way to locally develop applications that will run in the cloud.

This example shows how to populate environment variables from user secrets:

using Microsoft.Extensions.Configuration;

class Program
    static void Main()
        string username = Environment.GetEnvironmentVariable("username");
        string password = Environment.GetEnvironmentVariable("password");

    static void SetEnvironmentVariablesFromUserSecrets()
        var config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
        foreach (var child in config.GetChildren())
            Environment.SetEnvironmentVariable(child.Key, child.Value);

GitHub Actions

GitHub Actions makes it easy to load repository secrets into environment variables. See GitHub / Encrypted secrets for more information about how to add secrets to your repository.

This example snippet of a GitHub action loads two GitHub repository secrets (USERNAME and PASSWORD) as environment variables (username and password) that can be read by my unit tests using Environment.GetEnvironmentVariable() as shown above.

      - name: 🧪 Run Tests
          username: ${{ secrets.USERNAME }}
          password: ${{ secrets.PASSWORD }}
        run: dotnet test ./src


Using these strategies I am able to write code that seamlessly accesses secrets locally on my dev machine and from environment variables when running in the cloud. Since this strategy does not store secrets inside my project folder, the chance of accidentally committing a .env or other secrets file to source control approaches zero.