Presenting Byte Size Values in WPF

WPF Comments

Though it's not my main job, I still enjoy writing WPF application. Small tools, making my colleagues' and my own life easier.

Recently I had the requirement to display size values in bytes, kilobytes, etc in a well-rounded way. You will find many examples for formatting such values in the internet. Most look like this:

string result;
if (number >= 1024 * 1024 * 1024) {
    result = (number / 1024.0 / 1024 / 1024).ToString("F1") + " GB";
} else if (number >= 1024 * 1024) {
    result = (number / 1024.0 / 1024).ToString("F1") + " MB";
} else if (number >= 1024) {
    result = (number / 1024.0).ToString("F1") + " KB";
} else {
    result = number + " Bytes";
}

or, in a smarter way

string[] sizes = { "B", "KB", "MB", "GB", "TB" };
double len = number;
int order = 0;
while (len >= 1024 && order < sizes.Length - 1) {
    order++;
    len = len / 1024;
}
string result = $"{len:0.##} {sizes[order]}";

However, if you're on the Windows platform, there's a much easier option: StrFormatByteSize. That's the same method that Explorer is using to display file sizes. Its advantages are that you don't have any localization issues, and it it has a fixed precision of 3 digits.

Because my application is using WPF, I wrote a IValueConverter to be used in bindings:

Formatting binded values in XAML becomes quite easy with that converter (see full XAML):

<DataGrid
  AutoGenerateColumns="False"
  IsReadOnly="True"
  ItemsSource="{StaticResource numbers}">
  <DataGrid.Resources>
    <!--  the actual converter  -->
    <local:FormatKbSizeConverter x:Key="FormatKbSizeConverter" />
  </DataGrid.Resources>
  <DataGrid.Columns>
    <!--  First column shows the plain values  -->
    <DataGridTextColumn
      Binding="{Binding}"
      ElementStyle="{StaticResource RightCell}"
      Header="Plain" />
    <!--  Second column shows the formatted values  -->
    <DataGridTextColumn
      Binding="{Binding Converter={StaticResource FormatKbSizeConverter}}"
      ElementStyle="{StaticResource RightCell}"
      Header="Formatted" />
  </DataGrid.Columns>
</DataGrid>

FormatKbSizeConverter

Pretzel Plugin: Redirect

Pretzel Comments

A while back I wrote about the migration of my blog from Community Server over Jekyll to Pretzel.

One golden rule when restructuring a web site is to avoid dead links. The original web engine was a classic ASP.NET application, where every URL ends in .aspx (at least if you don't configure extensionless URLs). Tens years ago every URLs ended in an extension like .html, .php, whatever. Now-a-days, you barely see any file extensions anymore. The web servers don't expose the underlying technology, and the user just doesn't care. And so does Pretzel.

To use a new URL schema, but preserve the old links and redirect them to the new schema, I wrote an plugin for Pretzel, Pretzel.RedirectFrom. I've used the jekyll-redirect-from plugin as a guide, so the syntax is the same. Just add alternative URLs in the page's YAML front-matter:

---
title: "My First Post"
redirect_from:
  - /pages/page1
---

This will generate a small html page at \pages\page1\index.html, which will redirect to the new location:

<!DOCTYPE html>
<meta charset="utf-8" />
<title>Redirecting...</title>
<link rel="canonical" href="/2016/10/31/myfirstpost.html" />
<meta http-equiv="refresh" content="0; url=/2016/10/31/myfirstpost.html" />
<h1>Redirecting...</h1>
<a href="/2016/10/31/myfirstpost.html">Click here if you are not redirected.</a>
<script>
    location="/2016/10/31/myfirstpost.html"
</script>

Pretzel is a static file generator, so the redirection must be performed at the client-side.

However, I prefer a "real" redirect, i.e. a response with the correct HTTP status 301 Moved Permanently. Therefore I've implemented an additional switch. If you're using IIS (or Azure, or any other web server supporting ASP.NET), you can specify the switch redirect_generate_aspx: true in Pretzel's _config.yml. In this case the generated page will look like this:

<%@ Page Language="C#"%>
<script runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
    Response.StatusCode = 301;
    Response.Status = "301 Moved Permanently";
    Response.AddHeader("Location","/2016/10/31/myfirstpost.html");
    Response.End();
}
</script>

This ensures that the server returns the correct HTTP status.

Anyway, this plugin is a simple ScriptCs file, so you only have to copy Pretzel.RedirectFrom.csx to the _plugin folder of your Pretzel site, and you will be ready to use redirects.

Pretzel Plugin: Sitemap

Pretzel Comments

A couple of month ago I wrote that I switched to Pretzel to drive my site.

What I really like about Pretzel (except that it's written in .NET) is that it is so easy to extend. You can write plugins either as a .NET assembly, or—even simpler—throw in an .csx file, because Pretzel supports ScriptCs.

One of the first extensions I wrote was a site map plugin. By default Pretzel already creates a site map, but only for static pages. Unfortunately, this doesn't include paginated pages like the home page. Those pages are generated dynamically at runtime of Pretzel, and the default sitemap.xml doesn't take those dynamic pages into account.

Therefore I wrote this plugin which creates the sitemap.xml including all generated pages, even the paginated ones. It uses the same technique as JekyllEngineBase.ProcessFile: for each post and page it adds an url entry to the sitemap. Additionally it checks the page's front-matter if paginate is specified, and adds relevant URLs to the sitemap too.

The plugin is hosted on Github including some basic tests, but in fact you only have to copy Pretzel.Sitemap.csx to the _plugin folder of your Pretzel site.

Naming Events in .NET

.NET Comments

Update 2016/12/29: I've complained about the On prefix in the comment section of the documentation (and Jonas Gauffin too). In fact the prefix was a mistake and is fixed by now.


Things are changing in the .NET world. A couple of days ago Microsoft released .NET Core 1.0, the new cross-platform, open source, and modular .NET platform.

Unfortunately, not only the managed framework's changing, but naming guidelines too.

Lets start with the old .NET framework. Microsoft says in the Naming Guideline for Events:

✓ DO name events with a verb or a verb phrase.

Examples include Clicked, Painting, DroppedDown, and so on.

✓ DO give events names with a concept of before and after, using the present and past tenses.

For example, a close event that is raised before a window is closed would be called Closing, and one that is raised after the window is closed would be called Closed.

The (slightly outdated) Event Naming Guidelines for .NET Framework 1.1 even says more explicitly:

  • Do not use a prefix or suffix on the event declaration on the type. For example, use Close instead of OnClose.

That's what we've been taught for the last 15 years: Events are named without a prefix.

Let's repeat: Events are named without a prefix.

Entry .NET Core!

Robin Müller, maintainer of the telegram.bot library, changed the names of all event from an unprefixed name to prefixed with On in a recent commit. I complained that this renaming would contradict the guidelines recommendations by Microsoft and what we've learnt the last 15 years.

However, Robin pointed me to the new guidelines (emphasis mine):

There are a number of conventions that you should follow when declaring an event. Typically, the event delegate type has a void return. Prefix event declarations with 'On'. The remainder of the name is a verb.

WTF? Do we have to forget the old habits and rename all events when moving from good ol' .NET Framework to .NET Core?

The new guidelines include a comment section at the bottom where I asked for the rational behind the changed guideline a few days ago, but I still got no answer. I'd really like to now...

Sidenote: Most of us are used to name the handler for an event On<name of the event>, e.g.

foo.SomethingHappened += OnSomethingHappened;

What should we call those event handlers now? OnOnSomethingHappened?

From Jekyll To Pretzel

Jekyll, Pretzel Comments

Some time ago I told that I converted my blog from CommunityServer to Jekyll on Github Pages. However, I was not satisfied with that solution. Running a static site has one drawback: redirects for moved pages.

When you change the structure of a web site, you don't want old links to reference now invalid URLs. That's would be called link rot. Instead, you want that users following a link to an old location are redirected to the new page automatically.

Actually, there are plugins for Jekyll for redirection, the most popular is jekyll-redirect-from. However, what it does is creating an HTML page at the old location with a HTTP-REFRESH meta tag pointing to the new URL.

I don't like this solution because the status code of the HTTP response is 200, indicating that the old URL is still valid. I guess that Google or other search engines pay attention to the HTTP-REFRESH meta tag, but nevertheless it's a bad idea for SEO reasons.

Instead, a correct implementation would return the status code 302, indicating that the page moved permanently. Unfortunately that's not possible generally for static web sites.

That was the main reason I ditched Github Pages. I didn't want to go back to self-hosting on a virtual server, so I decided to move my site to Azure. Additionally I took the chance and replaced the blog engine too.

Not being a Ruby guy, I searched for a similar blog system but written in .NET. There are a few, but the most appearing to me was the Pretzel. Pretzel is an open source blog system, behaving more or less the same as Jekyll. Additionally it supports several extension points, which I as a developer really like.

I'll write about running Pretzel on Azure and different Pretzel extensions I wrote in some future posts.

TL;DR: I wanted to have more control over my website, therefore I moved from Github Pages to Azure, and from Jekyll to Pretzel.