Saturday, June 7, 2014

Upgrading Caliburn Micro from 1.5 to 2.0 for a WPF application

I am happy to see that the Model-View-View Model (MVVM) framework Caliburn Micro is adopting the Portable Class Library approach in version 2.0, and I thought that now would also be a good time to upgrade some of my existing applications from Caliburn Micro 1.5 to version 2.0.

So far, this seems to be a painless experience, but I ran to a few issues after upgrading to 2.0 via NuGet. I'd thought I share these experiences in case someone else is facing the same issues.

The application in question is a WPF application, and it is using the Managed Extensibility Framework (MEF) for bootstrapping the application.

When trying to build the application immediately after the upgrade, I ran into a compilation error in the class definition line of my MEF bootstrapper class:

public MefBootstrapper : Bootstrapper<IShell>

error CS0246: The type or namespace name 'Bootstrapper' could not be found (are you missing a using directive or an assembly reference?)

Searching the Caliburn Micro documentation, I found that the bootstrapper base class is now called ... BootstrapperBase! And it is non-generic.

OK, this change seems easy:

public MefBootstrapper : BootstrapperBase

Hooray, the application builds! Let's run it. And wait ... and wait ... and wait ... but it never starts?

Of course! Since the bootstrapper base class is now non-generic, there is no way for the bootstrapper to know which View it should start displaying, unless it is explicitly being told which View it should display. And according to this documentation page, the fix is easy; just add

DisplayRootViewFor<IShell>();

to the overridden OnStartup method.

Let's try to run the application again. Still no sight of the root window. What is missing?

Looking more closely into the bootstrapper implementation example here, the constructor also seems to perform some initialization operation. This was not necessary with the pre-2.0 Caliburn Micro versions, most likely because the base class constructor performed this operation instead. But with 2.0 it seems to be necessary to also implement the bootstrapper constructor explicitly. According to the migration instructions here it also seems like the Start method has been renamed Initialize. So, here goes:

public MefBootstrapper() { Initialize(); }

Run the application, and ... Yes! The start-up window appears!

To summarize: when upgrading a WPF/MEF application from using Caliburn Micro version 1.5 or earlier to version 2.0, make sure the following details are in place:

  • The MEF based bootstrapper class should inherit from BootstrapperBase.
  • The root view will be displayed by calling DisplayRootViewFor<> in the overridden OnStartup method.
  • The bootstrapper default constructor must be explicitly defined, and call the Initialize() method.

EDIT

Ironically, when I started upgrading my second application I faced a completely different compilation error:

error CS1501: No overload for method 'Publish' takes 1 arguments

But this issue has a quick and easy fix, as pointed out in the migration instructions:

EventAggregator.Publish now takes an action to marshal the event. Use EventAggregator.PublishOnUIThread for the existing behaviour.


Thursday, June 5, 2014

PCL Tips and Tricks: Extension methods to the rescue

The introduction of Portable Class Libraries, PCL, considerably facilitates the sharing of functionality across managed Microsoft and Xamarin platforms. I am very enthusiastic about the PCL concept, and I have ported several .NET Framework open source projects to Portable Class Libraries. Along the way I have stumbled across various issues of making .NET Framework source code PCL compliant. In this mini-series I'll share my experiences and workarounds to facilitate the transfer to PCL for other developers.

Now, here is a very common scenario when porting .NET class libraries to PCL:

public class SomeClassToPort
{
    public static byte[] SomeMethodToPort()
    {
        var stream = new MemoryStream();
        var writer = new StreamWriter(stream);
        writer.Write("Result: {0}, {1}", 10, "Hello");
        // some more writer operations ...

        writer.Close();   // Non-existent in PCL
        stream.Close();   // Non-existent in PCL

        return stream.ToArray();
    }
}

Correct, the Close() method is not available for streams, readers or writers in Portable Class Libraries! Since the method in practice only executes Dispose(), the Close() method has been excluded from PCL. Trying to build this code yields the following error:

error CS1061: 'System.IO.MemoryStream' does not contain a definition for 'Close' and no extension method 'Close' accepting a first argument of type 'System.IO.MemoryStream' could be found (are you missing a using directive or an assembly reference?)

Dispose() is generally available in PCL, so one solution is to replace all Close() calls with Dispose(). For those wanting to avoid the hassle and maintenance issues of replacing (potentially numerous) Close() calls, there is however a workaround.


Extension methods are a perfect fit for dealing with a scenario like the above. You can just add a static class with an arbitrary name to the PCL library, with code similar to this:

public static class CloseExtensions
{
    public static void Close(this Stream stream)
    {
        stream.Dispose();
    }

    public static void Close(this TextWriter writer)
    {
        writer.Dispose();
    }
}

Now, the compiler will "translate" stream.Close() into the call CloseExtensions.Close(stream) (analogously for the StreamWriter object) and the Portable Class Library can then build successfully. The extension methods perform practically the same operations as the Close() methods in the .NET Framework. Subsequent calls to Dispose() have no effect, so this implementation should be fail-safe. 

There is also no risk of name clashes; even when the PCL library is used in a .NET application the original Close() methods and the corresponding extension methods have completely different signatures (they can just be expressed equivalently in the code).

The Close() methods are probably the most obvious examples where this extension method technique can be applied, but whenever a PCL profile is not including an instance method of one type, the same technique may be applied. Other examples from the top of my head are:
  • several methods from the Type class which are not available for Windows 8 (f.k.a. Store or Metro apps); much of this functionality has been replaced by TypeInfo instance and extension methods,
  • Stream.BeginRead, Stream.EndRead, Stream.BeginWrite and Stream.EndWrite; again not available for Windows 8 but can be simulated using extension methods.

Thursday, May 22, 2014

BioSuite and DICOM

A few years ago Dr. Julian Uzan together with Professor Alan Nahum developed a comprehensive research tool for radiobiological evaluation and optimization, called BioSuite. The tool has continuously evolved and has been made available at no extra cost for the participants of the Clatterbridge Radiobiological Modeling course that is being held (more or less) annually.

BioSuite uses input from treatment planning systems in the form of differential dose-volume histograms (DVHs). More specifically, the tool supports DVHs exported from Philips Pinnacle³ and Varian Eclipse. One format BioSuite does not support though, is DICOM!

To overcome this limitation, I have developed a simple preprocessing tool called the BioSuite Exporter. This tool allows the user to import DICOM RT Plans, RT Structure Sets and RT Doses,


and based on this data the tool computes the resulting dose volume-histograms associated with each RT Plan for the regions of interest in the RT Structure Set. The user can view the dose-volume histograms and select a subset of the DVHs for export.


Upon export, BioSuite Exporter writes absolute volume, differential dose-volume histograms for each of the selected regions-of-interest in a comma-separated value (CSV) format that can be imported by BioSuite.

For BioSuite users and others interested in obtaining a free copy of this tool, please contact me at biosuite@cureos.com.

Wednesday, May 21, 2014

Arrays are bound to get you into trouble

A few days ago I read this old yet informative blog post by Eric Lippert, about why it is good practice to avoid arrays as much as possible in your C# code. Since I am working a lot with numerical computations, I do use arrays quite a lot since they tend to be faster than class-based collections such as List<T> etc. for my particular purposes. Nevertheless, Eric's article is a good eye-opener on the caveats associated with arrays.

Ironically, I today stumbled into a serious problem involving arrays and multiple threads. It was not obvious from the start that it would lead to problems, but it certainly did.

Somewhat simplified, I had one pre-sorted key array with no duplicate entries and a collection of value arrays. The value arrays were subject to some operation from a 3rd-party library that involved sorting based on the key array. The operation on one value array would be independent of the operations on the other arrays, so I decided to parallelize the process to gain time. Schematically, the code looked like this:

double[] x = GetSortedKeyArray();

var y = new double[samples][];
for (var i = 0; i < samples; ++i) y[i] = GetValueArray(i);

Parallel.For(
    0,
    samples,
    i =>
    {
        ThirdPartyLibMethodUsingArraySort(x, y[i]);
    });

And in the 3rd-party library:

public void ThirdPartyLibMethodUsingArraySort(
    double[] x, 
    double[] y)
{
    ...
    Array.Sort(x, y);
    ...
}

Since the key array was already sorted before the first call to the 3rd-party library method, I never imagined that the Array.Sort call would cause any trouble. As long as the number of items in the key and value arrays were no more than 16, it did not either. But for 17 items and above, chaos!

If the number of items in the key and value arrays exceeded 16 and the number of value arrays were large enough (of the order of hundreds on my machine), the Array.Sort method would on some calls return duplicates in the key array x. Of course, once this error started appearing, it would continue to propagate and completely run havoc with the supposedly immutable key array.

Reading the MSDN documentation on Array.Sort, it seems like array size 16 is an important limit, where the sorting internally switch from an insertion sort algorithm to a Quicksort algorithm. The Quicksort algorithm apparently does not account for the fact that the incoming array might already be sorted and shuffles around the data. When the same array is then entering Array.Sort from another thread before the previous thread is finished, things are bound to go wrong.

What I had to do in the end was to copy the contents of x to a temporary array before each call to the 3rd-party library method, and call the method using the temporary array instead:

    {
        var tmp = new double[x.Length];
        Array.Copy(x, tmp, x.Length);
        ThirdPartyLibMethodUsingArraySort(tmp, y[i]);
    }

Take-home message: you can never be too careful with array immutability in a multi-threaded context.

Monday, May 19, 2014

3D scatter plots for WPF and Windows 8

A few years ago I was searching for an open source solution for creating 3-D scatter plots with WPF. Googling around eventually led me to this solution on CodeProject.

I have used this solution in a few of my projects since, but as far as I have been able to tell, the library has not evolved at all since the article was published in 2009.

Recently, I came across a newer 3-D drawing and charting project for WPF, namely the Helix 3D Toolkit. This project is actively developed, mainly by Øystein Bjørke, it has a vibrant user community and it is also available for Windows 8 applications (i.e. "Metro")!

First glancing at the library, I could not find any 3-D scatter plot solution. Fortunately, Øystein proposed a solution based on one of the surface plot examples in one of the sample applications. Based on Øystein's suggestion I today created a very simple 3-D scatter plot example for Helix 3D Toolkit. It looks like this:


Nothing fancy, just a proof of concept. Anyway, I made a pull request that Øystein kindly accepted, and my example is now included in the Helix 3D Toolkit example collection.

Friday, May 16, 2014

What does the _ in lambda expressions stand for?

While reading this interesting blog post by Stephen Cleary, I noticed that he used the following lambda construct in some of the code:

_ => action()

At first, I couldn't figure out what it meant, but like so many times before, Google search came to the rescue (here and here).

It turns out that this is a C# idiom. Since _ (underscore) is a valid C# identifier, it is applied here to represent an ignored identifier in a single-input-parameter lambda expression. It is the same as writing for example:

x => action()

or

(x) => action()

but it is thought to be more obvious that the parameter on the left-hand-side of the lambda expression will be ignored if an underscore identifier is used.

Now, the accepted answer on StackOverflow and the associated blog post is a little careless with the wording: this idiom is actually not applicable to parameter-less lambdas, i.e. the empty parentheses () in

() => action()

cannot be replaced with _. This would imply a mismatch between the number of input parameters in the () lambda expression (0), and _ (1). Trying to use _ with parameter-less lambdas will inevitably lead to compilation errors.

PCL Tips and Tricks: List.ForEach

The introduction of Portable Class Libraries, PCL, considerably facilitates the sharing of functionality across managed Microsoft and Xamarin platforms. I am very enthusiastic about the PCL concept, and I have ported several .NET Framework open source projects to Portable Class Libraries. Along the way I have stumbled across various issues of making .NET Framework source code PCL compliant. In this mini-series I'll share my experiences and workarounds to facilitate the transfer to PCL for other developers.

The List<T>.ForEach method is available on all managed Microsoft platforms, except one: Windows 8 (f.k.a. Windows Store or Metro). Possibly as a consequence of this, it is also not available in the Portable Class Libraries, not even when Windows 8 is not targeted.

The exact reasons for leaving out List<T>.ForEach from Windows 8 and PCL is unknown to me, but maybe the library maintainers want to discourage developers from using this method since it allows for side effects in a functional context (thanks Vagif Abilov for pointing this out). Fortunately, there is a simple replacement that should work practically always: use foreach instead!

So, instead of:

List<string> strs = ...;
strs.ForEach(str => DoSometing(str));

Use this:

List<string> strs = ...;
foreach (var str in strs) { DoSomething(str); }

I recently looked into the Clipper project, which is an open source library for clipping and offseting 2D polygons, available in several languages. I examined the C# source code, and it turned out that the author had used the List<T>.ForEach construct in his code. This was in fact the only issue preventing the C# Clipper code from being truly portable. Therefore, as a feature request I asked him to use foreach instead. This feature request was later implemented, and it is now possible to take the entire clipper.cs file and include it in any Portable Class Library.

Here are a few links about List<T>.ForEach vs. foreach: