First Anniversary

A year has passed since Gigi Labs was launched as a successor to Programmer’s Ranch, my previous blog based on the Blogger platform which featured exclusively technical articles.

Gigi Labs is instead based on the more mature WordPress platform, and this has made it a whole lot easier to write technical articles and include code samples. In fact, a total of 85 articles have been published at Gigi Labs to date (compared to 91 in the 18 months of operation of Programmer’s Ranch).

The vast majority of articles here have been on Software Development. Some topics of note include C# 6 and Visual Studio 2015 (articles written while these were still in development and little information was available), Redis (articles featured in leading Redis newsletters), SignalR and RabbitMQ. Many other articles deal with a range of interesting and obscure topics.

Recently, I began migrating some of the more popular articles from Programmer’s Ranch to Gigi Labs. This is expected to continue, especially for the SDL2 articles which were among the first of their kind and were quite a hit around the time SDL2 became available.

Aside from technical articles, Gigi Labs has also seen posts published on a range of topics varying from guitar tabs to observations about life. The fact that WordPress allows neat categorization of articles is another of its strong points.

Finally, while many articles have been published at Gigi Labs, a number of static pages have also emerged since its launch: Projects, Websites, Writings and Public Talks show what I’ve been up to.  There are a few other pages with miscellaneous information that doesn’t really fit anywhere else.

I just wanted to thank all the people who have been following Gigi Labs over the past year, and hope they will continue doing that for years to come. You can get updates easily by subscribing via email, following me on Twitter, or liking the Gigi Labs Facebook page.

C#: Metronome with Timers and Beeps

This article was originally posted here at Programmer’s Ranch on 24th July 2014.

Hey people! 🙂

When you’re learning to play an instrument, one thing you need to make sure of is that you’re playing in sync with a regular beat. A device that helps you by producing such a regular beat is a metronome. In this article, we’re going to write a simple metronome application. In doing so, we’ll learn how to use the Console‘s beeping functionality, and we’ll learn to use timers to fire events at regular intervals.

So let’s begin by creating a new Console Application, and adding the following using statement near the top, which will give us access to some of the classes we need:

using System.Threading;

Now, making a quick and dirty metronome is very easy. This is all it takes:

            while (true)
            {
                Console.Beep(4000, 100);
                Thread.Sleep(1000);
            }

That Console.Beep() takes the frequency of the sound as the first parameter (in this case 4000Hz), and the duration of the beep as the second parameter (in this case 100 milliseconds). You can omit the arguments entirely to use default settings.

Thread.Sleep() is used to suspend the program for a specified duration (specified in milliseconds in the parameter). In this case we’re using it to cause a delay between beeps of 1000 milliseconds (i.e. 1 second).

Now, suspending the program like this is not a very good thing. In fact, we can’t give the user an option to quit, and if we were using a GUI (e.g. WPF), then this kind of blocking would be even more problematic.

A better approach for our metronome application is to use Timers. Now there are many different Timer classes we can use, but the one we need in this case is this one. So before we see how we can use these mystical creatures to create a more awesome metronome, let us first add another using statement:

using System.Timers;

Now let’s create an instance of our Timer class:

Timer timer = new Timer();

Now you’re going to see Visual Studio complain about this line:

csmetronome-ambiguity

As Visual Studio is telling you, there is also a Timer class in System.Threading, so C# doesn’t know which one to use. You can resolve the ambiguity by using the fully qualified names instead (or in this particular case, just remove System.Threading since we don’t need it any more):

System.Timers.Timer timer = new System.Timers.Timer();

Next, assign a new event handler to the Elapsed event:

timer.Elapsed += timer_Elapsed;

Visual Studio offers to create the event handler for you as you type:

csmetronome-event-completion

Take it up on the offer, and have the following code generated for you:

        static void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            throw new NotImplementedException();
        }

Replace the contents of this event handler with our beeping functionality:

        static void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            Console.Beep(4000, 100);
        }

Back in the Main() method, set an Interval for the timer:

timer.Interval += 1000;

You should begin to understand what we’re doing here. Every time the interval passes (i.e. every second in this case), the Elapsed event will fire, and do whatever we specify in the event handler.

Now all we need to do is start the timer. In the code below, I am also waiting for the user to press ENTER, and once this is done, I am stopping the timer and exiting the application:

            timer.Start();
            Console.ReadLine();
            timer.Stop();

Since the timer runs on a separate thread, it does not interfere with user input. So we can have the timer running in the background while the program waits for user input – similar to what we did last year in “C# Threading: Bouncing Ball” (except that all the threading stuff is handled for you).

So there’s your metronome! Full code below. 🙂

        static void Main(string[] args)
        {
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Elapsed += timer_Elapsed;
            timer.Interval += 1000;

            timer.Start();
            Console.ReadLine();
            timer.Stop();
        }

        static void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            Console.Beep(4000, 100);
        }

In this article, we created a very simple metronome application. We first used a sleep-based delay, and learned about the dangers of having it block the program, limiting its interactivity. We then used a Timer from the System.Timers namespace in order to trigger beeps at regular intervals.

There are many ways in which this can be improved (e.g. distinct beep every four beats, configurable beats per minute, etc), but this is a fully functional metronome and a pretty simple demonstration of how to use timers.

The beeping functionality can also come in handy in a wide range of scenarios. One example is to supplement last year’s article “C# Basics: Morse Code Converter Using Dictionaries” with actual sounds to represent the dots and dashes in Morse Code.

I hope you found this useful. Thanks for reading! 🙂

Displaying a Volume Meter using NAudio

Windows 7 has this volume meter in the system tray. I’m sure you’re pretty familiar with it.

windows-volume-meter

It’s pretty cool. If you’re playing music, the green bar dances up and down, reflecting the volume of the music being played at the time.

If you’re developing an application that includes some form of multimedia, such as the ability to play music or listen to recorded phone calls, something simple like this is a great way to provide feedback to the user, showing that something is actually playing.

Typically, doing anything with sound in Windows is a messy business, as you’d have to play around with some pretty low-level APIs.To get an idea, just take a look at how many different ways there are to get master sound volume in C#.

Fortunately, there’s a managed library called NAudio which takes away a lot of the pain of dealing with this stuff. And quite conveniently, it’s available as a NuGet package.

After installing NAudio via NuGet, you can get a reference to your default audio output device using the following code:

            var enumerator = new MMDeviceEnumerator();
            var device = enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Console);

Note that there are three different values for Role, but they don’t seem to make any difference.

Put a breakpoint at the end and hover over the device variable to see that it’s bound to your actual output audio device:

naudio-device

From this, we can get a value that indicates the audio volume:

            while (true)
            {
                Console.Write("\r{0}", device.AudioMeterInformation.MasterPeakValue);
            }

I’m using the old \r trick to overwrite the value displayed in the same line with each iteration. You’ll see that the volume displayed is a float value:

naudio-volume-float

That’s nice, but it’s a bit hard to visually interpret how it’s changing. Let’s build a simple volume meter in the console instead.

            while (true)
            {
                var volume = device.AudioMeterInformation.MasterPeakValue;
                var scale = (int)Math.Floor(volume * 79);

                Console.Write("\r");

                var sb = new StringBuilder();
                sb.Append('-', scale);
                sb.Append(' ', 79 - scale);
                Console.Write(sb.ToString());
            }

We can represent the volume meter as a series of dashes in a line in the command line. Since NAudio gives us a value between 0 and 1, we can scale that to something between 0 and 79 (since 80 characters fit in a line in the command line by default).

With that done, we can then:

  1. Print a \r character. This starts writing at the beginning of the line, essentially overwriting the previously drawn meter.
  2. Print a number of dashes proportional to the scaled volume we just calculated. Since we’re using StringBuilder’s repeat ability, we don’t need loops.
  3. Print spaces for the rest of the line. This clears any leftover dashes from the previously drawn meter.

And there, you have it:

naudio-console-volume-meter

This screenshot doesn’t really do it justice. Since the meter is updating pretty much in real time, go ahead and run this program when you have music playing to see how nicely it dances. 🙂

Calculating the Checksum of a FIX Message

The FIX (Financial Information Exchange) Protocol is an industry standard used by financial institutions to… guess what… exchange financial information.

A FIX message is simply a sequence of key-value pairs, each followed by a SOH (ASCII value 1) character. Since SOH is a non-printable character, FIX messages are often illustrated using another character, such as a pipe. The following is an example of a FIX message, taken from FIX Parser:

8=FIX.4.1|9=61|35=A|34=1|49=EXEC|52=20121105-23:24:06|56=BANZAI|98=0|108=30|10=003|

As you can see, key-value pairs are delimited by the pipe character (which would be a SOH character in a real FIX message). Note how there is also a pipe character at the very end. Keys are separated from values with an equals sign (=). The keys themselves are numbers; each number represents a particular field in the FIX protocol. For example, FIX Field 8 represents the FIX protocol as well as the beginning of a FIX message. The use of numbers instead of field names makes messages less readable, but keeps them small.

The last field in a FIX message is the checksum (FIX Field 10). The algorithm used to calculate the checksum is described here:

“The checksum of a FIX message is calculated by summing every byte of the message up to but not including the checksum field itself. This checksum is then transformed into a modulo 256 number for transmission and comparison. The checksum is calculated after all encryption is completed, i.e. the message as transmitted between parties is processed.

“For transmission, the checksum must be sent as printable characters, so the checksum is transformed into three ASCII digits.

“For example, if the checksum has been calculated to be 274 then the modulo 256 value is 18 (256 + 18 = 274). This value would be transmitted a |10=018| where “10=”is the tag for the checksum field.”

In C#, we can implement this as follows.

First, let’s create our test message. We start with a pipe-delimited representation (just because it’s more readable that way), without the checksum field, and then we swap out the pipes for SOH characters (\u0001). Since FIX uses an ASCII representation, we can easily get a byte representation of the message:

            string message = "8=FIX.4.1|9=61|35=A|34=1|49=EXEC|52=20121105-23:24:06|"
                + "56=BANZAI|98=0|108=30|";
            message = message.Replace('|', '\u0001');
            byte[] messageBytes = Encoding.ASCII.GetBytes(message);

The algorithm itself is then easy to implement. We simply iterate over each byte, add its value to a running total, divide it by 256, and take the remainder:

            for (int i = 0; i < message.Length; i++)
                total += messageBytes[i];

            int checksum = total % 256;

There’s nothing more to add – that’s the checksum. If you’re sending a FIX message, you’ll convert the value to a string and pad it with zeroes if necessary to make sure it’s exactly 3 characters:

            string checksumStr = checksum.ToString().PadLeft(3, '0');

If you’re parsing a received message, you’ll want to compare the checksum you calculated to the one provided with the message, to make sure the message isn’t corrupt.

Easy RabbitMQ Messaging with EasyNetQ

This article is about EasyNetQ, a library for using RabbitMQ with .NET. At the time of writing this article, EasyNetQ is still prerelease software. Despite that, several people have been using it in production environments for a while. If you use it in production, it’s at your own risk.

Last August I wrote “Getting Started with RabbitMQ with .NET“. This illustrated, among other things, how you can receive messages from a RabbitMQ queue using the official RabbitMQ .NET client library.

While that’s a perfectly fine thing to do, it’s often preferable to use a higher-level library that takes care of the little details and allows you to focus on the actual messaging in a structured way. Well, that’s why EasyNetQ exists. With EasyNetQ, you don’t have to worry about stuff like serialization, messaging patterns, connection reliability, etc. In the rest of this article, we’ll see how easy it is to send and receive messages with EasyNetQ.

The first thing we need to do, of course, is to install the EasyNetQ NuGet package:

easynetq-install-package

Then, let’s create a class that represents the messages we will be sending. In this example, we’ll pretend we’re sending the position of a player in a game:

    public class PlayerPosition
    {
        public int X { get; set; }
        public int Y { get; set; }
    }

Once we have that, we can subscribe to messages arriving in a queue. This is done like this:

            using (var bus = RabbitHutch.CreateBus("host=localhost"))
            {
                bus.Subscribe<PlayerPosition>("MyGame", playerPosition =>
                    Console.WriteLine($"{playerPosition.X}, {playerPosition.Y}"));

                Console.ReadLine();
            }

So you declare your queue using RabbitHutch.CreateBus(). Bus is just a queue. So what’s a RabbitHutch? Well, what can I say? It’s a rabbit cage.

Facepalmorangflipped

Note how we are subscribing specifically to receive a message of type PlayerPosition. We are using a subscriptionId of “MyGame”, and we are also passing in a handler that specifies what to do with the received message. If the syntax looks a little unfamiliar, that’s because I’m using string interpolation, a new C# language feature introduced in C# 6.0.

When we run this, we can see that a queue is created, with the name built from the message class name and the subscriptionId:

easynetq-newqueue

Now in order to understand what’s going through the queue, let’s stop the subscriber for the time being.

We can send a message on the queue as follows:

            using (var bus = RabbitHutch.CreateBus("host=localhost"))
            {
                var playerPosition = new PlayerPosition() { X = 1, Y = 2 };
                bus.Publish<PlayerPosition>(playerPosition);

                Console.ReadLine();
            }

Note how we’re sending a strongly typed object (as opposed to a loose string), which we supply as the generic parameter. You can of course leave out the generic parameter, but I am including it above for clarity.

We can now check out the message in the queue from the “Get messages” section in the RabbitMQ management web interface:

easynetq-message-example

As you can see, the data we sent is serialized into JSON, and it is also accompanied by type information that helps EasyNetQ to deserialize it at the receiving end.

In fact, we can now run our subscriber again, and see that it consumes the message:

easynetq-message-received

So you can see how EasyNetQ makes it really easy to focus on the messaging and leave the details to it. Naturally, there’s a lot more you can do with EasyNetQ than this introductory article illustrates. Check out the EasyNetQ documentation for more info.

Security Risk in Binding WPF PasswordBox Password

This article was originally posted here at Programmer’s Ranch with the title “C# WPF/MVVM: Why You Shouldn’t Bind PasswordBox Password”, on 4th October 2014.

Hi! 🙂

In WPF circles, the PasswordBox control has generated quite a bit of discussion. The thing is that you can access the password entered by the user using the Password property, but it’s not a dependency property, and MVVM purists don’t like the fact that they can’t bind it to their ViewModel.

In this article, I’m going to show how the password can be bound in the ViewModel despite this limitation. And I’m also going to show you why it’s a very bad idea to do this. This article is a little advanced in nature, and assumes you’re familiar with WPF and MVVM.

Right, so let’s set up something we can work with. Create a new WPF application, and then add a new class called MainWindowViewModel. In your MainWindow‘s codebehind (i.e. MainWindow.xaml.cs), set up your window’s DataContext by adding the following line at the end of your constructor:

            this.DataContext = new MainWindowViewModel();

Right, now let’s add a couple of properties to our MainWindowViewModel that we’ll want to bind to:

        public string Username { get; set; }
        public string Password { get; set; }

Now we can build our form by editing the XAML in MainWindow.xaml. Let’s go with this (just make sure the namespace matches what you have):

<Window x:Class="CsWpfMvvmPasswordBox.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Login"
        Height="120"
        Width="325">
    <Grid>

        <Grid.RowDefinitions>
            <RowDefinition Height="20" />
            <RowDefinition Height="20" />
            <RowDefinition Height="30" />
        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="90" />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>

        <TextBlock Text="Username:"
            Grid.Row="0"
            Grid.Column="0"
            Margin="2" />
        <TextBox Text="{Binding Path=Username}"
            Grid.Row="0"
            Grid.Column="1"
            Margin="2" />

        <TextBlock Text="Password:"
            Grid.Row="1"
            Grid.Column="0"
            Margin="2" />
        <PasswordBox Password="{Binding Path=Password}"
            Grid.Row="1"
            Grid.Column="1"
            Margin="2" />

        <Button Content="Login"
            Grid.Row="2"
            Grid.Column="1"
            HorizontalAlignment="Right"
            Width="100"
            Margin="2" />
    </Grid>
</Window>

Now, you’ll notice right away that something’s wrong when you see the blue squiggly line at the password binding:

wpf-bindpasswordbox-cantbind

Oh no! What are we going to do now? If we can’t bind the password, and have to somehow retrieve it from the control, then we’ll break the MVVM pattern, right? And we MVVM knights-in-shining-armour can’t afford to deviate from the path of light that is MVVM. You see, the Password property can’t be bound specifically because it shouldn’t, but let’s say that we’re like most other developers and we’re so blinded by this MVVM dogma that we don’t care about the security concerns and we want an MVVM-friendly solution.

Well, no problem! It turns out that there actually is an MVVM-friendly way to bind the password – see the PasswordBoxAssistant and PasswordHelper implementations. To get up and running, let’s add a new PasswordBoxHelper class to our project, and add the implementation from the second link:

    public static class PasswordHelper
    {
        public static readonly DependencyProperty PasswordProperty =
            DependencyProperty.RegisterAttached("Password",
            typeof(string), typeof(PasswordHelper),
            new FrameworkPropertyMetadata(string.Empty, OnPasswordPropertyChanged));

        public static readonly DependencyProperty AttachProperty =
            DependencyProperty.RegisterAttached("Attach",
            typeof(bool), typeof(PasswordHelper), new PropertyMetadata(false, Attach));

        private static readonly DependencyProperty IsUpdatingProperty =
            DependencyProperty.RegisterAttached("IsUpdating", typeof(bool),
            typeof(PasswordHelper));


        public static void SetAttach(DependencyObject dp, bool value)
        {
            dp.SetValue(AttachProperty, value);
        }

        public static bool GetAttach(DependencyObject dp)
        {
            return (bool)dp.GetValue(AttachProperty);
        }

        public static string GetPassword(DependencyObject dp)
        {
            return (string)dp.GetValue(PasswordProperty);
        }

        public static void SetPassword(DependencyObject dp, string value)
        {
            dp.SetValue(PasswordProperty, value);
        }

        private static bool GetIsUpdating(DependencyObject dp)
        {
            return (bool)dp.GetValue(IsUpdatingProperty);
        }

        private static void SetIsUpdating(DependencyObject dp, bool value)
        {
            dp.SetValue(IsUpdatingProperty, value);
        }

        private static void OnPasswordPropertyChanged(DependencyObject sender,
            DependencyPropertyChangedEventArgs e)
        {
            PasswordBox passwordBox = sender as PasswordBox;
            passwordBox.PasswordChanged -= PasswordChanged;

            if (!(bool)GetIsUpdating(passwordBox))
            {
                passwordBox.Password = (string)e.NewValue;
            }
            passwordBox.PasswordChanged += PasswordChanged;
        }

        private static void Attach(DependencyObject sender,
            DependencyPropertyChangedEventArgs e)
        {
            PasswordBox passwordBox = sender as PasswordBox;

            if (passwordBox == null)
                return;

            if ((bool)e.OldValue)
            {
                passwordBox.PasswordChanged -= PasswordChanged;
            }

            if ((bool)e.NewValue)
            {
                passwordBox.PasswordChanged += PasswordChanged;
            }
        }

        private static void PasswordChanged(object sender, RoutedEventArgs e)
        {
            PasswordBox passwordBox = sender as PasswordBox;
            SetIsUpdating(passwordBox, true);
            SetPassword(passwordBox, passwordBox.Password);
            SetIsUpdating(passwordBox, false);
        }
    }

You will also need to add the following usings at the top:

using System.Windows;
using System.Windows.Controls;

Now, let’s fix our Password binding. First, add the following attribute to the Window declaration in the XAML so that we can access our project’s classes (adjust namespace as needed):

        xmlns:local="clr-namespace:CsWpfMvvmPasswordBox"

Then update the PasswordBox declaration to use the PasswordBoxHelper as follows:

        <PasswordBox local:PasswordHelper.Attach="True"
            local:PasswordHelper.Password="{Binding Path=Password}"
            Grid.Row="1"
            Grid.Column="1"
            Margin="2" />

That did it! The project now compiles.

Now, let’s see why what we have done is a very stupid thing to do. To do this, we’re going to need this WPF utility called Snoop, so go over to their website, download it, and install it using the .msi file.

Run Snoop. All you’ll see is a thin bar with a few buttons. On the right hand side, there is a button that looks like a circle (in fact it’s supposed to be crosshairs). If you hover over it, it will explain how to use it:

wpf-bindpasswordbox-snoop1

Run the WPF application we just developed. Enter something into the PasswordBox, but shhhh! Don’t tell anyone what you wrote there! 🙂

Next, drag those crosshairs from Snoop onto the WPF window:

wpf-bindpasswordbox-snoop2

When you let go, a window opens. In the treeview to the left, you can navigate through the mounds of crap that internally make up our simple application. When you find the PasswordBox, you’ll also find the PasswordHelper:

wpf-bindpasswordbox-snoop3

…and as you can see, the PasswordHelper keeps the password exposed in memory so anyone who knows what he’s doing can gain access to it. With a program like Snoop, anyone can access passwords that are bound.

There are a couple of lessons to take from this.

First, don’t ever bind passwords in WPF. There are other alternatives you can use, such as passing your entire PasswordBox control as a binding parameter – although this sounds extremely stupid, it’s a lot more secure than binding passwords. And arguably, it doesn’t break the MVVM pattern.

Secondly, don’t be so religious about so-called best practices such as MVVM. Ultimately they are guidelines, and there are many cases such as this where there are more important things to consider (in this case, security). For something as simple as a login window, it’s much more practical to just do without MVVM and do everything in the codebehind. It isn’t going to affect the scalability, maintainability, robustness, [insert architectural buzz-word here], etc of your application if you make an exception that is rational.

Before ending this article, I would like to thank the person who posted this answer to one of my questions on Stack Overflow. That answer helped me understand the dangers of binding passwords, and provided the inspiration for this article. As further reading, you might also want to read this other question (and its answer) which deals with the security of processing passwords in memory in general (not just data binding).

That’s all for today. Happy coding! 🙂