Category Archives: Software development

Actor Logging with Akka .NET

In this article, we’re going to see how we can work with logging in Akka .NET. There is a logging adapter which allows one to work with various different logging providers (e.g. NLog), and it is very easy to use from within actors.

The source code for this article is available at the Gigi Labs BitBucket repository.

Example Application

Before we get to the details of how to use logging in Akka .NET, let’s create a very simple application. The first thing we need to do is install the Akka package:

Install-Package Akka

To work with basic Akka components, we need the following using:

using Akka.Actor;

We can now create a simple actor. This actor will just output whatever message (string) it receives:

    public class LoggingActor : ReceiveActor
    {
        public LoggingActor()
        {
            this.Receive<string>(s => Console.WriteLine(s));
        }
    }

Finally, we create our ActorSystem in Main() and send a message to the actor:

        static void Main(string[] args)
        {
            Console.Title = "Akka .NET Logging";

            using (var actorSystem = ActorSystem.Create("MyActorSystem"))
            {
                Console.WriteLine("ActorSystem created!");

                var actor = actorSystem.ActorOf(Props.Create<LoggingActor>(), "loggingActor");

                actor.Tell("Hello!");

                Console.WriteLine("Press ENTER to exit...");
                Console.ReadLine();
            }
        }

If we run this, we get the following output:

akkanetlogging-initialoutput

You can see that some of the output came from the Console.WriteLine()s we have in Main(); while the “Hello!” message came from the actor. But there is also a warning that is not coming from anywhere within our code.

StandardOutLogger

We can adjust our actor’s code to use a logger instead of writing directly to the console. The actor doesn’t care what kind of logger it is; this detail is entirely configurable. By default, it will use the StandardOutLogger which writes to the console. But we can use something else (e.g. NLog or Serilog) and the code would be completely unchanged.

    public class LoggingActor : ReceiveActor
    {
        private readonly ILoggingAdapter logger = Logging.GetLogger(Context);

        public LoggingActor()
        {
            this.Receive<string>(s => logger.Info(s));
        }
    }

If we run this, the “Hello!” message still gets written to the console, but it is now part of a longer formatted log message:

akkanetlogging-standardoutlogger

LogLevel

Just about all logging frameworks have a concept of log level. Typically these consist of at least Debug, Info, Warning and Error (some even have a Fatal level). You tell the logging framework what is the minimum level you’re interested in. So if your minimum level is Warning, the logging framework omits Debug and Info messages.

In Akka .NET, you can configure the minimum log level you’re interested in as part of the HOCON configuration within your App.config as follows:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <configSections>
    <section name="akka" type="Akka.Configuration.Hocon.AkkaConfigurationSection, Akka" />
  </configSections>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>

  <akka>
    <hocon>
      <![CDATA[ akka { loglevel = DEBUG } ]]>
    </hocon>
  </akka>

</configuration>

If we set loglevel to INFO, we get exactly the same as before. But now that we’ve set it to DEBUG, we actually get some additional logging from within Akka .NET:

akkanetlogging-debugoutput

Note: the screenshot actually contradicts what I was saying earlier about the StandardOutLogger. It actually seems to be replacing StandardOutLogger with this DefaultLogger. Presumably DefaultLogger uses StandardOutLogger underneath.

Automatic Logging

Akka .NET provides certain logging mechanisms out of the box. One of these is logging received messages (so we don’t even need to do that in code). You can turn on these mechanisms in the HOCON configuration as follows:

  <akka>
    <hocon>
      <![CDATA[
        akka
        {
          loglevel = DEBUG
          
          actor
          {
            debug
            {
              receive = on      # log any received message
              autoreceive = on  # log automatically received messages, e.g. PoisonPill
              lifecycle = on    # log actor lifecycle changes
              event-stream = on # log subscription changes for Akka.NET event stream
              unhandled = on    # log unhandled messages sent to actors
            }
          }
        }
      ]]>
    </hocon>
  </akka>

Now, to actually log received messages, you also need to make your actor implement the empty ILogReceive interface as per this StackOverflow question:

    public class LoggingActor : ReceiveActor, ILogReceive

If you run the application now, you’ll see that a lot more messages are being logged, including another entry for the “Hello!” message:

akkanetlogging-automaticlogging

Tip: ideally make sure the loglevel HOCON setting and the node under actor in HOCON (in this case debug) are in sync. If you set loglevel to INFO now, all the automatic logging will stop writing.

Integrating NLog

The logging adapter is particularly useful because you can swap out logging frameworks without having to touch the code. We are currently using the StandardOutLogger (or DefaultLogger?), but with some simple configuration, we can use NLog or some other provider instead.

The Akka .NET Logging documentation page shows the currently supported logging frameworks. Typically, you install a NuGet package for the framework you want, and set up its own configuration. I’m going to show you how to do this with NLog, but it’s an arbitrary choice, and the steps are similar for other logging frameworks.

1. Install the relevant NuGet package:

Install-Package Akka.Logger.NLog

2. Add an NLog.config to the project and configure it as you like:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <targets>
    <target name="file" xsi:type="File" fileName="test.log" />
  </targets>
  
  <rules>
    <logger name="*" minlevel="Info" writeTo="file" />
  </rules>
  
</nlog>

3. Right click NLog.config, Properties, then set to Copy always or Copy if newer:

akkanetlogging-copyalways

4. Update your HOCON to use the relevant logger:

  <akka>
    <hocon>
      <![CDATA[
        akka
        {
          loglevel = DEBUG
          loggers = ["Akka.Logger.NLog.NLogLogger, Akka.Logger.NLog"]
          
          actor
          {
            debug
            {
              receive = on      # log any received message
              autoreceive = on  # log automatically received messages, e.g. PoisonPill
              lifecycle = on    # log actor lifecycle changes
              event-stream = on # log subscription changes for Akka.NET event stream
              unhandled = on    # log unhandled messages sent to actors
            }
          }
        }
      ]]>
    </hocon>
  </akka>

Let’s run it now:

akkanetlogging-nlogoutput

You can see that the console output is now limited to what we’re writing in Main(), while the rest has gone into a file called test.log. Since our minlevel is Info, we’re not getting the automatic logging which is configured for the debug log level.

Secure Authentication with BCrypt

Introduction

Implementing authentication (i.e. user login) in a system sounds simple. Just compare username and password with what is stored in the database, right?

Actually, it’s not nearly as simple as it looks to the user logging in. Storing and checking user credentials is a process with different levels of security (and I’m no expert, so there may be more):

  1. Store passwords in plain text. Very bad idea.
  2. Hash the passwords. They won’t be easily readable, but can be cracked by rainbow tables.
  3. Salt and hash the passwords. Protects against rainbow tables as well, but still vulnerable to high-performance brute force attacks.
  4. Use a slow hash algorithm to limit the effectiveness of brute force attacks.

My article “Securing Passwords by Salting and Hashing” covers the first three items. This article will deal with the fourth item, and introduce BCrypt, which gives you all four.

The source code for this article is available at the Gigi Labs BitBucket repository.

Authentication with BCrypt

Before we discuss the merits of using BCrypt, let’s see how to use it.

You first need to include the BCrypt library in your project. You can do this via NuGet:

bcrypt-nuget

The functionality we need to use is all in a class called BCryptHelper, which you get access to by including the following namespace:

using DevOne.Security.Cryptography.BCrypt;

With that, it is very easy to generate a salt, hash a password with it, and validate the password against its salted hashed version:

        static void Main(string[] args)
        {
            Console.Title = "BCryptTest";

            string password = "My$ecureP@$sW0Rd";

            string salt = BCryptHelper.GenerateSalt();
            string hashedPassword = BCryptHelper.HashPassword(password, salt);

            bool valid = BCryptHelper.CheckPassword(password, hashedPassword);

            Console.WriteLine("Salt:            {0}", salt);
            Console.WriteLine("Hashed Password: {0}", hashedPassword);
            Console.WriteLine("Valid:           {0}", valid);

            Console.ReadLine();
        }

Here’s the output of this little program:

bcrypt-auth

The BCrypt hashed password is typically a 60-byte string. As you can see, the salt is actually embedded within the hashed password (this StackOverflow answer explains more about how this works). This means you don’t need to store the salt separately.

Why BCrypt?

The functionality we have seen in the previous section doesn’t really give us anything more than hashing and salting with any other reasonably strong hash function. So why use BCrypt?

In many programming situations, writing code that executes fast is a good thing. Authentication is not one of those. If the algorithms you use to authenticate your users are fast, that means that brute force attacks may attempt large amounts of combinations per second – more so with modern hardware and GPUs.

Algorithms such as PBKDF2 and BCrypt differ from traditional hash algorithms such as MD5 or SHA256 in that they take a work factor as an input. That is, you can decide how fast or slow the algorithm runs. So if, for instance, you set up your algorithm to take 1 second to validate a password, that greatly limits the possibilities of brute force attacks when compared to algorithms that can run several hundreds or thousands of times per second. Read more about why BCrypt is badass at this Security StackExchange answer.

In BCrypt, the GenerateSalt() method takes an optional logRounds parameter that affects the performance of subsequent hash operations. It has a default value of 10 and can be set to a number between 4 and 31. The algorithm will run 2 to the power of logRounds times, making it run exponentially slower. To get an idea of this, I wrote some simple benchmarking code with the help of my trusted ScopedTimer class (from “Scope Bound Resource Management in C#“):

        static void GenerateSaltBenchmarks(string password)
        {
            for (int i = 10; i < 16; i++)
            {
                using (var scopedTimer = new ScopedTimer($"GenerateSalt({i})"))
                {
                    string salt = BCryptHelper.GenerateSalt(i);
                    string hashedPassword = BCryptHelper.HashPassword(password, salt);
                }
            }
        }

Here are the results:

bcrypt-benchmark

Summary

Use BCrypt to securely store and validate your passwords. It’s easy to use, easy to store, and hard to break. Also importantly, you can make it as slow as you like.

Data-Driven Tests with NUnit

This article shows how you can run the same unit test multiple times with different input data, using NUnit.

A Simple Scenario

Before we can learn about data-driven testing using NUnit, we need some actual logic to test. Let’s use the following class for this purpose:

    public class PriceCalculator
    {
        private decimal adultPrice;

        public PriceCalculator(decimal adultPrice)
        {
            this.adultPrice = adultPrice;
        }

        public decimal CalculatePrice(int age)
        {
            decimal multiplier = 0.0m;

            if (age >= 5 && age < 16) // 5 to 15: half price
                multiplier = 0.5m;
            else if (age >= 16 && age < 60) // 16 to 59: full price
                multiplier = 1.0m;
            else if (age >= 60) // 60+: half price
                multiplier = 0.5m;

            return this.adultPrice * multiplier;
        }
    }

So, here we have a scenario where we have something to sell (whatever it is), and certain age ranges get discounts. Kids under 5 years of age are free; older kids under 16 pay half price, as do senior citizens from age 60 onwards.

If you want to run NUnit unit tests from within Visual Studio, make sure you have the NUnit Test Adapter. You can get it from Tools menu -> Extensions and Updates…:

nunit-test-adapter

Plain Old Unit Tests

To test this, you’d have to write several unit tests. One of them could look like this:

        [Test]
        public void CalculatePriceTest()
        {
            // arrange

            const decimal adultPrice = 10m;
            var priceCalculator = new PriceCalculator(adultPrice);
            const int age = 10;

            // act

            decimal actualPrice = priceCalculator.CalculatePrice(age);

            // assert

            const decimal expectedPrice = 5m;

            Assert.AreEqual(expectedPrice, actualPrice);
        }

You’d have to write other similar tests to cover the various age ranges and edge cases (e.g. making sure that age boundaries are inclusive or exclusive as needed).

Copying this test code and varying the input data is a bit of a hassle and not quite DRY. An alternative could be to set up a list with the input data and expected result and iterate over it. That’s not necessary, because NUnit gives us a way to do this out of the box.

The TestCase Attribute

NUnit provides a feature called Parameterized Tests. These provide two mechanisms that allow you to easily run the same test with multiple input data.

The first of these is the [TestCase] attribute. This replaces the [Test] attribute we used before, and provides input data to pass to the test method via parameters:

        [TestCase(1, 0)]
        [TestCase(10, 5)]
        [TestCase(20, 10)]
        [TestCase(70, 5)]
        public void CalculatePriceTest(int age, decimal expectedPrice)
        {
            // arrange

            const decimal adultPrice = 10m;
            var priceCalculator = new PriceCalculator(adultPrice);

            // act

            decimal actualPrice = priceCalculator.CalculatePrice(age);

            // assert

            Assert.AreEqual(expectedPrice, actualPrice);
        }

This can actually be simplified further by using the ExpectedResult named parameter, and replacing the Assert with a simple return statement:

        [TestCase(1, ExpectedResult = 0)]
        [TestCase(10, ExpectedResult = 5)]
        [TestCase(20, ExpectedResult = 10)]
        [TestCase(70, ExpectedResult = 5)]
        public decimal CalculatePriceTest(int age)
        {
            // arrange

            const decimal adultPrice = 10m;
            var priceCalculator = new PriceCalculator(adultPrice);

            // act

            decimal actualPrice = priceCalculator.CalculatePrice(age);

            // assert

            return actualPrice;
        }

Note: technically we should declare the expected results as decimals in this case, such as ExpectedResult = 0m. However, the attribute doesn’t seem to allow it. Integers work just fine.

The TestCaseSource Attribute

The [TestCase] attribute works great when you want to run the same test against a few different combinations of input data and expected results. However, it can still get very tedious for very exhaustive tests with a lot of input data.

A more fitting technique for such scenarios is to use the [TestCaseSource] attribute:

        [TestCaseSource("TestCases")]
        public decimal CalculatePriceTest(int age)
        {
            // arrange

            const decimal adultPrice = 10m;
            var priceCalculator = new PriceCalculator(adultPrice);

            // act

            decimal actualPrice = priceCalculator.CalculatePrice(age);

            // assert

            return actualPrice;
        }

The [TestCaseSource] attribute takes the name of a public static property which will provide the input data (i.e. the same data that we passed in to the [TestCase] attribute earlier). You can use this to load the data from arbitrary sources such as databases, files, etc.

There are a number of ways of working with the [TestCaseSource] attribute (refer to the documentation), but a straightforward way to work with it is to use the TestCaseData class. You can provide it with any input data as well as an expected result. For instance, say we have the following CSV file mapping age to expected price, for ages between 0 and 99:

0,0
1,0
2,0
3,0
4,0
5,5
6,5
7,5
8,5
9,5
10,5
11,5
12,5
13,5
14,5
15,5
16,10
17,10
18,10
...

We can write a property that reads this and provides the necessary test case data as follows:

        public static List<TestCaseData> TestCases
        {
            get
            {
                var testCases = new List<TestCaseData>();

                using (var fs = File.OpenRead(@"C:\test.csv"))
                using (var sr = new StreamReader(fs))
                {
                    string line = string.Empty;
                    while (line != null)
                    {
                        line = sr.ReadLine();
                        if (line != null)
                        {
                            string[] split = line.Split(new char[] { ',' },
                                StringSplitOptions.None);

                            int age = Convert.ToInt32(split[0]);
                            decimal expectedPrice = Convert.ToDecimal(split[1]);

                            var testCase = new TestCaseData(age).Returns(expectedPrice);
                            testCases.Add(testCase);
                        }
                    }
                }

                return testCases;
            }
        }

You can see the power of this approach when you run a hundred tests in the bat of an eyelid:

nunit-hundred-tests

The first test takes a small performance penalty as the test data is loaded. But that’s a small price to pay for the development time saved in writing unit tests.

Unity3D: Changing game speed and pausing

This article was originally posted on 4th August 2013 at Programmer’s Ranch using Unity3D 4.2.0f4. This updated version of the article uses Unity3D 5.3.4f1, and the source code is available at the Gigi Labs BitBucket repository. Syntax highlighting and a new screenshot have been added, and the text is slightly modified.

In this article, we’ll learn about controlling time in Unity3D. This allows us to easily pause the game, slow it down, or speed it up.

Create a new project and add a sphere to your scene via GameObject menu -> 3D Object -> Sphere. Next, create a new C# script by right clicking in the Project panel, and selecting Create -> C# Script. Name it Ball, and drag it onto your Sphere in the Hierarchy panel. Double-click the script to open it in Visual Studio.

We’re going to make a very basic bouncing ball just to be able to see the effects of our change in speed. Start off with the following code for the Ball script:

public class Ball : MonoBehaviour
{
    private Vector3 velocity;

    // Use this for initialization
    void Start()
    {
        this.velocity = new Vector3(1.0f, 1.0f, 0.0f);
    }

    // Update is called once per frame
    void Update()
    {
        this.transform.position += this.velocity * Time.deltaTime;

        if (this.transform.position.x > 5.0f)
            velocity.x = -velocity.x;
        else if (this.transform.position.x < -5.0f)
            velocity.x = -velocity.x;
        else if (this.transform.position.y > 6.0f)
            velocity.y = -velocity.y;
        else if (this.transform.position.y < -5.0f)
            velocity.y = -velocity.y;
    }
}

This will make the ball bounce when it reaches the sides of the screen. This may vary depending on your monitor so use whichever values work best.

unity3d-speed-ball

Games look interactive because they generate a certain number of images (frames) per second, usually something between 30 and 60. Time.deltaTime is the time between one frame and the next; multiplying this by the velocity makes the ball move pretty uniformly.

Another important property of the Time class is Time.timeScale. This is a measure of how quickly scripts and animations run, and is set to 1.0f by default. We can change this to make the game run at different speeds. To try it out, add the following code to the Ball script’s Update() method:

        if (Input.GetKeyDown(KeyCode.P))
            Time.timeScale = 0.0f;
        else if (Input.GetKeyDown(KeyCode.N))
            Time.timeScale = 1.0f;
        else if (Input.GetKeyDown(KeyCode.F))
            Time.timeScale = 2.0f;
        else if (Input.GetKeyDown(KeyCode.S))
            Time.timeScale = 0.5f;

What we’re doing here is:

  • If the player presses ‘P’ (pause), we set the time scale to zero, effectively stopping any movement in the game.
  • If the player presses ‘N’ (normal speed), we set the time scale to the default of 1.0f.
  • If the player presses ‘F’ (fast), we set the time scale to double the normal speed.
  • If the player presses ‘S’ (slow), we set the time scale to half the normal speed.

This simple property allows you to not only pause the game, but also to play the game at different speeds. Several games including Starcraft and Warcraft 2 have settings that allow you to tweak the game speed in order to make it more challenging or less frenetic.

starcraft-speed-settings

This article showed how a single line of code in Unity3D is enough to change the speed of a game or pause it. Although this was a very easy tutorial, I hope you will also find it very useful in any games you make!

Monitoring the Size of a Folder

In this article, we’ll develop a simple application that can check the total size taken by a folder (including the files directly inside it, and those in its subfolders), and monitor it periodically to send alerts if it exceeds a certain threshold. This can be useful, for example, to ensure that automatic backups aren’t taking too much space on disk. The source code is available at the Gigi Labs BitBucket repository.

The techniques we’ll use for this are nothing new. We’ll use recursive directory traversal to calculate the total size of the folder, and we’ll use a timer to check this periodically. To send alerts, we’d typically use SmtpClient to send email, but since you’d need an actual SMTP server to test this, we’ll just write something to the console instead.

We’ll start off by calculating the total size of a folder:

        static void Main(string[] args)
        {
            string directoryPath = ConfigurationManager.AppSettings["DirectoryPath"];

            var dir = new DirectoryInfo(directoryPath);
            var size = CalculateDirectorySize(dir);
            Console.WriteLine(size);

            Console.ReadKey(true);
        }

We’re reading the path to the directory to monitor from an application setting (remember to add a reference to System.Configuration). Then we pass the resulting DirectoryInfo object to a recursive CalculateDirectorySize() method, which we’ll define next:

        static long CalculateDirectorySize(DirectoryInfo dir)
        {
            long totalSize = 0L;

            foreach (var file in dir.EnumerateFiles())
                totalSize += file.Length;

            foreach (var subdir in dir.EnumerateDirectories())
                totalSize += CalculateDirectorySize(subdir);

            return totalSize;
        }

This recursive method simply adds up the sizes of the files it contains directly, then adds the total size after recursing into its subdirectories. We’re using the long data type because int will overflow if the folder contains several gigabytes of data.

Note: you might get an UnauthorizedAccessException if you run this in something like C:. It’s easiest to just run it on a folder within your user folder.

This is the result of running the above code against my desktop (which I seem to need to clean up):

dirsize-desktop

We can now refactor our Main() method to run a timer and periodically check the size of the folder:

        private static string directoryPath;

        static void Main(string[] args)
        {
            directoryPath = ConfigurationManager.AppSettings["DirectoryPath"];

            var timer = new Timer();
            timer.Interval = 5000;
            timer.Elapsed += Timer_Elapsed;
            timer.Enabled = true;
            timer.Start();

            Console.ReadKey(true);
        }

Every 5 seconds, the timer will run the following event handler:

        private static void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            var dir = new DirectoryInfo(directoryPath);
            var size = CalculateDirectorySize(dir);
            Console.WriteLine(size);
        }

It is now very easy to extend this with a warning mechanism:

        private static string directoryPath;
        private static long threshold;

        static void Main(string[] args)
        {
            directoryPath = ConfigurationManager.AppSettings["DirectoryPath"];
            threshold = Convert.ToInt64(ConfigurationManager.AppSettings["Threshold"]);

            var timer = new Timer();
            timer.Interval = 5000;
            timer.Elapsed += Timer_Elapsed;
            timer.Enabled = true;
            timer.Start();

            Console.ReadKey(true);
        }

        private static void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            var dir = new DirectoryInfo(directoryPath);
            var size = CalculateDirectorySize(dir);
            string warning = size > threshold ? " WARNING - THRESHOLD EXCEEDED" : null;
            Console.WriteLine("{0}{1}", size, warning);
        }

Here’s an example run of this application:

dirsize-warnings

Add to that some exception handling and console title code, and you get the source code available in the Gigi Labs BitBucket repository.