I have been working with a WPF app on my spare time. I decided to use the WPF application framework called Caliburn. Caliburn is a lightweight framework that aids WPF and Silverlight development considerably.

Caliburn Goals:

  • Support building WPF/SL application that are TDD friendly.
  • Implement functionality for simplifying various UI design patterns in WPF/SL. These patterns include MVC, MVP, Presentation Model (MVVM), Commands, etc.
  • Ease the use of a dependency injection container with WPF/SL.
  • Simplify or provide alternatives to common WPF/SL related tasks.
  • Provide solutions to common UI architecture problems.

How does Caliburn work? A big part of WPF is it’s strong data binding functionality, however WPF control event handlers are normally defined in the control or view code behind. Caliburn lets you route using a declarative syntax control events to normal methods on your data bound presentation model.

Example:

<UserControl x:Class="GenArt.Client.Views.TargetImageView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Action.Target="{Binding}"
    >
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <Border Style="{StaticResource TargetImageBorder}">
            <Image x:Name="TargetImage" Source="..\Resources\Images\ml.bmp" Grid.Row="0" MinHeight="150" MinWidth="150"></Image>            
        </Border>
        <Grid Grid.Row="1">                            
            <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
                <Button Height="Auto" Message.Attach="[Event Click] = [Action BrowseForTargetImage] : TargetImage.Source">Select Target Image</Button>
                <Button Height="Auto" Message.Attach="[Event Click] = [Action StartPainting] : ">Start Painting</Button>
            </StackPanel>
        </Grid>
    </Grid>
</UserControl>

The first interesting Caliburn part is the attribute Action.Target="{Binding}" set on the top UserControl. This tells Caliburn that the action target is the current data binding instance (that is a presentation model). The second is the attribute Message.Attach="[Event Click] = [Action StartPainting]” set on the last Button Control. This two is a Caliburn WPF extension to declaratively attach the button click event to the method StartPainting.

The StartPainting method is defined on the class named ApplicationModel (this is the top, root data bound class for the entire WPF app).

public class ApplicationModel : PropertyChangedBase, IApplicationModel
{
  private DrawingStatsModel stats;
  private PaintingCanvasModel paintingCanvas;

  public ApplicationModel(GenArtDispatcher dispatcher) : base(dispatcher)
  {
      stats = new DrawingStatsModel(this, dispatcher);
      paintingCanvas = new PaintingCanvasModel(this, dispatcher);      
  }

        
  public ImageSource BrowseForTargetImage()
  {    
    //...
  }

  [AsyncAction(BlockInteraction = true)]
  public void StartPainting()
  {
      ///...
  }

}
As you can see Caliburn can route WPF control events to normal methods, methods can have arguments taken from other WPF controls, methods can return values that Caliburn can use to update control properties (as in the case of the BrowseForTargetImage that returns a ImageSource). This is very powerful as it almost allows for an MVC like separation between UI and the underlying presentation behavior.

Threading

Caliburn also makes async actions dead simple, if you need to have a WPF event handled in a background thread (so that it doesn't lock the UI) you only need to add a AsyncAction attribute. When the BlockInteraction parameter is set to true Caliburn will disable the WPF control that initiated the event and re-enable it when the action completes.

Almost all logic in a WPF app should be handled in a background threads however all UI interactions need to be done on the main UI thread. This can be handled easily by using a Dispatcher and a base class PropertyChangedBase.
public abstract class PropertyChangedBase : INotifyPropertyChanged
{
    protected GenArtDispatcher dispatcher;

    public PropertyChangedBase(GenArtDispatcher dispatcher)
    {
        this.dispatcher = dispatcher;
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion

    protected void RaisePropertyChanged(string propertyName)
    {
        var ChangeEvent = new ChangeEvent();
        ChangeEvent.PropertyName = propertyName;
        ChangeEvent.Source = this;
        dispatcher.Invoke(ChangeEvent);
    }

    public void RaisePropertyChangedEventImmediately(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}
This class is very important if you want your data bound WPF presentation model to be able to automatically update the UI by just raising a PropertyChanged event. The WPF infrastructure will subscribe to this event for all data bound classes. The dispatcher part is used so that the event is always raised on the UI thread, this is powerful as you can set presentation model properties without having to think about which thread you are in. Example:
private void UpdateStats()
{
    Fitness = Math.Max(0, MaxFitness - model.EvolutionProcess.CurrentFitness);
    Generations = model.EvolutionProcess.Generations;
    SelectedGenerations = model.EvolutionProcess.SelectedGenerations;
}

public double Fitness
{
    get { return fitness; }
    set
    {
        fitness = value;
        RaisePropertyChanged("Fitness");
    }
}
I was very impressed with Caliburn and how it makes WPF development easier. It allows you to move some of the code you would normally write in a code behind class or in a presenter directly into the presentation model and at the same time making this code easier to unit test. There are still scenarios that would require presenters but I think a majority of UI interactions could be handled using Caliburn in this way. There are more to Caliburn than I have mentioned in this post, so be sure to check it out yourself

Next Saturday there will be another ALT.NET unconference in Stockholm. As before this is an open conference by developers for developers. This time we will open with some lightning talks.

There are 8 lightning talks currently booked:

  1. Develop for IPhone, perspectives from a .NET developer – Christian Libardo
  2. Fight code rot – Petter Wigle
  3. Should we stop mocking – Emil Gustafsson
  4. OpenTK – Olof Bjarnason
  5. Context/Specification with MSpec – Joakim Sundén
  6. Object databases for .NET – Peter Hultgren
  7. Continues Integration a case study – Helen Toomik

The last ALT.NET conference was a great success so if you have a chance to attend be sure to sign up.

imageI have been playing with Silverlight the last few evenings, trying to port Roger Alsings "EvoLisa" application to Silverlight. This application is very cool, it uses a genetic algorithm to create an image composed of polygons that resembles a target image (that you can choose). I have been thinking of doing something like that for some time. I am very interested in artificial life and evolution simulations, especially after reading so many books on evolution by Richard Dawkins and others.

The EvoLisa application is written in WebForms and uses the GDI Graphics object to draw polygons to a bitmap surface, it then does pixel level comparisons to check how close this generated image is to the target image. This proved to be very difficult to port to Silverlight as it was not possible access the pixel buffer of Silverlight WPF controls and surfaces. After hours of googling for 2D or 3D graphícs libraries for Silverlight I gave up and implemented a standard scan line polygon fill algorithm. It is not the simplest of algorithms, especially if you want to support complex polygons.

Another issue was to to display the generated pixel buffer, this is also not possible. The only way to currently do it is through the Image control and encode you pixel buffer as a binary PNG stream which the Image control can then display.  Luckily Joe Stegman had already figured this out, so I did not need to write my own png encoder.

The last issue was also surprising, there is currently no way to read an image (client side) and access the pixels of that image. This is very easy to do server side with the Bitmap class, so instead of writing my own jpg/png decoder I send the target image to the server do the decoding there using the Bitmap class and  then return the pixels as an array of bytes. This is only required once so there is no significant performance penalty for doing this. Hopefully Silverlight 3 will add more low level graphics APIs.

You can see a screenshot to the right, this is just after two evenings of hacking, so the GUI is still very ruff. The performance is not completely on par with the WinForms version, probably because of the scan line polygon renderer is not as optimised as the GDI version (I think GDI is not hardware accelerated, right?).

Last night I took a break from the Silverlight version because I just had to try to do the same but using WPF and Direct3D to render the polygons, I got something working but I don't know the performance benefit yet as it is currently only rendering at the monitor refresh rate. You clearly notice how the Silverlight version slows down as more polygons are added, this is something that I hope the Direct3D version will eliminate.

image

I thought I would do a best of post, as many others seems to be doing it.

Most viewed posts (in order):

  1. IoC Container Benchmark - Unity, Windsor, StructureMap and Spring.NET
  2. NHibernate 2.0 Events and Listeners
  3. JQuery and Seperation of Concerns
  4. Cleanup your html with JQuery
  5. Breadcrumb menu using JQuery and ASP.NET MVC
  6. Url Routing Fluent Interface
  7. Creating a WatiN DSL using MGrammar
  8. View Model Inheritance
  9. NHibernate 2.0 Statistics and a MonoRail filter

image This was actually my first year of blogging. I have had ambitions to start blogging for years but just never got around to actually do it, mainly because of two reasons. First I thought that if I was going to start blogging I would need to setup a custom domain, fix hosting, install and configure some blogging software, etc. All that initial setup time was a road block to start blogging, I could just not find the time to do it because of a heavy work load and a lot of overtime. The second reason was that if I started blogging I wanted it to be a serious blog with good valuable content, and for that I felt that I needed to mature and gain some more experience.

But in retrospect I regret that I did not start sooner, during 2005-2007 I was a lead developer on a multi-tenant B2B system where I did some interesting work with url rewriting with WebForms (before there was much information about it), started using NHibernate and Castle Windsor, SAP integration logging using AOP, etc, in short I had a lot to blog about that could have been valuable and helpful to the .NET community.

I am very glad that I eventually started blogging because it has been a very fun, rewarding and learning experience. One of the reasons that I eventually started was the extremely easy setup that Google's blogger service provided where you could register a domain and start blogging in a mater of minutes. Google's blogger service has been pretty great as a way to get started, the only problem is the bad comment system and some lack of flexibility. I will probably be moving to a hosted solution where I can run and configure the blogging software myself during 2009 but right now it is not a top priority.

I want thank everyone who subscribes or reads this blog, I have been very pleasantly surprised by the amount of people who subscribe, it is very motivating to see that people find value in things I write and keeps me wanting to write more and better.

Merry Christmas & Happy New Year

If you have worked with DTS or SSIS packages you probably know that they can quickly become painful to work with, especially concerning versioning, logging and above all deployment.

I recently tried Ayende´s open source ETL framework RhinoETL, it tackles the ETL problem from a completely different angle compared to DTS / SSIS. At it's heart RhinoETL is a very simple .NET framework to handle an ETL process, the key components are processes, pipelines and operations. 

The process that I needed was a very simple one, namely to update a text table stored in multiple databases. The update could be of different types, for example swap every occurrence of a text translation to another and delete or update a specific row. In previously releases this was handled by writing manual update scripts. The release that I am working on currently however requires extensive changes to the texts in these tables spread over many databases and writing repetitive SQL scripts was not something that I felt doing. It felt like a good opportunity to try RhinoETL.

I began writing this input operation:

public class ReadWordList : InputCommandOperation
{
    public ReadWordList(string connectionStringName) 
      : base(connectionStringName) {  }

    protected override Row CreateRowFromReader(IDataReader reader)
    {
        return Row.FromReader(reader);                
    }

    protected override void PrepareCommand(IDbCommand cmd)
    {
        cmd.CommandText = "SELECT * FROM Wordlists";
    }
}

This is the first operation, its responsibility is to fill the pipeline with rows from the Worldlists table. The next operation is the one updating the rows. It takes as input a list of ITextChange instances that is the object that performs the change.

public class TextChangeOperation : AbstractOperation
{
    private IList<ITextChange> changes;
  
    public TextChangeOperation(IList<ITextChange> changes)
    {
        this.changes = changes;
    }

    public override IEnumerable<Row> Execute(IEnumerable<Row> rows)
    {
        foreach (var row in rows)
        {
            foreach (var change in changes)
            {
                if (change.IsValidFor(row))
                    change.Perform(row);
            }

            yield return row;
        }
    }
}

There is a class hierarchy representing the different types of text changes:

 

image

The code for the GeneralTextSwap class is very simple:

public class GeneralTextSwap : ITextChange
{
    public string TextOld { get; set; }
    public string TextNew { get; set; }

    public bool IsValidFor(Row row)
    {
        var text = ((string) row["Text"]).Trim();
        return text == TextOld;
    }

    public void Perform(Row row)
    {
        row["TextOld"] = row["Text"];
        row["Text"] = TextNew;
    }
}

The point of storing the old text value is that I have an operation after the TextChangeOperation that logs all changes to a csv file. The changes for a specific release is then just defined as static list on a static class. For example:

public class ReleaseChanges_For_Jan09
{
  public static IList<ITextChange> List;

  static ReleaseChanges_For_Jan09()
  {
    List = new List<ITextChange>()
    {            
      new GeneralTextSwap() 
      {
         TextOld = "some old link value",
         TextNew = "some new link value"
      },
      new UpdateTextRow()
      {
          DbName = "DN_NAME",
          WorldList = "USER_PAGE",
          Name = "CROSS_APP_LINK",
          TextNew = "New link value"
      },
      new DeleteTextRow()
      {
          DbName = "DN_NAME_2",
          WorldList = "SOME_PAGE",
          Name = "SOME_LINK"
      }
    }
  }
}

The above is just an example in reality I have hundreds of general and specific changes, and yes this is legacy system which handles text and links very strangely. The above code could easily be handled by a simple sql script with about the same number of lines of TSQL code, the benefit of placing this inside an ETL written in C# is that I can easily reuse the change logic over multiple databases and I also get great logging and tracing of all changes. The point of this post is to show how easy it can be to use OOP to model and abstract an ETL process using RhinoETL. Even though this ETL process i very simple it serves as good example for showing how a TSQL script, DTS or SSIS packages can be rewritten and simplified using the power of an object oriented language.

Fredrik Normén recently posted about how crosscutting concerns are implemented with boring and often duplicated code, which can be handled by using aspect oriented programming (AOP). I have used AOP with great success in previous projects to handle scenarios like logging, transactions and change tracking.

The problem with AOP is that it is not well supported or integrated into the CLR or the .NET framework and toolset. Sure there are great AOP frameworks that solve the problem via dynamic proxies, but such solutions have some big restrictions, for example they only work with virtual functions and you need to instantiate the object via a proxy creator. PostSharp handled AOP differently, it is a framework and a .NET post compiler that injects your crosscutting concerns at compile time. The problem I have found with PostSharp is that the post compile step is kind of slow, which is an issue if you do TDD (because you are constantly recompiling). Beside the compile time issue PostSharp is great tool and framework with great flexibility and power.

I was kind of disappointed that Microsoft didn't present any plan to make AOP scenarios easier and more natural on the .NET platform at this years PDC. I am not sure how, but I just feel that the AOP experience on .NET could be vastly improved :)

A couple of weeks ago I was invited to a presentation by Scott Ambler on "Scaling Agile Software Development: Strategies for Applying Agile in Complex Situations", it was an interesting talk. He showed a lot of diagrams and stats from a 2008 Agile Adoption rate survey, you can find the info here. The survey results are for example agile adoption rates, success rates, increase / decrease in code quality and costs. The problem with the survey is that it does not include any definition of what qualifies as agile. There are many different definitions on what makes software development agile, and many definitions like the manifesto (if you can even call that a definition) are very vague. I am not saying there is anything wrong with the manifesto or that agile needs to be better defined, what I am saying is that because agile can mean a lot of things to different people, and that many think they are doing agile while others might heartedly disagree, makes agile surveys like this very hard to interpret.

For example, the survey that covers modelling and documentation practices concludes that:

  • Agile teams are more likely to model than traditional teams.
  • Traditional teams are equally as likely to create deliverable documentation.
  • For all the talk in the agile community about acceptance test driven development, few teams are actually doing it in practice.
  • etc..

Without some minimum criteria for what qualifies as "doing agile" these surveys don't tell me that much. Even if I would disagree with the definition I think they would make surveys like this a lot more interesting.

I am not saying that the surveys are worthless, they do tell you something and they are a great resource for convincing management of agile practices so it is great that someone is taking the time to make them.