‘C#’ Archive

Footbreak 0.0

Thursday, October 22nd, 2009

Footbreak is an alternative GUI for the Handbrake video encoding software.  It’s goal is to make ripping television shows as simple as possible.  Simply select an ISO file (that has been decrypted with DVD Decrypter), search for the television show, select the season, and relate each episode with a DVD Title.  Once you’ve done this for all of your ISOs, specify your video settings, and walk away from your computer.

Version 0.0 is available for download (155 Kb).  Full source code is included.

Screenshots that detail the wizard process are available after the jump.

(more…)

Creating Immutable Data Classes in C#… Quickly

Tuesday, May 26th, 2009

Of late, I’ve been tempted by F#.  In reading articles and familiarizing myself with the language, there seems to be something truly interesting there, but I just don’t grok functional programming yet.

One item in particular that I’ve seen is the Record data expression.  This allows you to create an immutable data structure, like so:

type Data = { Count : int; Name : string }
let data1 = { Count = 3; Name = "Hello"; }

Then, if at a later time you wish to change Count but keep Name the same, that’s absurdly simple.

let newData = data1 with Count = 4;

C#… does not have anything like this.  To create a similar immutable data structure (including equality checking), you’d have to do something like this:

using System;
using System.Collections.Generic;

public class Data : IEquatable<Data>
{
    private readonly int mCount;
    public int Count
    {
        get { return mCount; }
    }

    private readonly string mName;
    public string Name
    {
        get { return mName; }
    }

    public Data( int aCount, string aName )
    {
        mCount = aCount;
        mName = aName;
        return;
    }


    public Data ChangeCount( int aCount )
    {
        return new Data( aCount, mName );
    }

    public Data ChangeName( string aName )
    {
        return new Data( mCount, aName );
    }

    public bool Equals( Data aOther )
    {
        bool lResult = false;
        if ( aOther != null )
        {
            lResult = ( this.Count == aOther.Count &&
                        this.Name == aOther.Name );
        }
        return lResult;
    }

    public override bool Equals( object aOther )
    {
        bool lResult = false;
        if ( aOther is Data )
        {
            lResult = Equals( aOther as Data );
        }
        return lResult;
    }

    public override int GetHashCode()
    {
        return Name.GetHashCode();
    }

    public static bool operator ==( Data aLeft, Data aRight )
    {
        return EqualityComparer<Data>.Default.Equals( aLeft, aRight );
    }

    public static bool operator !=( Data aLeft, Data aRight )
    {
        return !EqualityComparer<Data>.Default.Equals( aLeft, aRight );
    }
}

That’s a lot of work! In F#, what takes a single line takes 70 in C#. And a lot of that is nasty, crufty copy-paste code. And its easy to forget to change some things, like the Equals method.

Well, let me correct myself. That would be a lot of work… if I wrote that. But I didn’t. I just wrote this:

<#
this.Namespace = "Example";
this.ClassName = "Data";
this.ClassScope = "public";
this.ImplementINotifyProperty = false;
this.HashCodeVariable = "Name";
this.Variables = new List<Variable>()
{
    new Variable( "Count", "int", Options.Immutable | Options.ChangeMethod ),
    new Variable( "Name", "string", Options.Immutable | Options.ChangeMethod ),
};
#>
<#@ include file="DataClass.tt" #>

What is this mysterious mumbo-jumbo? That, sir (or madam), is T4: Microsoft’s Text Template Transformation Toolkit (aka a code generator). It is included in Visual Studio 2008, but it isn’t widely advertised.

My DataClass.tt file is a horribly messy template that takes in the values I listed above, and translates them into the real source code example I pasted above. Besides immutable data structures, it also supports mutable members, including support for INotifyPropertyChanged and [Member]Changed events.

I’m rather liking this so far. If it turns out that this code generation is a horrible idea, I can simply delete my .tt files and use my auto-generated .cs files from then-on with little loss.

Note that the following source code is not well documented, and is not very error tolerant. If you do something silly, chances are you’ll get an obtuse compilation error. I recommend modifying it to suit your own needs.

Data Class Code Generator Source Code (11 KB, requires Visual Studio 2008)

Presenter First: Simple Presenters

Tuesday, February 17th, 2009

While reading this article, please keep in mind that I am a novice in using Presenter First.  The following technique has not been fully tested in a production environment, and may have drawbacks that I have not anticipated.


In developing an obscenely large and complicated personal project, I have become a big fan of the Presenter First design pattern.  It ‘clicks’ with me in a way that standard Model-View-Controller and Model-View-Presenter patterns simply have not.

A quick explanation of what makes Presenter First a little different: A Presenter contains a reference to a Model interface and a View interface.  The Presenter subscribes to events on the Model and View.  The Model and View can only communicate with the Presenter by raising these events.  The Model and View do not have any direct reference to each other.  This allows you to test the Model and Presenter logic without creating a View.

I highly recommend reading the Presenter First white paper (PDF) for more details.

In my project, I’ve been trying to follow a test-driven development approach, where I write test cases (using NUnit and NMock2) before I write the actual code.

I immediately ran into issues testing event subscription and event firing.  It was difficult to test the presenter, because it required the test to fire an event owned by the mock Model.

For example, this was my presenter code for a simple History presenter. The goal is the History model fires the MessageLogged event when a new message has been added to the History log, which will prompt the Presenter to call the View’s UpdateHistory function.

public interface IHistoryModel
{
    event Action MessageLogged;
    string Message { get; }
}

public interface IHistoryView
{
    void UpdateHistory( string aMessage );
}

public class HistoryPresenter
{
    private readonly IHistoryModel mModel;
    private readonly IHistoryView mView;

    public HistoryPresenter( IHistoryModel aModel,
                             IHistoryView aView )
    {
        mModel = aModel;
        mView = aView;

        aModel.MessageLogged += OnMessageLogged;
    }

    private void OnMessageLogged()
    {
        mView.UpdateHistory( mModel.Message );
    }
}

To test this, I mocked up a Model and View with NMock2, but NMock2 does not have any direct provisions for firing events that are on mock objects. I googled around, found a way to create MockEvents, and I found myself with a terrible, complicated test case.

To be fair, the Presenter First white paper does recommend that events should not be specified in the interface itself; they should be hidden by a separate function, like ‘SubscribeMessageLogged’. I found this concept ridiculous, but I started to understand why.

After struggling with MockEvents for several days, I had a sudden epiphany that would greatly simplify everything. I changed the Model event to provide the associated data as a parameter (a behavior that was also discouraged by the white paper) and transform the Presenter into a brain-dead connector.

public interface IHistoryModel
{
    event Action<string> MessageLogged;
}

public interface IHistoryView
{
    void UpdateHistory( string aMessage );
}

public class HistoryPresenter
{
    public HistoryPresenter( IHistoryModel aModel,
                             IHistoryView aView )
    {
        aModel.MessageLogged += aView.UpdateHistory;
    }
}

And… that’s it. The Presenter doesn’t even need any additional methods outside of the constructor!

The test case is super simple as well:

[TestFixture]
public class HistoryPresenterTest
{
    [Test]
    public void Constructor()
    {
        var lMockery = new Mockery();

        var lView = lMockery.NewMock<IHistoryView>();
        var lModel = lMockery.NewMock<IHistoryModel>();

        Expect.Once.On( lModel ).EventAdd(
            "MessageLogged",
            new Action(
                lView.UpdateHistory ) );

        new HistoryPresenter( lModel, lView );

        lMockery.VerifyAllExpectationsHaveBeenMet();
    }
}

The mock Model expects that it will be connected to the View’s UpdateHistory method, and that’s all of the testing that is required. There is no need to raise the MessageLogged event, because that would simply test the functionality of C# events.

The advantage of this simple presenter is even more profound as you add new events to the Model and View. Now, all that is needed is one event, one method, one line connecting the model and view in the Presenter, and one line in the test case.

As long as each event can be tied to a corresponding method, this makes writing presenters (and their tests) extremely simple.

Simple Presenter Example Source Code (26 KB, requires Visual Studio 2008 and Nunit 2.4.8)

Playing Video in C#

Saturday, February 16th, 2008

I have been working on a WPF (Windows Presentation Framework) application using Visual C# 2008 Express. Even though I am at the Initial Optimism phase of Software Development, and my imagination is running wild, I know that nothing will probably become of this work.

The basic goal is to play videos encoded with a number of different codecs (i.e. h.264, Xvid, and DivX). So, I thought, before I went into all of the other features that this application will do, I’ll keep things simple and just play a video with the filename hard-coded.

It’s the year 2008. I have the latest Microsoft tools available. Playing a video can’t be that difficult, can it? (more…)