Many project websites and readmes have status badges that display build status, project details, or code metrics. badgen.net and shields.io are popular services for dynamically generating status badges as SVG files using HTTP requests. This article demonstrates how I use C# and Microsoft.Maui.Graphics to build status badges from NDepend static analysis reports. Source code for this project is available on GitHub.
NDepend can analyze a code base at different points in time and display code metric trends. See NDepend: Trend Monitoring for a full description. These metrics are stored in an XML file available in the HTML build folder.
The XML file contains many Root/MetricIndex/Metric elements that describe each metric and its units. This can be parsed to obtain the Name and Unit for each metric.
<Root><MetricIndex><MetricName="# New Issues since Baseline"Unit="issues"/><MetricName="# Issues Fixed since Baseline"Unit="issues"/><MetricName="# Issues Worsened since Baseline"Unit="issues"/><MetricName="# Issues with severity Blocker"Unit="issues"/><MetricName="# Issues with severity Critical"Unit="issues"/><MetricName="# Issues with severity High"Unit="issues"/><MetricName="# Issues with severity Medium"Unit="issues"/> ...
</MetricIndex></Root>
The XML file contains multiple Root/M/R elements that contain the value of each metric at a distinct time point. Numerical metrics have been converted to strings separated by the | character. Metric values for each time point are in the same order as the metric index.
I’ve already written how to make status badges with C# and Maui.Graphics, but that strategy only generates PNG files. For this project I also chose to generate SVG files. Rather than discuss that in detail, I’ll just show to the source code for an example SVG file.
It is important to note that in order to know the image width I must measure the string width. In HTML environments this could be done with vanilla Javascript, but in a C# environment I reached for Microsoft.Maui.Graphics (see how to MeasureString() with Maui.Graphics).
<svgxmlns='http://www.w3.org/2000/svg'xmlns:xlink='http://www.w3.org/1999/xlink'width='237'height='20'role='img'aria-label='languages: 5'><title>Average # Lines of Code for Types: 25.96</title><linearGradientid='s'x2='0'y2='100%'><!-- linear gradient to use for the background shadow --><stopoffset='0'stop-color='#bbb'stop-opacity='.1'/><stopoffset='1'stop-opacity='.1'/></linearGradient><clipPathid='r'><!-- clip to a rectangle with rounded edges --><rectwidth='237'height='20'rx='3'fill='#fff'/></clipPath><gclip-path='url(#r)'><!-- left background --><rectwidth='195'height='20'fill='#555'/><!-- right background --><rectx='195'width='42'height='20'fill='#007ec6'/><!-- background shadow --><rectwidth='237'height='20'fill='url(#s)'/></g><gfill='#FFF'text-anchor='center'font-family='Verdana,Geneva,DejaVu Sans,sans-serif'text-rendering='geometricPrecision'font-size='110'><!-- left text semitransparent shadow then white text --><textaria-hidden='true'x='40'y='150'fill='#010101'fill-opacity='.3'transform='scale(.1)'textLength='1854'>Average # Lines of Code for Types</text><textx='40'y='140'transform='scale(.1)'fill='#FFF'textLength='1854'>Average # Lines of Code for Types</text><!-- right text semitransparent shadow then white text --><textaria-hidden='true'x='1994'y='150'fill='#010101'fill-opacity='.3'transform='scale(.1)'textLength='300'>25.96</text><textx='1994'y='140'transform='scale(.1)'fill='#FFF'textLength='300'>25.96</text></g></svg>
One day Maui.Graphics may offer SVG export support (issue #103) but for now generating these files discretely isn’t too bad.
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
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.
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.
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.
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.
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!
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.
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!
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))
continue;
string d = tag.Description.Split(" ")[0].Replace(":", "-");
string t = tag.Description.Split(" ")[1];
return DateTime.Parse($"{d} {t}");
}
}
}
thrownew InvalidOperationException($"Date not found in {filePath}");
}