Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Thursday, 31 October 2013

Faking AppSettings in tests

If you have some code that uses configuration from an app.config or web.config file, and you need to retrospectively write tests for it, there are several approaches you can take to get fake setting into your tests.

Given this code
using System;
using System.Configuration;
using System.IO;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var writer = new StringWriter())
            {
                new SeasonWriter().WriteSeason(writer);
                Console.WriteLine(writer);
                Console.ReadLine();
            }
        }
    }

    public class SeasonWriter
    {
        public void WriteSeason(TextWriter textWriter)
        {
            var month = ConfigurationManager.AppSettings["Month"];
            switch (month)
            {
                case "January":
                case "February":
                case "December":
                    textWriter.Write("Winter");
                    break;
                case "March":
                case "April":
                case "May":
                    textWriter.Write("Spring");
                    break;
                case "June":
                case "July":
                case "August":
                    textWriter.Write("Summer");
                    break;
                case "September":
                case "October":
                case "November":
                    textWriter.Write("Autumn");
                    break;
                default:
                    throw new ConfigurationErrorsException("No setting defined for 'Month'."
                        + Environment.NewLine
                        + "Please add a setting to the .exe.config file under the section AppSettings."
                        + Environment.NewLine
                        + "For more info on the .exe.config file, follow this link "
                        + "http://msdn.microsoft.com/en-us/library/vstudio/1fk1t1t0(v=vs.110).aspx");
            }
        }
    }
}
In order to get tests around the SeasonWriter class, the AppSettings entry "Month" needs to be faked or abstracted. Some options are:

Create an app.config file in the test project

This is the most obvious starting point. Create a test project to contain the SeasonWriterTests file, with an app.config containing a "Month" entry:
<appSettings>
  <add key="Month" value="January"/>
</appSettings>
using NUnit.Framework;
using System.IO;

namespace Demo.Test
{
    [TestFixture]
    public class SeasonWriterTests
    {
        [Test]
        public void WriteSeasonExpectWinter()
        {
            var writer = new StringWriter();
            var target = new SeasonWriter();
            target.WriteSeason(writer);
            Assert.That(writer.ToString(), Is.EqualTo("Winter"));
        }
    }
}
This will allow the test to run, but will limit you to testing a single path through the code. It's also flaky, because your test depends on a magic string in a separate file.

Pass the configuration setting in


This solution is a refactor of the WriteSeason method, so it takes the config setting in as a string. This sounds like a clean fix, with benefits
  • the responsibility for getting that value has been handed off to the user of the method
  • the code is easier to test

However, there are downsides
  • the refactor is an untested change
  • there could be many users of this method, and each one would be responsible for getting the month value
  • the exception type in the WriteSeason method is no longer correct

Set the config value


The easiest way to fake an AppSettings value is just to set it in your test class. ConfigurationManager.AppSettings is just a NameValueCollection, and items can be written as well as read:
using NUnit.Framework;
using System.IO;
using System.Configuration;

namespace Demo.Test
{
    [TestFixture]
    public class SeasonWriterTests
    {
        [TestCase("January""Winter")]
        [TestCase("February""Winter")]
        [TestCase("March""Spring")]
        [TestCase("April""Spring")]
        [TestCase("May""Spring")]
        [TestCase("June""Summer")]
        [TestCase("July""Summer")]
        [TestCase("August""Summer")]
        [TestCase("September""Autumn")]
        [TestCase("October""Autumn")]
        [TestCase("November""Autumn")]
        [TestCase("December""Winter")]
        public void WriteSeasonExpectCorrectSeasonForMonth(string month, string expectedSeason)
        {

          ConfigurationManager.AppSettings["Month"] = month;

            var writer = new StringWriter();
            var target = new SeasonWriter();
            target.WriteSeason(writer);
            Assert.That(writer.ToString(), Is.EqualTo(expectedSeason));
        }
    }
}

Sunday, 13 October 2013

Refactoring legacy code to add tests

Imagine you have some legacy code in your product. Code that's been added to over the years by several different developers, none of who were certain they understood the code. There is no separation of concerns; the code has business logic and database access baked in. There's no useful documentation and the code comments are no more than sarcastic outbursts of cynicism.

A bug report has come in that suggests some of the SQL being executed from this method is invalid. So, what's the plan? Hack the SQL construction around until it feels like it does what you want, hoping you haven't broken anything else in the class? Or take a more structured approach?

To illustrate the problem, I have written some legacy-style code so I can show how to refactor it to make it testable. The techniques here are a pragmatic approach to getting legacy code under test, while making as few untested changes as necessary. Because as you will already know, a class is only able to be refactored when it's under test.

The code for the class is available on GitHub here, and looks like this
using System.Collections;

namespace CombinationOfConcerns
{
    public class Data
    {
        private readonly string _type;

        public Data(string type)
        {
            _type = type;
        }

        public ArrayList GetData(string code, string gdr, string filterType, bool getAge)
        {
            ArrayList results = null;

            var sql = "select id from people where type = " + _type + " and gender ='" + gdr + "'";
            string values = DatabaseWrapper.GetSingleResult(sql);
            for (int i = 0; i < values.Split(',').Length; i++)
            {
                switch (code)
                {
                    case "128855":
                        sql = "select name";
                        if (getAge)
                            sql += ",age";                    
                        sql += ",gender from people where type in(" + values + ")";
                        if (filterType == "45")
                        {
                            sql += " and gender='" + gdr + "'";
                        }
                        if (filterType == "87")
                        {
                            sql += " and shoesize = 43";
                        }
                        results = DatabaseWrapper.GetManyResults(sql);
                        break;
                    case "1493":
                        sql = "select dogs.name, dogbreeds.breed from";
                        sql += " dogs inner join dogbreeds on";
                        sql += " dogs.breed = breed.breed where dogs.ownerId in(" + values + ")";
                        if (filterType == "12")
                        {
                            sql += " and coat='curly'";
                        }
                        results = DatabaseWrapper.GetManyResults(sql);
                        break;
                    default:
                        sql = "select name, population from countries,people on where people.countryname = countries.name and people.id in(" + values + ")";
                        if (filterType == "f")
                        {
                            sql += " and countries.continent='South America'";
                        }
                        if (filterType == "642")
                        {
                            sql += " and countries.continent='Europe'";
                        }
                        results = DatabaseWrapper.GetManyResults(sql);
                        break;
                }
            }
            return results;
        }
    }
}

Run the code

Some great advice from Michael Feathers goes something like this: "if you need to see what some code does, run it." In practice, this means write a test that exercises the code, and see how far it gets without failing. If it doesn't fail, that route through the code has no dependencies and will be easier to write tests for. If it does fail, it will highlight dependencies that need to be abstracted.

To run some code, the first job is to find a suitable entry point to the method. If the method to test is public or internal, that's the entry point. If not, is the method called from a public or internal method? If not, the method should be made internal to allow it to be called directly.

The method on the Data class that needs testing is the public GetData method. Here's the first test:
        [TestFixture]
        public class GetData
        {
            [Test]
            public void WithEmptyArgs()
            {
                var target = new Data("");
                target.GetData("", "", "", false);
            }
        }
When this runs, the GetData method fails on a call to the DatabaseWrapper class, showing that there's a dependency on that class that needs to be faked for testing.
        public ArrayList GetData(string code, string gdr, string filterType, bool getAge)
        {
            ArrayList results = null;

            var sql = "select id from people where type = " + _type + " and gender ='" + gdr + "'";
            string values = DatabaseWrapper.GetSingleResult(sql);
            //Code fails in call to GetSingleResult

Deal with dependencies

If the DatabaseWrapper class was an instance, the best way to deal with it would be to extract its interface and use that interface through the code, allowing a stub to be used from a test. However, in this example DatabaseWrapper is a static class, so needs to be dealt with in a different way.

One way would be to add an instance wrapper class around the static class (DatabaseWrapperWrapper..?). This would call the static method from within that class's instance methods, and allow an interface to be used in the GetData method.

Another way is to add a protected virtual method in the Data class that wraps the static method; this allows the test code to use a subclass of the Data class, and override the virtual method. I'll demonstrate that. Here's the new virtual method and its usage in the GetData method:
        protected virtual string GetSingleResult(string sql)
        {
            return DatabaseWrapper.GetSingleResult(sql);
        }

        public ArrayList GetData(string code, string gdr, string filterType, bool getAge)
        {
            ArrayList results = null;

            var sql = "select id from people where type = " + _type + " and gender ='" + gdr + "'";

            //Now calls virtual method
            string values = GetSingleResult(sql);

and here's the usage in the test project. There's a new class, FakeData, that extends Data. This has an override of the virtual GetSingleResult method, returning an empty string for now. Note that the FakeData class is the new target for the test.
        [TestFixture]
        public class GetData
        {
            [Test]
            public void WithEmptyArgs()
            {
                var target = new FakeData("");
                target.GetData("", "", "", false);
            }

            private class FakeData : Data
            {
                public FakeData(string type)
                    : base(type)
                { }

                protected override string GetSingleResult(string sql)
                {
                    return "";
                }
            }
        }
The code under test now runs up to the call to DatabaseWrapper.GetManyResults, so the GetManyResults method needs a virtual wrapper the same as GetSingleResult did:
        protected virtual ArrayList GetManyResults(string sql)
        {
            return DatabaseWrapper.GetManyResults(sql);
        }
the calls to DatabaseWrapper.GetManyResults need to be changed to the local GetManyResults:
...
    default:
        sql = "select name, population from countries,people on where people.countryname = countries.name and people.id in(" + values + ")";
        if (filterType == "f")
        {
            sql += " and countries.continent='South America'";
        }
        if (filterType == "642")
        {
            sql += " and countries.continent='Europe'";
        }

        // Now calls the virtual method
        results = GetManyResults(sql);
        break;
...
and the FakeData class in the tests needs to override the method:
            private class FakeData : Data
            {
                public FakeData(string type)
                    : base(type)
                { }

                protected override string GetSingleResult(string sql)
                {
                    return "";
                }

                protected override ArrayList GetManyResults(string sql)
                {
                    return new ArrayList();
                }
            }
Now there's a test that mocks a call to the database, and runs through the method from start to finish. But because of the many responsibilities of the code, what needs to be asserted - the SQL that is being executed on the database - is not exposed outside the GetData method.

Sensing variables

In order to see the value of the SQL being executed, the test class will use a "sensing variable". This is a variable that stores a runtime value so that it is available for a test to perform an assertion on. In this example, the sensing variable will be on the FakeData class, and will store the value of the SQL string passed to the GetManyResults method.
        [TestFixture]
        public class GetData
        {
            [Test]
            public void WithEmptyArgs()
            {
                var target = new FakeData("");
                target.GetData("", "", "", false);
                // Use the sensing variable in the assertion
                Assert.That(target.ExecutedSql, Is.EqualTo(""));
            }

            private class FakeData : Data
            {
                // The sensing variable
                public string ExecutedSql { get; private set; }

                public FakeData(string type)
                    : base(type)
                { }

                protected override string GetSingleResult(string sql)
                {
                    return "";
                }

                protected override ArrayList GetManyResults(string sql)
                {
                    //Store the value in the sensing variable
                    ExecutedSql = sql;
                    return new ArrayList();
                }
            }
        }
A well-placed breakpoint allows the sensing variable's value to be harvested, and used as the expected result for that test.

            [Test]
            public void WithEmptyArgs()
            {
                var target = new FakeData("");
                target.GetData("", "", "", false);
                
                const string expected = "select name, population "
                    + "from countries,people on where people.countryname = "
                    + "countries.name and people.id in()";
                
                Assert.That(target.ExecutedSql, Is.EqualTo(expected));
            }
Which gives the first green test!

Although this single test is not particularly useful, the journey to get to it has shown some techniques that are available when tackling legacy code. In future posts I'll write more tests and get to a point where it's safe to refactor the code. The I'll refactor the hell out of it.

In Summary

  1. Run the code
    • Identify the start point
    • Make method visible (public/internal)
    • Write a test to exercise the code
  2. Deal with dependencies
    • Introduce interface for instance class
    • Wrap a static class in an instance class
    • Create virtual method to hide static method calls
  3. Sensing variables
    • Use to surface runtime values


If there are other techniques that you employ to refactor legacy code, I'd like to know what they are - they are all useful.

The before and after code used in this example is on GitHub at orangutanboy/LegacyCodeUnderTest

Monday, 30 September 2013

What I Learnt About .Net Custom Formatters

I recently needed to format a DateTime object to a custom format, this post is a dump of what I learnt. It shows the steps necessary to implement a formatter that returns the name of the date's weekday. (This wasn't the custom format I needed to implement, it's just an example).

There are 2 components to formatting, a FormatProvider and a CustomFormatter - the FormatProvider's task is to serve up an instance of a CustomFormatter.

First, the FormatProvider:
    public class WeekdayFormatProvider : IFormatProvider
    {
        public object GetFormat(Type formatType)
        {
            throw new NotImplementedException();
        }
    }
Next, the CustomFormatter:
    public class WeekdayFormatter : ICustomFormatter
    {
        public string Format(string format, object arg, IFormatProvider formatProvider)
        {
            throw new NotImplementedException();
        }
    }
IFormatProvider.GetFormat() is called from within the string.Format method. The formatType argument is the type of CustomFormatter required; the convention is, if you can provide a formatter of that type, then return one, otherwise return null.
    public class WeekdayFormatProvider : IFormatProvider
    {
        public object GetFormat(Type formatType)
        {
            if (formatType == typeof(ICustomFormatter))
            {
                return new WeekdayFormatter();
            }
            return null;
        }
    }
The type of formatter required will change depending on the method used to invoke the FormatProvider. For example, the DateTime.ToString(IFormatProvider) method will request a formatter of type DateTimeFormatInfo. As this class is sealed, it's not possible to derive from it. So in order to use a custom formatter with a DateTime, you need to use a string.Format(IFormatProvider...) overload.

ICustomFormatter.Format() is also called from the string.Format method. It should return the formatted string for the required object (passed to the method via the arg parameter). For this example it just needs to calculate the day name and reverse it.
    public class WeekdayFormatter : ICustomFormatter
    {
        public string Format(string format, object arg, IFormatProvider formatProvider)
        {
            var dayName = ((DateTime)arg).DayOfWeek.ToString();
            return new string(dayName.Reverse().ToArray());
        }
    }
The format parameter is used to pass the formatString component of a format item.
So, for the usage
    string.Format(new WeekdayFormatProvider(), "{0:R}", DateTime.MinValue);
the arguments would be
    format : "R"
    arg : [DateTime.MinValue]
    formatProvider : WeekdayFormatProvider
The following shows how this format string could be used. The formatter is going to inspect the value passed; if it's "R" then reverse the weekday, otherwise return the weekday in the more usual format.
    public class WeekdayFormatter : ICustomFormatter
    {
        public string Format(string format, object arg, IFormatProvider formatProvider)
        {
            var dayName = ((DateTime)arg).DayOfWeek.ToString();
            if (format == "R")
            {
                return new string(dayName.Reverse().ToArray());
            }
            return dayName;
        }
    }
Another convention, in the Format() method, is to handle arguments that are not specifically of the type expected. The pattern is shown in this, the final version of the formatter:
    public class WeekdayFormatter : ICustomFormatter
    {
        public string Format(string format, object arg, IFormatProvider formatProvider)
        {
            try
            {
                var dayName = ((DateTime)arg).DayOfWeek.ToString();
                if (format == "R")
                {
                    return new string(dayName.Reverse().ToArray());
                }
                return dayName;
            }
            catch (InvalidCastException)
            {
                if (arg is IFormattable)
                {
                    return ((IFormattable)arg).ToString(format, CultureInfo.CurrentCulture);
                }
                else if (arg != null)
                {
                    return arg.ToString();
                }
                else
                {
                    return String.Empty;
                }
            }
        }
    }
Putting it all together, this usage:
        static void Main(string[] args)
        {
            var formatProvider = new WeekdayFormatProvider();
            
            var formattedMinDate = string.Format(formatProvider, "{0}", DateTime.MinValue);
            Console.WriteLine(formattedMinDate);
            
            var formattedMinDateReversed = string.Format(formatProvider, "{0:R}", DateTime.MinValue);
            Console.WriteLine(formattedMinDateReversed);

            var formattedInteger = string.Format(formatProvider, "{0:R} {1}", DateTime.MinValue, int.MaxValue);
            Console.WriteLine(formattedInteger);
            
            Console.ReadLine();
        }
gives this output:
Monday
yadnoM
yadnoM 2147483647
The final code used is available on GitHub at https://github.com/orangutanboy/CustomFormatter/

Saturday, 27 July 2013

Visual Studio's Make Object ID

Ever wished you could watch the value of an out-of-scope variable while debugging in Visual Studio? You can, if you use the Make Object ID option in the watch/local window. Here's an example, with a variable p that goes out of scope when control jumps to a new method, or back to the calling method:
class Person
{
    public Person(string name)
    {
        Name = name;
    }
    public string Name { get; set; }
}

public class Program
{
    public static void Main(string[] args)
    {
        DoIt();
    }

    private static void DoIt()
    {
        var p = new Person("Baldrick");
        DoIt2();
    }

    private static void DoIt2()
    {
        return;
    }
}
If you step through this code in Visual Studio and add a watch to variable p in method DoIt, the watch window will look like this:


When you step into method DoIt2, or out to Main, and refresh the watch on p, you get this message in the watch window:


If you want to be able to reliably watch the variable, the solution is to Make Object ID. Let's take the code back to DoIt and right-click on the watch on variable p:

Click on Make Object ID, and you'll see variable p is allocated object ID "1#"

If you add a watch to 1#, this allows you to view the value of p even when p goes out of scope:

The 1# reference can be used to update the value of the underlying variable p:

which will be reflected when (if) the object comes back into scope:



What about Garbage Collection?

The Object ID doesn't create a managed reference to the underlying object, which means that it will not interfere with its garbage collection:




Sunday, 21 July 2013

How to post an HTTP form with .Net Micro Framework

This snippet of code shows how to use the .Net Micro Framework to create a representation of an HTTP form, and post it to a URL:
        public void PostNameValues(string value1, string value2)
        {
            // Create the form values
            var formValues = "name1=" + value1 + "&name2=" + value2;

            // Create POST content
            var content = Gadgeteer.Networking.POSTContent.CreateTextBasedContent(formValues);

            // Create the request
            var request = Gadgeteer.Networking.HttpHelper.CreateHttpPostRequest(
                @"http://www.mjonesweb.co.uk/api/values" // the URL to post to
                , content // the form values
                , "application/x-www-form-urlencoded" // the mime type for an HTTP form
            );

            // Post the form
            request.SendRequest();
        }

Friday, 21 June 2013

Why you should check event delegates for null

The other day I came across some code that was raising an event like this:
    public class Dummy
    {
        public event EventHandler SomethingHappened;
        public void RaiseEvent()
        {
            try
            {
                SomethingHappened(this, EventArgs.Empty);
            }
            catch { }
        }
    }
As opposed to the recognised pattern of
    public class Dummy
    {
        public event EventHandler SomethingHappened;
        public void RaiseEvent()
        {
            if (SomethingHappened != null)
            {
                SomethingHappened(this, EventArgs.Empty);
            }
        }
    }
Chatting to a friend at the pub, I mentioned about this code and the fact that the code was relying on exception handling to control the flow, and he mentioned that it would be a lot slower if there wasn't an event handler defined. I knew it would be slower to create, throw and catch a NullReferenceException than to perform a null check, but I hadn't realised just how much slower.

To prove it, I created a class that contains a single event, and exposed two methods to raise the event - one with a try/catch block and one with a null check
    public class Dummy
    {
        public event EventHandler SomethingHappened;

        public void RaiseWithNullCheck()
        {
            if (SomethingHappened != null)
            {
                SomethingHappened(this, EventArgs.Empty);
            }
        }

        public void RaiseInTryCatch()
        {
            try
            {
                SomethingHappened(this, EventArgs.Empty);
            }
            catch { }
        }
    }
...and a console app to repeatedly run the methods with no event handler defined
        public static void Main(string[] args)
        {
            var dummy = new Dummy();
            var stopwatch = Stopwatch.StartNew();
            var iterations = 10000;

            for (int i = 0; i < iterations; ++i)
            {
                dummy.RaiseWithNullCheck();
            }
            stopwatch.Stop();
            Console.WriteLine("Null check: {0}", stopwatch.ElapsedMilliseconds);

            stopwatch.Restart();
            for (int i = 0; i < iterations; ++i)
            {
                dummy.RaiseInTryCatch();
            }
            stopwatch.Stop();
            Console.WriteLine("Try catch: {0}", stopwatch.ElapsedMilliseconds);

            Console.ReadLine();
        }
This is a screenshot of the output - note the values are milliseconds
That's right. Sub-millisecond for the 10,000 null checks, and over 36 seconds for the 10,000 exceptions.


The remaining question is "what's the difference in timing if there is a handler defined for the event?" Obviously in this case the try/catch will be quicker because there's no overhead of checking for null before invoking the event handler. I had to massage the code a little though, before the difference was noticeable:
        public static void Main(string[] args)
        {
            var dummy = new Dummy();
            // Add an empty event handler
            dummy.SomethingHappened += (s, e) => { };

            var stopwatch = Stopwatch.StartNew();
            var iterations = 10000;

            for (int i = 0; i < iterations; ++i)
            {
                dummy.RaiseWithNullCheck();
            }
            stopwatch.Stop();

            // report in ticks, not milliseconds
            Console.WriteLine("Null check: {0} ticks", stopwatch.ElapsedTicks);

            stopwatch.Restart();
            for (int i = 0; i < iterations; ++i)
            {
                dummy.RaiseInTryCatch();
            }
            stopwatch.Stop();
            Console.WriteLine("Try catch: {0} ticks", stopwatch.ElapsedTicks);

            Console.ReadLine();
        }
Here's a typical output for this one (the timings vary a little between runs). Note that this is in ticks not milliseconds (a tick being 1/10,000 of a millisecond).
Given the tiny numbers when the event handler is defined, there isn't a good reason to rely on a try/catch when a simple null check will do.

Sunday, 16 June 2013

Make your Gadgeteer app testable with the MVP pattern

As Gadgeteer is very much about hardware, it's not always obvious how to write unit tests for the code. This post will go through the mechanics of the MVP pattern. The example app cconsists of a button and a multicolour LED; when the button is pressed, the LED displays a random colour. If you don't believe me, there's a video.

The MVP pattern

The Model-View-Presenter (MVP) pattern is designed to split the UI (View) from the business logic (Model) via a class that sends messages between the two (Presenter). In the implementation I use (Passive View) the view has little or, if possible, no logic. When an event occurs (e.g. a button press), the view raises an event which is handled by the presenter. The presenter then invokes a void method on the model. If required, the model will raise an event to signal that the work is completed. The presenter handles that event too, and calls a method on the view to cause a UI update to occur.

Here's the sequence that occurs in the example app:

The Classes

The solution consists of three projects: the Gadgeteer project, the class library and the test project.
The class library defines the classes and interfaces required to implement the MVP pattern - the model, the presenter and the view interface.
The IView interface declares an event ButtonPressed, to be handled by the presenter, and a method ShowColour that will be called by the presenter:

using Microsoft.SPOT;

namespace ButtonAndLight.Lib
{
    public delegate void ButtonPressedEventHandler(object sender, EventArgs args);

    public interface IView
    {
        // The event that the UI will raise when the button is pressed
        event ButtonPressedEventHandler ButtonPressed;
        
        //The method the presenter will call when the colour needs to change
        void ShowColour(byte r, byte g, byte b);
    }    
}

The Model class declares an event ColourChanged, to be handled by the presenter, and a method CalculateNewColour, to be called by the presenter:
using Microsoft.SPOT;

namespace ButtonAndLight.Lib
{
    public class Model
    {
        public Model()
            : this(new RandomGenerator())
        { }

        public Model(IRandomGenerator randomGenerator)
        {
            _randomGenerator = randomGenerator;
        }

        private IRandomGenerator _randomGenerator;

        // Old school event handler for the Micro Framework
        public delegate void ColourChangedEventHandler(object sender, ColourChangedEventArgs args);

        // The event that will be raised when the colour has changed
        public event ColourChangedEventHandler ColourChanged;

        // This will be called by the presenter
        public void CalculateNewColour()
        {
            var r = _randomGenerator.GetNextColourPart();
            var g = _randomGenerator.GetNextColourPart();
            var b = _randomGenerator.GetNextColourPart();

            OnColourChanged(r, g, b);
        }

        private void OnColourChanged(byte r, byte g, byte b)
        {
            if (ColourChanged != null)
            {
                ColourChanged(this, new ColourChangedEventArgs(r, g, b));
            }
        }
    }

    public class ColourChangedEventArgs : EventArgs
    {
        public byte R { get; private set; }
        public byte G { get; private set; }
        public byte B { get; private set; }
        public ColourChangedEventArgs(byte r, byte g, byte b)
        {
            R = r;
            G = g;
            B = b;
        }
    }
}
The Presenter class stitches the model and view together, by calling the relevant method when an event occurs:
using Microsoft.SPOT;

namespace ButtonAndLight.Lib
{
    public class Presenter
    {
        IView _view;
        Model _model;

        public Presenter(IView view, Model model)
        {
            _view = view;
            _model = model;

            _view.ButtonPressed += new ButtonPressedEventHandler(view_ButtonPressed);
            _model.ColourChanged += new Model.ColourChangedEventHandler(model_ColourChanged);
        }

        void model_ColourChanged(object sender, ColourChangedEventArgs args)
        {
            _view.ShowColour(args.R, args.G, args.B);
        }

        void view_ButtonPressed(object sender, EventArgs args)
        {
            _model.CalculateNewColour();
        }
    }
}
These are the Gadgeteer components:

The program class in the Gadgeteer project needs to implement the IView interface, so it can pass a reference to itself to the presenter. In this example I've also made it responsible for building the presenter:

using ButtonAndLight.Lib;
using Microsoft.SPOT.Presentation.Media;
using Microsoft.SPOT;
using Gadgeteer.Modules.GHIElectronics;

namespace ButtonAndLight
{
    public partial class Program : IView
    {
        private Presenter _presenter;

        void ProgramStarted()
        {
            _presenter = new Presenter(this, new Model());

            // Wire up handler for the the physical button press
            button.ButtonPressed += new Button.ButtonEventHandler(button_ButtonPressed);
        }

        void button_ButtonPressed(Button sender, Button.ButtonState state)
        {
            if (ButtonPressed != null)
            {
                ButtonPressed(this, EventArgs.Empty);
            }
        }

        public event ButtonPressedEventHandler ButtonPressed;

        public void ShowColour(byte r, byte g, byte b)
        {
            var colour = ColorUtility.ColorFromRGB(r, g, b);
            multicolorLed.TurnColor(colour);
        }
    }
}
All that's left now is the test class. As this is the Micro Framework, I've had to do by hand what I'd normally have done with Rhino and NUnit
using System;
using Microsoft.SPOT;

namespace ButtonAndLight.Lib.Test
{
    public class Program
    {
        public static void Main()
        {
            ButtonPressed_ExpectRandomColourGenerated();
        }

        private static void ButtonPressed_ExpectRandomColourGenerated()
        {
            // Create objects
            var view = new FakeView();
            var model = new Model(new FakeRandomGenerator());
            var presenter = new Presenter(view, model);

            // Raise event
            view.RaiseButtonPressEvent();

            // Check result
            if (view.R == 10 && view.G == 20 && view.B == 30)
            {
                Debug.Print("Success");
                return;
            }

            throw new InvalidOperationException("Failure");
        }
    }

    public class FakeView : IView
    {
        // Sensing variables
        public byte R { get; private set; }
        public byte G { get; private set; }
        public byte B { get; private set; }

        // Pretend a button's been pushed
        public void RaiseButtonPressEvent()
        {
            if (ButtonPressed != null)
            {
                ButtonPressed(this, EventArgs.Empty);
            }
        }

        #region IView interface
        public event ButtonPressedEventHandler ButtonPressed;

        public void ShowColour(byte r, byte g, byte b)
        {
            R = r;
            G = g;
            B = b;
        }
        #endregion
    }

    public class FakeRandomGenerator : IRandomGenerator
    {
        byte[] _values = new byte[] { 10, 20, 30 };
        int _valuePointer = 0;

        public byte GetNextColourPart()
        {
            return _values[_valuePointer++];
        }
    }
}
Here's a video of the hardware in action:
The code for this example can be found on GitHub at https://github.com/orangutanboy/MVPExample/

Sunday, 24 March 2013

C# syntactic sugar - the using statement

The C# using statement (as opposed to the using directive) is usually described along the lines of syntactic sugar for a try/finally block that guarantees to call the Dispose method of a class or struct that implements IDisposable. This is correct except for a subtle detail that I'll explain in a while.

Consider the following code:
using System;

public class Program
{
    public static void Main(string[] args)
    {
        using (var myDisposable = new MyDisposable())
        {
            myDisposable.DoThing();
        }
        // not allowed, myDisposable is out of scope
        //myDisposable.DoThing();
    }
}

public class MyDisposable : IDisposable
{
    public void DoThing()
    {
        // method intentionally left blank
    }

    public void Dispose()
    {
        Console.WriteLine("Disposed");
    }
}
Assuming the standard description of the using statement, this is how lines 7-12 above are expanded by the compiler:
        var myDisposable = new MyDisposable();
        try
        {
            myDisposable.DoThing();
        }
        finally
        {
            if (myDisposable != null)
            {
                ((IDisposable)myDisposable).Dispose();
            }
        }
        // not allowed, myDisposable is out of scope
        //myDisposable.DoThing();
However, the comment at line 13 is no longer correct; the variable myDisposable is now available in the whole method following its declaration.

Variable Scope

Assuming a variable is declared within the using statement, the compiler will scope that variable, by adding a set of braces around its usage. Here's the full method as it is compiled - note the braces at lines 3 and 16:
    public static void Main(string[] args)
    {
        {
            var myDisposable = new MyDisposable();
            try
            {
                myDisposable.DoThing();
            }
            finally
            {
                if (myDisposable != null)
                {
                    ((IDisposable)myDisposable).Dispose();
                }
            }
        }
        // not allowed, myDisposable is out of scope
        //myDisposable.DoThing();
    }
Of course, it is possible to live more dangerously by applying the using statement on a variable declared outside scope of the using statement:
    public static void Main(string[] args)
    {
        var myDisposable = new MyDisposable();
        using (myDisposable)
        {
            myDisposable.DoThing();
        }
        // careful, myDisposable has been disposed
        myDisposable.DoThing();
    }
... if you do that, good luck.

C# syntactic sugar - the params keyword

This is the second in what might soon be a series of blogposts on C# syntactic sugar - that is, where the language allows you to express your intent using a keyword, and the compiler restructures the code to perform how you expect it to.

The params Keyword

This post is about the params keyword. This keyword allows you to define an array parameter to a method, which can be specified by its caller as a list of values. Here's an example that demonstrates the flexible nature of the parameter:
        public static void Main(string[] args)
        {
            // All valid calls
            DoStuff();
            DoStuff(1);
            DoStuff(1, 2);
            DoStuff(new[] { 1, 2 });
        }

        private static void DoStuff(params int[] ints)
        {
            // this method intentionally left blank
        }

The IL

So, what does the compiler does with this? Here's the IL that the compiler produces for the DoStuff method, with the interesting bit highlighted:

.method private hidebysig static void DoStuff(int32[] ints) 
cil managed 
{
 .param [1]
 .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 )
 // Code size 2 (0x2)
 .maxstack 8
 IL_0000: nop
 IL_0001: ret
} // end of method Program::DoStuff

The Compiler

So, the code that the compiler is actually producing looks like this:

        private static void DoStuff([System.ParamArray] int[] ints){
            // this method intentionally left blank
        }

However if you try to compile this code, the C# compiler gives this message:


Clearly this is more than syntactic sugar, it's a requirement!

Saturday, 23 March 2013

C# syntactic sugar - the lock statement

Inspired by a talk I saw a DevWeek 2013 by Andrew Clymer, I took a look at the IL created by the C# compiler when the lock keyword is used. If you don't need an introduction to how the lock statement works, scroll down a bit and skip the first couple of C# snippets.

The Lock Statement

As a brief introduction to the lock keyword, it is used as a mechanism to allow access by a thread to a critical piece of code. Typically, this is when you have the possibility of multiple threads trampling on each other's data.

Take the sample code here:
using System;
using System.Threading;
using System.Threading.Tasks;

public class Program
{
    public static void Main(string[] args)
    {
        // Create a totaliser
        var totaliser = new Totaliser();

        // Set it off on a new thread
        Task.Run(() => totaliser.ModifyTotal());

        // Give the totaliser a chance to do something
        Thread.Sleep(100);

        // Write the current total
        Console.WriteLine(string.Format("Current value of Total: {0}", totaliser.Total));
        Console.ReadLine();
    }
}

public class Totaliser
{
    public int Total { get; private set; }

    // increment the total to 500, then down again to 0
    public void ModifyTotal()
    {
        for (var counter = 0; counter < 5000000; ++counter)
        {
            Total++;
        }
        for (var counter = 0; counter < 5000000; ++counter)
        {
            Total--;
        }
    }
}
The intent of the Totaliser class is to be able to freely increment and decrement its Total without any external visibility of what's happening. Unfortunately, because its Total property is publicly readable, the Total can be read at any stage in the increment-decrement cycle in a multi-threaded environment:

A solution to this problem is to use the lock statement, around the reads and writes to Total:
using System;
using System.Threading;
using System.Threading.Tasks;

public class Program
{
    public static void Main(string[] args)
    {
        // Create a totaliser
        var totaliser = new Totaliser();

        // Set it off on a new thread
        Task.Run(() => totaliser.ModifyTotal());

        // Give the totaliser a chance to do something
        Thread.Sleep(100);

        // Write the current total
        Console.WriteLine(string.Format("Current value of Total: {0}", totaliser.Total));
        Console.ReadLine();
    }
}

public class Totaliser
{
    private object lockObject = new object();

    private int _total;
    public int Total
    {
        get
        {
            lock (lockObject)
            {
                return _total;
            }
        }
        private set { _total = value; }
    }

    // increment the total to 500, then down again to 0
    public void ModifyTotal()
    {
        lock (lockObject)
        {
            for (var counter = 0; counter < 5000000; ++counter)
            {
                Total++;
            }
            for (var counter = 0; counter < 5000000; ++counter)
            {
                Total--;
            }
        }
    }
}
See the new lockObject at line 26, and the lock statement at lines 33 and 44.

The lock statement forces the thread to obtain a lock on the lockObject before it can proceed; if another thread has the lock, it must wait until it's been released. The result is a success:

The IL

Looking at the IL produced by the compiler, you can see the framework objects used to implement the lock:

.method public hidebysig specialname instance int32 
        get_Total() cil managed
{
  // Code size       48 (0x30)
  .maxstack  2
  .locals init ([0] bool '<>s__LockTaken0',
           [1] int32 CS$1$0000,
           [2] object CS$2$0001,
           [3] bool CS$4$0002)
  IL_0000:  nop
  IL_0001:  ldc.i4.0
  IL_0002:  stloc.0
  .try
  {
    IL_0003:  ldarg.0
    IL_0004:  ldfld      object Totaliser::lockObject
    IL_0009:  dup
    IL_000a:  stloc.2
    IL_000b:  ldloca.s   '<>s__LockTaken0'
    IL_000d:  call       void [mscorlib]System.Threading.Monitor::Enter(object, bool&)
    IL_0012:  nop
    IL_0013:  nop
    IL_0014:  ldarg.0
    IL_0015:  ldfld      int32 Totaliser::_total
    IL_001a:  stloc.1
    IL_001b:  leave.s    IL_002d
  }  // end .try
  finally
  {
    IL_001d:  ldloc.0
    IL_001e:  ldc.i4.0
    IL_001f:  ceq
    IL_0021:  stloc.3
    IL_0022:  ldloc.3
    IL_0023:  brtrue.s   IL_002c
    IL_0025:  ldloc.2
    IL_0026:  call       void [mscorlib]System.Threading.Monitor::Exit(object)
    IL_002b:  nop
    IL_002c:  endfinally
  }  // end handler
  IL_002d:  nop
  IL_002e:  ldloc.1
  IL_002f:  ret
} // end of method Totaliser::get_Total


System.Threading.Monitor

Does that mean we could use the System.Threading.Monitor class to manually implement our own lock? Yes, of course. A simple C# lock statement such as
        lock (lockObject)
        {
            DoSomething();
        }
actually gets compiled as if the C# statements were
        object obj = (System.Object)lockObject;
        System.Threading.Monitor.Enter(obj);
        try
        {
            DoSomething();
        }
        finally
        {
            System.Threading.Monitor.Exit(obj);
        }
The System.Threading.Monitor class has a couple of options when trying to grab a lock on an object, in particular the TryEnter method. This has an overload that takes a timeout value in milliseconds, which specifies how long this thread should wait to obtain the lock
        object obj = (System.Object)lockObject;
        if (System.Threading.Monitor.TryEnter(obj, 3))
        {
            try
            {
                //Do something
            }
            finally
            {
                System.Threading.Monitor.Exit(obj);
            }
        }
        else
        {
            //Do something else
        }
I don't advocate rewriting your lock statements to use the longhand versions above, but this hopefully removes a layer of abstraction between you and your multi-threaded executable.

Saturday, 24 November 2012

SignalR Demo In Pictures

Disclaimer: this demo is not intended to show best practice in C#, javascript, HTML, MVC, Visual Studio, NuGet etc etc. It is intended to use as a picture-book style guide to creating RPC communications between a web client and an ASP.Net application using SignalR.
Note: the code is not as simple as I'd hoped, but it changed to use a singleton to hold the timer, after the lack of best practice with a SignalR hub was pointed out by one of its authors.