Friday, May 3, 2013

Extension methods are cool

You are creating a vocabulary, not writing a program. Be a poet for a moment.

-- Kent Beck

When Microsoft first introduced extension methods to C#, my first reaction was "eh". I viewed them as a novelty without much use. As time has worn on, I've come to appreciate them more and more. Their biggest win for me is to add features to basic system defined types and to fix what I consider deficiencies in the .Net libraries.

Static methods that take as a parameter an instance of the class they are defined in really annoy me. One frequent irritation: string.IsNullOrEmpty(). Every time I go to use this I always start writing the variable I want to test and then realize the method is static and have to go back and insert the "string.IsNullOrEmpty" at the front. This is simply one of many, many other similar methods spread throughout the framework with this.

Shortly after extension methods were added, one day while I was again grumbling at the IsNullOrEmpty implementation, I realized this would be an easy thing to fix. About five minutes later, after figuring out the syntax for extension methods, I had something like:
public static class StringExtensions
{
     public static bool IsNullOrEmpty(this string target)
     {
          return string.IsNullOrEmpty(target);
     }
}

Now I could write tests in the much more natural (for me) "if (someString.IsNullOrEmpty())..." format. Personally I find this much easier to read.

Flush with this success I immediately added another library function I remembered from Delphi that, in my opinion, helps with readability:

public static class ObjectExtensions
{
     public static bool IsAssigned(this object target)
     {
          return target != null;
     }
}

Instead of "if (someObj != null)..." I could now say "if (someObj.IsAssigned())..."

There is a real downside I with this though: Resharper does not recognize this as a test for null and reports a possible null value warning on subsequent accesses.

I'll admit, these aren't earth-shaking, industry-changing algorithms. But in day-in, day-out coding, I find the resulting code much easier to read.

Today I threw together a couple extensions to simplify work with Points, Rectangles and ranges:
public static Extensions
{
     public static Point Center(this Rectangle bounds)
     {
          return new Point((bounds.Left + bounds.Width) / 2, (bounds.Top + bounds.Height) / 2);
     }

     public static double DistanceTo(this Point p1, Point p2)
     {
          return Math.Sqrt(Math.Pow(p1.X - p2.X, 2) + Math.Pow(p1.Y - p2.Y, 2));
     }

     public static int ConstrainTo(this int constrainedValue, int min, int max)
     {
          return Math.Max(min, Math.Min(constrainedValue, max));
     }
}

With these, I transformed a method where the purpose was lost in all the notation to one where the purpose was eminently clear. Extension methods truly enable the craftsman to apply the opening quote from Kent Beck. They easily allow the developer to introduce, at the application level, domain vocabulary to system and other 3rd party classes.

Yes, extension methods are pretty cool!

Friday, April 12, 2013

Unit Tests Not Found in VS2012 and How It Was Fixed (partially)

I am setting up a virtual machine for a new upcoming project. It will use some core libraries that have already been developed in-house with Visual Studio 2012 as the development environment. The team that developed the existing libraries did a good job to make sure there was a suite of unit tests that worked and was reasonably comprehensive. So, after I installed VS2012 and Resharper I retrieved the code from the repository, compiled it and tried to run the unit tests.

The Resharper test runner (the one I normally use) listed all the tests and reported their status as "Inconclusive. Test not run."

The test runner built into Visual Studio didn't list any tests at all. Zip. Nada. Nothing.

A web search revealed some posts indicating there was a compatibility issue between VS2012 and Resharper that was supposedly fixed in VS2012's Update 2. I downloaded and installed the update.

After this, Resharper listed all the tests and reported their status as "Pending" without doing anything further. A change, but arguably not as good as before. To exit with things pending just seems strange. At least the previous "Inconclusive" state gives a sense that something's wrong, even if it doesn't say what.

On the other hand, Microsoft's test runner... still did the same thing. Absolutely no indication that any tests even existed.

After quite a bit more searching, chanting various incantations and sacrificing not a few livestock, I stumbled upon an ancient forum post from early last summer when VS2012 was still gestating as an RC. It indicated there was a bug with unit tests when they existed on a network share.

Hmm. I wanted my VM to be just the build environment and had placed the source code on a shared folder that was mapped alongside all the other source code on the host machine's disk. I wondered what would happen if I moved the code to the C: drive.

As soon as I loaded the project from its new location on C:, Microsoft's test runner immediately found and ran the tests.

Unfortunately, Resharper's still doesn't work. It continues to set them to "pending" and never does anything else. Apparently this is a known issue that hopefully will be fixed soon.

(Hopefully I've added enough keywords to this that others will be able to find this problem and solution without having to spill blood all over the keyboard.)

Thursday, December 6, 2012

Apparent binding problems with NotSupportedException in PresentationFramework

I ran into this problem twice over the last couple weeks. Perhaps if I write an article, it'll help my future self (and just perhaps someone else) not spend so much time on it...

I put together a simple WPF form with a ListView. The ListLiew's View contained a GridView with columns bound to a POCO's properties. This was all done in XAML. In the constructor, I created an ObservableCollection to contain the objects and set it to the ListView's ItemsSource property. An event fired when interesting things happened. The event handler created the POCO object, set its properties and added it to the collection.

Everything should have worked.

However, when items were added to the collection, the debug window reported:
A first chance exception of type 'System.NotSupportedException' occurred in PresentationFramework.dll
Over the years, I've found data binding to be a challenge to get working. Part of the problem is it's mostly silent when it fails. So, data simply doesn't show up where it's expected with no indication as to why. Because of this, I assumed this is where the problem lay and spent significant time trying to figure out what was happening.

After quite a while I realized the event handler was called from a non-UI thread. I changed the line that added objects to the collection from:
ListViewDetails.Add(detailData);
to:
Dispatcher.Invoke((Action)(() =>
    ListViewDetails.Add(detailData)));
and everything worked properly. A simple solution once I realized what was wrong.

It'd be really nice if the debug window would output the exception message and not just the type. This would have told me immediately what was wrong and I wouldn't have spent so much time going down a dead-end road.

Wednesday, October 31, 2012

Sandcastle Help File Builder and error MSB4062 on Team 2008 build agents

I recently had to add a Sandcastle Help File Builder task to our automated build process. Our product consists of both .Net 3.5 projects and native C++ projects. It compiles under Visual Studio 2008 with Team 2008 build agents.

The latest version of Sandcastle is built against .Net 4.0, so, as part of its installation, I also installed the .Net 4.0 runtime. Everything worked fine in the GUI but when the build agent tried to run, it failed with:
error MSB4062: The "SandcastleBuilder.Utils.MSBuild.BuildHelp" task could not be loaded from the assembly C:\Program Files\EWSoftware\Sandcastle Help File Builder\\SandcastleBuilder.Utils.dll. Could not load file or assembly 'file:///C:\Program Files\EWSoftware\Sandcastle Help File Builder\SandcastleBuilder.Utils.dll' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded. Confirm that the <UsingTask> declaration is correct, and that the assembly and all its dependencies are available.

The UsingTask declaration appeared correct and all the dependencies seemed to be in order. I searched for quite a while and found several places purporting to have answers, but none of them worked. As I expanded my search, I finally happened upon an InfoSupport article about building VS2010 solutions with the 2008 build agent. This article described a means to fix a problem with a similar error message and, even though it wasn't related to Sandcastle, I decided to give it a try.

Short answer: it worked!!

The fix feels more like a hacky workaround than a good solution, but absent anything better, and given the fact that it allows the build to actually function properly, it currently stands.

The solution is to change a setting in a .Net configuration file.
  1. Edit %Program Files%\Microsoft Visual Studio 9.0\Common7\IDE\PrivateAssemblies\TFSBuildService.exe.config.
  2. Find the line that assigns a value to the key MSBuildPath.
  3. Change the value from an empty string to the directory of the .Net runtime that should be used, e.g. %WINDOWS%\Microsoft.NET\ Framework\v4.0.30319.
  4. Save the file.
  5. Either stop/stop the TFS build agent service or reboot the machine.

I hope that helps someone else.

Thursday, July 19, 2012

Are Coding Philosophies Irrelevant?

I recently read a rant opinion piece about how the behind the scenes part of an application is irrelevant. The author had some good points. One was, from an end user's perspective, how an application is put together is irrelevant. Another one was that success in the marketplace is not determined by which patterns are used, what the development tool-chain looks like or which language is used. I agree with all this. However he went on to say that therefore, these behind-the-scenes things are irrelevant.

To this I respectfully disagree. If the code base for an application is only to instruct the computer how to do something now, then I suppose the author might have a point. But, I think the author forgot that the end user is only one user of the application and source code is important for more than the current compile. Another very important user is the developer. Over the course of an application's lifetime, there might be many developers who will work with that code. Or there might be one who maintains it for its entire life. In either case, the source is used as much, if not more, to communicate to those reading the code what is going on as it is for the computer.

The computer just does as it's told. It doesn't care what it's told or the meaning behind the why or how. It doesn't have any concept about patterns or tool-chains or philosophies. These things are not used to communicate intent to the computer. As a simplistic example, the assignment of the sum of y and z to x, to the computer is meaningless. It doesn't care why this addition is done, or the importance of assigning the result to one place over another. The mechanics of line
x = y + z
are clear to both computer and programmer but it could mean anything. And, the meaning is irrelevant to the computer. But, to the developer, it is crucial to understanding the bigger picture.

To the computer, these two lines are equivalent to the one above.
balance = beginningBalance + deposit
newHeading = currentHeading + errorDelta
However, to a developer, assuming the variable names are accurate for the problem domain, they communicate very different things.

In the same way, other more abstract organizations of how a given piece of software is written communicate, to various degrees and with various success, important information to the developer. Patterns, tool-chains and coding philosophies are irrelevant to the compiler. To the developer, they can, if effectively used, convey information crucial to understanding the problem the software attempts to solve and the original author's vision of how to do it.

In the greater scheme of things, they are far from being irrelevant.

They are critical.


Update: I just ran across this quote I thought was appropriate:
The best programs are written so that computing machines can perform them quickly and so that human beings can understand them clearly. A programmer is ideally an essayist who works with traditional aesthetic and literary forms as well as mathematical concepts, to communicate the way that an algorithm works and to convince a reader that the results will be correct.
-- Donald E. Knuth, Selected Papers on Computer Science
And this reminded me of another quote:
You're creating a vocabulary, not writing a program. Be a poet for a moment.
-- Kent Beck

Friday, June 22, 2012

List all values of an enumeration

I'm probably late to the party on this one, but I recently discovered a cool, handy little static method tucked away in the Enum class: GetValues. It simply returns all the values of an enum type. This enables nifty things like:
public enum TestEnum
{
    Value1,
    Value2,
    Value3,
    Value4
};

public void ShowEnumValues()
{
    Enum.GetValues(typeof (TestEnum))
        .Cast<TestEnum>()
        .ToList()
        .ForEach(e => Console.WriteLine(e));
}
With this, any changes to TestEnum automatically get picked up at run-time without any additional changes to the rest of the code.

Last year, I wrote about using a dictionary to facilitate converting between an enum and human readable text. To adapt the code presented then to the above example, the following will convert all values in the enum to human readable text.
private IDictionary<TestEnum, string> enumToString =
    new Dictionary<TestEnum, string>
        {
            {TestEnum.Value1, "Value one"},
            {TestEnum.Value2, "Value two"},
            {TestEnum.Value3, "Value three"},
            {TestEnum.Value4, "Value four"}
        };

public void ShowEnumStrings()
{
    Enum.GetValues(typeof(TestEnum))
        .Cast<TestEnum>()
        .ToList()
        .ForEach(e => Console.WriteLine(enumToString[e]));
}

In the previous article, I lamented the fact that this C# solution, unlike the Pascal variant, does not provide a reliable means to check that all the values of the enumeration have a corresponding entry in the dictionary. Because of strong typing with generics, I know I can't have any thing that's not part of the enumeration in the dictionary, but I can't know I have all the values of the enumeration in the dictionary. In other words, I know I can't have any invalid values, but I can't know I have all the values.

Until I found this method. Now I can at least write an easy test case for this. While it's not quite as good as a compile time check, it does give an early, reliable means of being alerted to the problem.
[TestMethod]
public void EnsureAllEnumValuesAreInDictionary()
{
    Assert.IsTrue(
        Enum.GetValues(typeof(TestEnum))
            .Cast<TestEnum>()
            .All(type => EnumToString.ContainsKey(type)),
        "Enum value missing from enumToString dictionary");
}

Since variables of this type typically do not change from instance to instance, they can be made static so they're only instantiated once. And since many times they are only used inside a single class, they can be made private. In these cases having a unit test might be problematic, not being able to test a private field. To solve this, code similar to the above test can be put in a static constructor, throwing an exception if there's a mismatch.
private static readonly IDictionary<TestEnum, string> EnumToString =
    new Dictionary<TestEnum, string>
        {
            {TestEnum.Value1, "Value one"},
            {TestEnum.Value2, "Value two"},
            {TestEnum.Value3, "Value three"},
            {TestEnum.Value4, "Value four"}
        };

static UnitTest1()
{
    if (!Enum.GetValues(typeof (TestEnum))
             .Cast<TestEnum>()
             .All(type => EnumToString.ContainsKey(type)))
        throw new InvalidOperationException(
            "Enum value missing from enumToString dictionary");
}

Finally, if this needs to be done much, making a generic helper function will clean-up code, hiding all the casting and repetition of the type.
private static IEnumerable<T> GetEnumValues<T>()
{
    return Enum.GetValues(typeof (T)).Cast<T>();
}

[TestMethod]
public void EnsureAllEnumValuesAreInDictionary1()
{
    Assert.IsTrue(
        GetEnumValues().All(type => EnumToString.ContainsKey(type)),
        "Enum value missing from enumToString dictionary");
}

All in all, I'm pleased with finding this little nugget.

A complete VS2008 solution containing the code examples above is available on github.

Hope this helps someone else.

Monday, June 4, 2012

Functional FizzBuzz in C#

Back when Jeff Atwood first wrote about FizzBuzz, I implemented it a number of different ways in Delphi. It was an interesting exercise; I think I came up with around five different ways to implement it. I also did some performance testing and was surprised by the results. Perhaps someday I'll try to find that code and publish it. Over the years since, I've used it, or variations, in interviews and have been surprised at how many applicants it weeded out.

Recently I ran across an article listing several ways to do it in various functional languages and wondered how functional I could code it in C#. So, I fired up Visual Studio and created a new console project. I didn't think my first attempt was too bad.
namespace FunctionalFizzBuzz
{
  class Program
  {
    static string FizzBuzzResult(bool showFizz, bool showBuzz, int val)
    {
      return showFizz && showBuzz
        ? "FizzBuzz"
        : showFizz
          ? "Fizz"
          : showBuzz
            ? "Buzz"
            : val.ToString(CultureInfo.InvariantCulture);
    }

    static string GenerateFizzBuzz(int start, int end)
    {
      return Enumerable
        .Range(start, end)
        .Aggregate(new StringBuilder(), (seed, val) =>
          {
            seed.AppendLine(FizzBuzzResult(val % 3 == 0, val % 5 == 0, val));
            return seed;
          })
        .ToString();
    }

    static void Main(string[] args)
    {
      Console.WriteLine(GenerateFizzBuzz(1, 100));
    }
  }
}

However, there were a couple things I didn't like about it. First, returning the whole result as a string seemed a bit overkill and intuitively not too memory friendly. For purposes of displaying 100 lines, it's not too bad, but for a more general use case, it's not good for composition. Second, the use of Aggregate bothered me a bit. How it works is not obvious to most people when first seeing it; it's use is a bit obtuse. And concatenating a bunch of strings just felt wrong.

So, I replaced the string result with an IEnumerable. This allowed changes which I think expresses the intent better. First, the Aggregate could be be changed to a Select, clarifying the GenerateFizzBuzz method. Second, the call to Console.WriteLine to generate each output line could be passed as a parameter to an iterator function. This is an example of how the new method makes it easier to use the output for different things. Another example is to count how many "Fizz" lines there are.

static IEnumerable GenerateFizzBuzz(int start, int end)
{
  return Enumerable
    .Range(start, end-start+1)
    .Select(val => FizzBuzzResult(val % 3 == 0, val % 5 == 0, val));
}

static void Main(string[] args)
{
  var result = GenerateFizzBuzz(1, 100).ToList();
  result.ForEach(Console.WriteLine);
  Console.WriteLine("Number of Fizzes: {0}", results.Count(l => l == "Fizz"));
}

With the GenerateFizzBuzz method cleaned up some, my attention turned to the FizzBuzzResult method. I wasn't terribly happy with the multiple nested conditional statement. While functional, it seemed more computational than declarative to me. What it did was a bit opaque. I like the parameter pattern matching available in the more functional languages and wondered how I could do something similar. I couldn't think of a way to let the compiler do it and regular expressions (the only pattern matching I can think of in the .Net libraries) only works on strings. However, it seemed pretty straight forward using a data structure.

I created a dictionary with a boolean key and dictionary value. The nested dictionary also had a boolean key but with a string value. I initialized these with the four possible values. The case which should return the numeric value was set to null. Then then the result was simply the lookup value of the dictionaries unless it returned null, in which case it was the passed in value, converted to a string.

private static readonly Dictionary<bool, Dictionary<bool, string>>
  FizzBuzzMap =
    new Dictionary<bool, Dictionary<bool, string>>
      {
        {true, new Dictionary<bool, string> {{true, "FizzBuzz"}, {false, "Fizz"}}},
        {false, new Dictionary<bool, string> {{true, "Buzz"}, {false, null}}}
      };

static string FizzBuzzResult(bool showFizz, bool showBuzz, int val)
{
  return FizzBuzzMap[showFizz][showBuzz] ?? val.ToString(CultureInfo.InvariantCulture);
}

I liked the way FizzBuzzResult looked, but the initialization code for the dictionaries was a bit ugly to my eye. I tried changing it to a single dictionary containing an array of booleans as the key.

private static readonly Dictionary<bool[], string>
  FizzBuzzMap =
    new Dictionary<bool[], string>
      {
        {new[] {true, true}, "FizzBuzz"},
        {new[] {true, false}, "Fizz"},
        {new[] {false, true}, "Buzz"},
        {new[] {false, false}, null},
      };

static string FizzBuzzResult(bool showFizz, bool showBuzz, int val)
{
  return FizzBuzzMap[new [] {showFizz, showBuzz}] ?? val.ToString(CultureInfo.InvariantCulture);
}

Ah, this looked much nicer. But... it raised a key not found exception. Oops. Fail. I hypothesized the key comparison during lookup looked at the arrays as objects, rather than the values they contained, and so raised the exception. I quickly wrote a comparison class for the dictionary and passed in an instance of it.

internal class BoolArrayComparer : IEqualityComparer
{
  public bool Equals(bool[] x, bool[] y)
  {
    if (x.Length != y.Length)
      return false;
    return !x.Where((t, i) => t != y[i]).Any();
  }

  public int GetHashCode(bool[] obj)
  {
    return obj.Aggregate(0, (seed, val) => seed + val.GetHashCode());
  }
}

Sure enough, it now worked properly. So the initialization looked pretty, but at the expense of having to have this extra, ugly class floating around spoiling things. Reflecting on the prior solution with the arrays, I realized structures have slightly different semantics and might work better with comparison. I changed the boolean array to a two member structure.

internal struct FizzBuzzKey
{
  internal bool showFizz;
  internal bool showBuzz;
};

private static readonly Dictionary
  FizzBuzzMap =
    new Dictionary
      {
        {new FizzBuzzKey {showFizz = true, showBuzz = true}, "FizzBuzz"},
        {new FizzBuzzKey {showFizz = true, showBuzz = false}, "Fizz"},
        {new FizzBuzzKey {showFizz = false, showBuzz = true}, "Buzz"},
        {new FizzBuzzKey {showFizz = false, showBuzz = false}, null},
      };

static string FizzBuzzResult(bool showFizz, bool showBuzz, int val)
{
  return FizzBuzzMap[new FizzBuzzKey {showFizz = showFizz, showBuzz = showBuzz}] ?? val.ToString(CultureInfo.InvariantCulture);
}

And this worked without requiring a Comparer class. But it's quite a bit more verbose than the array notation; I really liked the succinctness of the array notation. Then I remembered structs can have constructors. I added one and this helped cut down the verbosity quite a bit.

So, in the end I finished this little exercise with the following.

namespace FunctionalFizzBuzz
{
  internal class Program
  {
    internal struct FizzBuzzKey
    {
      internal FizzBuzzKey(bool showF, bool showB)
      {
        showFizz = showF;
        showBuzz = showB;
      }

      internal bool showFizz;
      internal bool showBuzz;
    };

    private static readonly Dictionary
      FizzBuzzMap =
        new Dictionary
          {
            {new FizzBuzzKey (true, true), "FizzBuzz"},
            {new FizzBuzzKey (true, false), "Fizz"},
            {new FizzBuzzKey (false, true), "Buzz"},
            {new FizzBuzzKey (false, false), null},
          };

    static void Main(string[] args)
    {
      var results = Enumerable
        .Range(90, 11)
        .Select(val => FizzBuzzResult(val%3 == 0, val%5 == 0, val))
        .ToList();
      results.ForEach(Console.WriteLine);
      Console.WriteLine("Number of Fizzes: {0}", results.Count(l => l == "Fizz"));
    }

    private static string FizzBuzzResult(bool showFizz, bool showBuzz, int val)
    {
      return FizzBuzzMap[new FizzBuzzKey(showFizz, showBuzz)] ?? val.ToString(CultureInfo.InvariantCulture);
    }
  }
}

Final thoughts

One solution I considered during this process was to map the four values of booleans to integers and do a lookup after a conversion. Intuitively, I didn't like the approach because it added an extra level of abstraction. Levels of abstraction can be good if they clarify. However, in this case, I thought it would simply obfuscate. In spite of this, out of desire to be complete, I threw this implementation together too.

private static readonly Dictionary
  FizzBuzzMap =
    new Dictionary()
      {
        {3 /* true, true */, "FizzBuzz"},
        {2 /* true, false */, "Fizz"},
        {1 /* false, true */, "Buzz"},
        {0 /* false, false */, null},
      };

static string FizzBuzzResult(bool showFizz, bool showBuzz, int val)
{
  return FizzBuzzMap[(val%3 == 0 ? 1 : 0) + (val%5 == 0 ? 1 : 0)] ?? val.ToString(CultureInfo.InvariantCulture);
}

But it didn't work. It emitted "Buzz" in places it should have output "Fizz." But not all the time. It took me a minute or two to find it.

Can you spot the error?


The fact that 1) this was the first bug I'd produced during this exercise, 2) it wasn't immediately obvious what the problem was and 3) the need for the comments in the setup, all confirmed my suspicion this is not a good solution.

Two other things I vacillated over was whether FizzBuzzResult needed to be a separate routine and, if so, what its parameters should be. At times I'd roll it into the main routine and other times I'd pass in just the numeric value and yet other times I'd pass in the three parameters as shown. I concluded that a toy exercise like this is too small to really have a clear winner in this debate. Additional use cases provided by a larger application would probably make one of these various options a clear winner.

After going through this process, I did a web search on "C# functional FizzBuzz" and found a number of solutions including this interesting take.