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}");
}
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.
Secrets are stored as plain-text key/value pairs in JSON format in %AppData%\Microsoft\UserSecrets
This isn’t totally secure, but may be an improvement over .env and .json files stored inside your project folder which can accidentally get committed to source control if your .gitignore file isn’t meticulously managed
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:
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.
steps:...- name:🧪 Run Testsenv: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.
.NET MAUI (Multi-Platform Application User Interface) is a new framework for creating cross-platform apps using C#. MAUI will be released as part of .NET 6 in November 2021 and it is expected to come with Maui.Graphics, a cross-platform drawing library superior to System.Drawing in many ways. Although System.Drawing.Common currently supports rendering in Linux and MacOS, cross-platform support for System.Drawing will sunset over the next few releases and begin throwing a PlatformNotSupportedException in .NET 6.
By creating a graphics model using only Maui.Graphics dependencies, users can share drawing code across multiple rendering technologies (GDI, Skia, SharpDX, etc.), operating systems (Windows, Linux, MacOS, etc.), and application frameworks (WinForms, WPF, Maui, WinUI, etc.). This page demonstrates how to create a platform-agnostic graphics model and render it using Windows Forms and WPF. Resources in the Maui.Graphics namespace can be used by any modern .NET application (not just Maui apps).
⚠️ WARNING:Maui.Graphics is still a pre-release experimental library (as noted on their GitHub page). Although the code examples on this page work presently, the API may change between now and the official release.
For this example I will start by creating a a .NET 5.0 WinForms project from scratch. Later we will extend the solution to include a WPF project that uses the same graphics model.
We need to get the windows forms MAUI control and all its dependencies. At the time of writing (September, 2021) these packages are not yet available on NuGet, but they can be downloaded from the Microsoft.Maui.Graphics GitHub page.
💡 Tip: If you’re developing a desktop application you can improve the “rebuild all” time by editing the csproj files of your dependencies so TargetFrameworks only includes .NET Standard targets.
Add the Microsoft.Maui.Graphics project to your solution and add a reference to it from your project.
Windows Forms: Add the Microsoft.Maui.Graphics.GDI.Winforms project to your solution and add a reference to it in your WinForms project. A GDIGraphicsView control should appear in the toolbox.
WPF: Add the Microsoft.Maui.Graphics.Skia.WPF project to your solution and add a reference to it in your WPF project. A WDSkiaGraphicsView control should appear in the toolbox.
A drawable is a class that implements IDrawable, has a Draw() method, and can be rendered anywhere Maui.Graphics is supported. By only depending on Maui.Graphics it’s easy to create a graphics model that can be used on any operating system using any supported graphical framework.
usingMicrosoft.Maui.Graphics;
This drawable fills the image blue and renders 1,000 randomly-placed anti-aliased semi-transparent white lines on it. Note that the location of the lines depends on the size of the render field (passed-in as an argument).
Windows Forms applications may also want to intercept SizeChanged events to force redraws as the window is resized.
publicpartialclassForm1 : Form
{
public Form1()
{
InitializeComponent();
gdiGraphicsView1.Drawable = new RandomLines();
}
privatevoid GdiGraphicsView1_SizeChanged(object? sender, EventArgs e) =>
gdiGraphicsView1.Invalidate();
privatevoid timer1_Tick(object sender, EventArgs e) =>
gdiGraphicsView1.Invalidate();
}
I found performance to be quite adequate. On my system 1,000 lines rendered on an 800x600 window at ~60 fps. Like System.Drawing this system slows down as a function of image size, so full-screen 1920x1080 animation was much slower (~10 fps).
Since our project is configured to display the same graphics model with both WinForms and WPF, it’s easy to edit the model in one place and it’s updated everywhere. We can replace the random lines model with one that manages randomly colored and sized balls that bounce off the edges of the window as the model advances.
To build this project from source code you currently have to download Maui.Graphics source from GitHub and edit the solution file to point to the correct directory containing these projects. This will get a lot easier after Microsoft puts their WinForms and WPF controls on NuGet.
Can you recreate this classic screensaver using Maui.Graphics? Bonus points if the user can customize the number of shapes, the number of corners each shape has, and the number of lines drawn in each shape’s history. It’s a fun problem and I encourage you to give it a go! Here’s how I did it: mystify-maui.zip