Wednesday, 9 December 2009

C# 3.5 Batch Executor

I wanted to have something that would take a load of tasks I had to run, and run them on multiple threads to make them as efficient as possible. The first time I used this I put in 10 web service calls I needed to make. Running them through this sped them up by 50%.

Another feature of this is that it can be run on the main UI (STA) thread as it uses _manualResetEvent.WaitOne(). If you used WaitHandle.WaitAll you'd have to run on the MTA thread, which may not be convenient. I hope you'll agree it's a nice lightweight simple solution to this problem.

Usage as follows:-

var batchExecutor = new BatchExecutor();
_actions.ForEach(action => batchExecutor.AddMethodToExecute(action.Initialise));

Batch Executor class:-

public class BatchExecutor
private readonly List _actions;
private readonly ManualResetEvent _manualResetEvent;
private int _methodsLeftToExecute;

public BatchExecutor()
_actions = new List();
_manualResetEvent = new ManualResetEvent(false);

public void AddMethodToExecute(Action action)
Interlocked.Increment(ref _methodsLeftToExecute);

public void ExecuteAndWaitUntilAllComplete()
_actions.ForEach(action => ThreadPool.QueueUserWorkItem(o =>

if (Interlocked.Decrement(ref _methodsLeftToExecute) == 0)


Friday, 31 July 2009

Installing True Type fonts in a C# WPF application

I just had to install fonts into the Windows fonts folder for the application I'm developing as I wanted to use Segoe UI as it renders well in very small sizes.
I read a whole bunch of posts that used

static extern int AddFontResource(string lpszFilename);

I tried that, but it wasn't working for me so I went down the simpler path of just copying my .ttf files into the windows\fonts directory. Seems to work fine. I suspect there could be permission options if your application doesn't have the right level of trust - but that's not an issue with what I'm doing. Code is as follows. Make sure the fonts are in your solution and are being copied to the output directory of your application:

private static void InstallFonts()
var windowsDirectory = Environment.GetEnvironmentVariable("SystemRoot") + "/Fonts/";
var directoryInfo = new DirectoryInfo();

foreach(var file in directoryInfo.GetFiles())
InstallIfNotExists(file, windowsDirectory);
catch (Exception ex)
// Do something

private static void InstallIfNotExists(FileInfo file, string windowsDirectory)
var destination = new FileInfo(windowsDirectory + file.Name);

if (!destination.Exists)

Friday, 22 May 2009

Flex 3 versus Silverlight 3 in Enterprise development.

While there are an abundance of articles comparing features of Flex and Silverlight, I’ve not seen anything that compares both from the perspective of enterprise development. A lot of people who are pro Flex cite the install base, in the corporate environment this need not be a sticking point and is certainly only one of the factors that should make up your decision.

Having previously developed enterprise software on the .NET platform virtually since its inception, I’ve recently taken a break and spent a few months working on a very large Flex application.

Rich Internet Applications (RIAs) are coming of age. Abobe have made their Flash offering more developer centric with Flex. Microsoft has more recently entered the market with Silverlight.

In my view Adobe has a strong design background with a portfolio of great looking applications. Microsoft and the .NET platform have been the leaders for developing business applications, inherently making Silverlight a compelling option where business functionality is more important than look and feel.

What I aim to show with this article, through a comparison of the two technologies, is that I believe that the cost of delivering complex business functionality with Silverlight is likely to be significantly less than doing so with Flex.

The languages - C# vs. Actionscript

C# is a fully featured object oriented programming language that that is the pack leader when it comes to building business software. Actionscript was initially a scripting language for Flash player which has been redesigned in Actionscript 3. As an object oriented language it lacks many features Java or .NET developers will take for granted. Some of these differences are noted here:

· Decimal data type
· Threading support
· Generics
· Overloading method signatures
· Operator overloading
· Structs and Enums
· Private constructors
· Abstract keywords
· Lambdas and Linq
· Public getters/private setters
· Automatic Properties
· Object Initializers
· Implicit variable typing

· Dynamic classes and types
· Events in Actionscript are wired up with Strings, which can cause refactoring issues
· Internal access modifier seems slightly pointless vs. c# implementation

These missing features invariably result in impure and unnecessarily complex OO code. Casting is frequently necessary, such as when accessing collections. While it’s still technically possible to make Actionscript do what you need it to, the resultant code is inevitably hackier, less type-safe and less maintainable.

The fact that Flex is missing a decimal datatype has been a particular issue while working on finance applications. Floating point maths is frequently not accurate enough for financial calculation as can be seen here. There is a decimal implementation FXComps has produced in Flex, but when performance testing it, I found decimal divide was 3,000 times slower than float divide. Decimal multiply was 650 times slower than float multiply. Clearly decimal arithmetic if slower than floating point arithmetic in C# too, but not by these orders of magnitude as you can see here. This point alone should be enough for people who are considering creating a financial application to have serious doubts as to the suitability of Flex.

As a result of these and other shortcomings the Actionscript compiler is less effective at diagnosing issues at compile time. Compilation is slower than the C# compiler (Flex takes around 2 minutes per 100,000 lines of code). Similarly Actionscript executes more slowly than C#.

Beyond the language basics, C# has the .NET framework, a lot of which is accessible in Silverlight. In this area Flex/Actionscript has a lot of catching up to do.


MXML and XAML try to accomplish similar things. Both are markup languages for defining UI layout and animations. MXML is relatively simple and intuitive, hence most experienced developers can learn MXML quickly. On the flipside XAML is less rigid, more powerful but also
harder to learn.

Silverlight does more to encourage separation of layout and code, with partial classes offering a cleaner code-behind model. Flex allows script blocks to be placed within an MXML file, which can make UI layout files become bloated with presentation model code.

Framework components

Out of the box, Flex still has a more comprehensive component set. If you require any complex functionality with many of these components though, quality is not always consistent.

Ask any Flex developer who’d worked with the internals of the Advanced DataGrid what they think (e.g. I’ve seen people have to manually control focus using tab out events, and code to deal with scrollbar clicks in combo boxes in grids. It seems that as soon as the required functionality gets a little complex the amount of heavy lifting required in Flex grows exponentially.

Microsoft has done a good job of catching up to Flex in the Silverlight 3 feature set. However there are a few items which Silverlight lacks such as video and audio recording, and printing.

3rd party components

This is one area Microsoft does particularly well. Take a look at the current offerings from Infragistics, Syncfusion and Telerik. With these offerings you can quickly create very powerful UI’s without needing to write almost any code.

Flex has some commercial and open source offerings here also, for example ILOG Elixir from IBM. But there have been companies developing components for Microsoft for years. In Flex the offering more limited.

Patterns and Practices, Frameworks and IoC

Silverlight has a number of frameworks that can be more or less used off the shelf. e.g., Composite WPF,, Having a tried and tested off the shelf framework can greatly enhance developer productivity, not only because it establishes a repeatable pattern for writing consistent and maintainable code, but it also means a lot of the hardest code you’d have to write on a project has been written for you.

Likewise .net has several great IoC frameworks which can greatly reduce code coupling; one of my favourites is Autofac. While Actionscript is making inroads in this area, it’s significantly behind C#. Spicefactory’s Parsley is a good one, but it requires big configuration files like Spring that I’m not a huge fan of. Adobe does have LifeCycle ES which offers a lot, although sometimes with restrictions that can be a sticking point.

IDE/refactoring tools

On a large project, having a powerful and full featured IDE can save huge amounts of developer time, and therefore money. Conversely, having an underpowered, unstable and limited IDE can mean days or weeks in wasted developer time over the course of a project.

This is one area where Silverlight has an undeniable lead. Visual Studio 2008 is an awesome IDE, particularly when combined with refactoring tools like Resharper.

FlexBuilder and Eclipse however have some major shortfalls, including:

· Virtually no refactoring support. In a large codebase, try hitting Find Usages, or even Rename and you’ll have to kill your IDE and restart unless you want to wait 10 minutes to reach the out of memory error.
· The debugger. Flex Builder 3 doesn’t have basic necessities such as Conditional Breakpoints, and can only watch simple expressions. Conditional Breakpoints are coming in Flex Builder 4, but this is indicative of the gap between VS and FB –VS2010 will introduce next generation features such as Historical Debugging, while FB4 finally adds a feature that should be in any v1.0 IDE.
· No integrated Unit Test runner, as compared with MS Test or Resharper offerings.

Unit testing/mocking

The Flex unit testing capability is satisfactory. Personally I feel that projects can get too bogged down with their choice of tools in this area. However C# does have better testing options available and a much wider choice of mocking libraries.

Unit testing in C# with Visual Studio is made more efficient by integrated tools such as MS Test or Resharper – just select the test methods or classes you want to run and the results are delivered within the IDE. If a test fails, click on it and it’ll open the failing test method for you. If you need to test just a small portion of your Flex app, you need to create a separate test runner class, specify the test cases you’re targeting, recompile, and then run. If the tests fail in Flex Unit, you then have to make note of the failing tests and manually find them in the IDE.

You can get the job done in Flex, but it is just harder and takes longer.


The Flexbuilder profiling tool is very poor and there are no 3rd party alternatives. Performance statistics are taken from application start up and not from between two snapshots. Therefore if you’re trying to profile a small feature, such as what happens after a button click, you may have to wade through a minute of start code to find your button click.

As far as I know, there is currently no profiler for Silverlight, however it’s fairly simple to convert your code to a WPF app and from there you can use a number of the capable profiling tools, my favourite is dotTrace. Aqtime and DevPartner are other good options amongst a host of others.

Code samples/documentation

99% or more of what you want to do in C# has been done before. 90% or more of it has been written about on the web. The .NET developer community is thriving. If you’re stuck it generally takes five minutes of googling, or a quick look at MSDN to find your answer. On the flipside there is far less in this area in Flex and the Flex Livedocs are far less complete than MSDN.

Experience of developers

In general, Flash/Flex developers have years of experience of making good looking applications, but they don’t always write solid maintainable code. This is understandable, given the lack of enterprise Flex projects there have been to this point.

Similarly, there are a wealth of C# developers with years of experience in writing enterprise software, but it could certainly be argued that the majority of their user interfaces are poor.

Naturally there are exceptions to both cases; I’ve met some excellent Flex developers.

Install Base

Flash Player is installed on around 99% of PC’s. If you’re targeting as many users as possible with a light weight application Flex/Flash is an obvious choice.

For an enterprise application this argument may not carry much weight. Generally speaking, the client will have bought into the value of your application. Asking them to install the Silverlight plugin shouldn’t be a big issue. A lot of corporations are now including it as part of their standard desktop install.


Ultimately for me the choice comes down to what you’re trying to achieve. At this stage if looks are your only concern, then Flex probably has an edge. However if you’re looking to build complex business functionality and are concerned with value for money then I think Silverlight offers a better value proposition. This is primarily due to the resultant code base that you would have with a Silverlight project; simpler, higher level, more maintainable and robust code. As complexity increases, so does the importance of having a well structured codebase. Without this the number of bugs and regressions can grow exponentially, in turn driving up development cost.

I’m biased, I’ve developed with C# for years and I’ve enjoyed doing so. Coming over to Flex I’ve felt like I’ve been working with an arm tied behind my back. It’s frustrating to be in an environment delivering a small fraction of what you know you could be achieving. Having said that, this particular Flex application is the best looking application I’ve ever seen!

Many thanks to Marcus Whitworth, a colleague of mine, who wrote this article with me.

Monday, 27 April 2009

Flex in finance

Recently I’ve been taking a break from C# and Winforms and have been having a look at Actionscript and Flex. Looking through Flex livedocs I noticed this paragraph on their description of the Flex “Number” data type.
“Although this range of numbers is enormous, the cost of this range is precision. The Number data type uses 52 bits to store the significand, with the result that numbers that require more than 52 bits to represent precisely, such as the fraction 1/3, are only approximations. If your application requires absolute precision with decimal numbers, you need to use software that implements decimal floating-point arithmetic as opposed to binary floating-point arithmetic.”
Seems to me they’re basically saying that if you have an app where number precision is important, then don’t use Flex. While Flex can create some great looking applications, my impressions are that for financial and LOB applications – Silverlight with the pedigree of C# and the wide range of 3rd party controls and tools should be the first choice.
Update: I’ve just found a 3rd party library with a simplified implementation of the decimal data type. Naturally Flex is extensible, so it’s possible to solve most problems one way or another. However it’s nicer to have an out of the box solution where things like this are present without you having to even think about it. Moreover I tested the performance of this library and found "divide" to be 3000 times slower than float divide, and "multiply" to be 650 times slower than float multiply.

Thursday, 20 March 2008

Market Liquidity Analysis, WPF Visualisations

I recently spent a few weeks doing some data visualisations for Aleri, to demonstrate their new MLA offering. You can see some screenshots of this here.

Friday, 14 September 2007

Agile 2007, Washington DC

I recently had the good fortune to attend and present at the Agile 2007 conference. Of the people I saw presenting Robert Martin aka Uncle Bob was a superb speaker. While he was only covering the fundamentals of TDD the verve with which he presented was awesome. His mission to rid the world of “bad code” was highly entertaining as well as inspiring.
Mary Poppendieck with her talk on applying Lean Thinking to Software Development provided the most food for thought. It was my first real discovery of Lean and I found that the principles she discussed were things that rang true with my own experience. Hearing her talk on the Toyota Management System was particularly interesting.
Finally I gave my own presentation with Vivake Gupta of a paper by Nick Robinson entitled “A Technical Story”. The presentation was well received; you can download the slides from the presentation
here. Hopefully I will be giving the presentation again at the XP Day in London in November.