Archive for the ‘.NET’ Category

This Saturday past we had the Edmonton Code Camp.  I’d say things went pretty well.  It’s my understanding that some 80 people showed up to hear a variety of topics.  I kicked off the day in "Track #2" with a Introduction to Test Driven Development.  For those who are interested in my presentation / code, you can download it here.

On a project that I’m currently involved with, I’m using NHibernate and a persistance-ignorant domain. Today NHibernate threw me a "You may not dereference an collection with cascade="all-delete-orphan"" error. This kind of had me confused for a bit. What this error means is this: When you have a parent-child relation in your domain, say something like this:

public class Parent
{
     ISet<Child> _children;
}

You can’t do something like this in the parent class:

_children = new Set<Child>();

NHibernate gets angry with this and throws the aforementioned error.  It does this because the collection object that NHibernate was tracking is now gone.

What you need to do is something like:

_children.Clear();

The collection object that NHibernate is tracking is still around, so NHibernate can figure out how to persist the collection of child objects.

For those who are interested, I put the PowerPoint slides and code from my Intro to Test Driven Development and Unit Test talk at Desert Code Camp 2007 here.

The presentation is in PowerPoint 2007.  If you need me to convert it to another format (PowerPoint 2003, OpenOffice Impress), let me know.

Yesterday I was house-bound looking after a sick eight year old boy.  To help pass time, I decided to play around with my chronograph (to clarify: in this context a chronograph is a tool to help you measure the velocity of projecticles, i.e. bullets).  I happen to own a Shooting Chrony Beta Master, which you can, in theory, hook up via a serial port to your computer, download the velocities of up to 60 shots, and use that data to help you with building up some ballisitic tables for your firearm and hand-loaded ammunition.

The only problem is that the software that Shooting Chrony sells sucks.  It was probably okay ten or twelve years ago, but by today’s standards it’s lacking.

I figured that it would be neat to try and figure out how the Shooting Chrony software communications with the actual chronograph.  Typically serial port communications isn’t to complex, but figuring out what is happening on the wire isn’t necessarily the easiest thing.

To help me, I used Eltima‘s Serial Port Monitor.  This handy little application allows you to see all the traffic on a given serial port, in both directions.  You can even save a log of the traffic for later analysis.  Pretty handy little tool, well suited for just this kind of thing.

So, I started up Shooting Chrony’s application, started up Serial Port Monitor, and proceeded to download the velocities from my last trip to the range.  I then spent some quality time dissecting the log of the traffic generated, and figured out what commands I need to send to download the velocities from the chrony.  A couple more hours inside VS2008, and I had a quick and dirty WinForms app that would download the data from the chrony and display it in a simple text box.

It’s nothing fancy, but it does the trick.  The next step is to parse this data into a more meaningful format, persist it somehow, and then do a self-taught crash course in exterior ballistics for my own home grown .NET ballistics program.

Of course, I’ll try to keep this compatible with Mono:)

I just pulled this handy tip from the Rhino.Mocks mailing list:

If you would like to see more details of the expectations that you are recording and matching, try adding this in your test setup:

RhinoMocks.Logger = New TextWriterExpectationLogger (Console.Out)

You should then see all the logging messages in the Output window of Visual Studio.

(or, DataRowView How I Hate Thee)
Recently I had to enhance an ASP.NET 2.0 GridView on a Web Form.  Basically, the idea is that, if a certain field in the grid was false, I would strike-through all the text in that row.  It seems simple enough: just use the RowDataBound event of the GridView control and  apply the formating.  Wanting to make this as testable as possible, I thought that perhaps some sort of decorator class would do the trick, something like:

myGridView.RowDataBound +=
    delegate(object sender, GridRowEventArgs rowEventArgs)
    {
        InventoryPartVendorGridRowDecorator gridRowDecorator =
            new InventoryPartVendorGridRowDecorator(rowEventArgs.Row);
        gridRowDecorator.Decorate();
    }; 

Then, using the dynamic duo of NUnit and Rhino.Mocks, I would be able to test my decorator class independent of my web application.  I thought I could mock out the GridViewRow and a DataRowView, and be on my merry way.  Life would be good.  And it would have been, until the wretched DataRowView entered into the picture.

DataRowView sits pretty high up on the inheritance tree, doesn’t have any interfaces that are meaning full in this context, and it’s constructors are internal.  So, it proved to be pretty difficult to mock. 
To explain what I did, I will first show you my unit test:

[Test]
public void Decorate_InactiveVendor_TextDecorationLineThrough()
{
    MockRepository mockery = new MockRepository();
    GridViewRow mockGridViewRow = mockery.CreateMock<GridViewRow>(1, 1, DataControlRowType.DataRow, DataControlRowState.Normal);
    Hashtable dataRowViewDataItem = new Hashtable(1);
    dataRowViewDataItem.Add("Active", false);

    using (mockery.Record())
    {
        Expect.Call(mockGridViewRow.RowType)
            .Return(DataControlRowType.DataRow)
            .Repeat.Once();
        Expect.Call(mockGridViewRow.DataItem)
            .Return(dataRowViewDataItem)
            .Repeat.Once();
        mockGridViewRow.Style
            .Add(HtmlTextWriterStyle.TextDecoration, "line-through");
    }
    using (mockery.Playback())
    {
        InventoryPartVendorGridRowDecorator gridRowDecorator =
            new InventoryPartVendorGridRowDecorator(mockGridViewRow);
        gridRowDecorator.Decorate();
    }
} 


Notice what I did; I created a Hashtable and have my mockGridViewRow.DataItem return that.  In otherwords, I’m not mocking DataRowView at all, I just cut it out of the picture.  Then inside inside my InventoryPartVendorGridRowDecorator class I had to put this method:

private bool IsVendorActive()
{
    object val;
    object dataItem = _row.DataItem;
    // HACK [TO070508@1149] Because we can't mock DataRowView, we do this. 
    if (dataItem is DataRowView)
    {
        val = ((DataRowView) dataItem)[ActiveColumnName];
    }
    else if (dataItem is IDictionary)
    {
        val = ((IDictionary) dataItem)[ActiveColumnName];
    }
    else
    {
        val = null;
    }
    if (val == null)
    {
        throw new NullReferenceException("Could not find the field 'Active'.");
    }
    return TypeHelper.ConvertToBoolean(val, true);
} 


As you can see, what I ended up doing was sticking in a little "adapter" into my decorator.  Not pretty, but it works.

What would others do in this situation?

Ever have a need to convert some VB.NET code to C# (or vis versa)?  Telerik has a online code converter that seems to do the trick.

Well, I see that Billy McCafferty has updated his article NHibernate Best Practices with ASP.NET to cover NHibernate 1.2.  Excellent article, I’d suggest taking the time to read it.

As mentioned in some of my previous blog entries, I’m looking for am embedded database.  At the present, I think that I will remove SQL Server CE for now.  The biggest reason is that, as part of my pet project, the application to run on Mono as well.  So, that kind of leaves SQLite and Firebird
Now, in theory, it should matter much between the two for what I want to do.  I’m planning to use ActiveRecord for my data layer, and I see that both SQLite and Firebird are supported.  So, switching between SQLite or Firebird will be pretty minimal.  What about stored procedures, I hear you say?  Well, truth be told, in my old age, I’ve sort of drifted away from stored procedures and look at them with a suspicious eye.  So, the fact that SQLite doesn’t have stored procedures really doesn’t bother or impact me at all.
I’ll do a bit more comparison between the two, and then decided from there which database to use.

Well, as predicted something did distract me from my ActiveRecord experiment.  I got a copy of Genome Express while at an EDMUG meeting recently.  Given that my copy of Genome Express was shiny and new, I installed it and began playing.

My initialize impression is that it’s promising.  I was able to very quickly reverse engineer a SQL 2005 schema and get a heirarchical data model going.  I was able to generate working DAL code for a 12 table database inside of a couple of hours.  About 75% of this time was spent reading the documentation.

One thing I’m not to sure about is how they pretty much replace SQL. Genome has it’s own Object Query Language (OQL) for getting objects from database tables.  Given that I’ve been working with SQL for the past 12 years, I really don’t see why I need to learn a proprietary, non-standard "query language" to find data.  Doubly so with LINQ and WinFX floating around.

Another thing that kind of gives me reason to pause is, as a consultant, I don’t know how receptive clients would be to me coming in and saying that they have to spend up to $3000.00 to buy another tool.  Especially when things like ActiveRecord do the same job for free, and the source code is available.