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.