# Wednesday, April 18, 2012

I'm trying my hand at making using some of our stuff a bit easier.  Today I burned some time trying to understand the project template infrastructure and the result was the creation of a couple VSIX files for installing IoC templates into Visual Studio. 

Right now it only supports desktop projects (IoC supports Windows Phone, Mono for Android, Monotouch and Compact Framework). I've also not figured out how to actually deploy the IoC and Extensions binaries with the templates, so when you create your project, the References section will contain IoC references, but they'll be broken.  Still, as a first cut it greatly simplifies setting up a new IoC UI (SmartClientApplication) or IoC Module project.

You can install the templates in one of three ways:

Wednesday, April 18, 2012 2:04:05 PM (Central Daylight Time, UTC-05:00)  #     | 
# Monday, November 21, 2011

This post is part of my "Software Development" series. The TOC for the entire series can be found here.


Let’s start this post with a couple questions.  What is an ORM and why would you use one?  If you don’t know the answer to both of these questions, then this post is for you.  If you do know the answers, feel free to skip to the next post (after I’ve created it of course).

First, let’s look at what an ORM is. And ORM is an object-relational mapping.  According to Wikipedia, which we all know is the infallible and definitive resource for all knowledge, and ORM is “a programming technique for converting data between incompatible type systems in object-oriented programming languages.”  Ok, what the hell does that mean?  My definition is a little less “scholarly.”  I’d say that

An ORM is a way to abstract your data storage into simple class objects (POCOs if you’d like) so that you don’t have to worry about all the crap involved in actually writing data fields, rows, tables and the like.  As a developer, I want to deal with a “Person” class.  I don’t want to think about SQL statements.  I don’t want to have to worry about indexes or tables or even how my “Person” gets stored to or read from disk.  I just want to say “Save this Person instance” and have it done.  THAT is what an ORM is.  A framework that lets me concentrate on solving my business problem instead of spending days writing bullshit, mind-numbing, error-prone data access layer code.

Why would we use an ORM?  I think I’ve been fairly upfront that I consider myself to be a lazy developer.  No, I don’t mean that I take shortcuts or do shoddy work, I mean that I hate doing things more than once.  I hate having to write reams of code to solve problems that have already been solved.  I’ve been writing applications that consume data for years, and as a consequence, I’ve been writing data access code for years.  If you’re not using an ORM, you probably know down in your soul that this type of work flat-out sucks.  Anything that simplifies data access to me is a win.

Of course there are other, more tangible benefits as well.  If you’re using an ORM, it’s often possible to swap out data stores – so maybe you could write to SQL Server then swap a line of two in configuration and write to MySQL or an XML file.  It also allows you to mock things or create stubs to remove data access (really handy when someone tells you that your data access is what’s slowing things down when you’re pretty sure it’s not).

I can see that some of you still need convincing.  That’s good – you shouldn’t ever just take someone’s word for it that they know what they’re doing.  Ask for proof.  Well let’s look at a case of my own code, why I built the OpenNETCF ORM and how I was recently reminded why it’s a good thing.

A couple years ago I wrote an application for a time and attendance device (i.e. a time clock) that, not surprisingly, stored data about employees, punches, schedules, etc.  on the device.  It also has the option to store it on a server and synchronize the data from clock to server, but that’s not core to our discussion today.  The point is that we were storing a fair bit of data and this was a project I did right before I create the ORM framework.  It was, in fact, the project that made it clear to me that I needed to write an ORM.

Just about a month ago the customer wanted to extend the application, adding a couple features to the time clock that required updates to how the data was stored.  It took me very little time to realize that the existing DAL code was crap.  Crap that I architected and wrote.  Sure, it works.  They’ve shipped thousands of these devices and I’ve heard no complaints and had no bug reports, so functionally it’s fine and it does exactly what was required.  Nonetheless the code is crap and here’s why.

First, let’s look at a table class in the DAL, like an Employee (the fat that the DAL knows about tables is the first indication there’s a problem):

internal class EmployeeTable : Table 
{ 
    public override string Name { get { return "Employees"; } }

    public override ColumnInfo KeyField 
    { 
        get  
        { 
            return new ColumnInfo { Name = "EmployeeID", DataType = SqlDbType.Int }; 
        } 
    }

    internal protected override ColumnInfo[] GetColumnInfo() 
    { 
        return new ColumnInfo[] 
        { 
            KeyField, 
            new ColumnInfo { Name = "BadgeNumber", DataType = SqlDbType.NVarChar, Size = 50 }, 
            new ColumnInfo { Name = "BasePay", DataType = SqlDbType.Money }, 
            new ColumnInfo { Name = "DateOfHire", DataType = SqlDbType.DateTime }, 
            new ColumnInfo { Name = "FirstName", DataType = SqlDbType.NVarChar, Size = 50 }, 
            new ColumnInfo { Name = "LastName", DataType = SqlDbType.NVarChar, Size = 50 }, 
            // ... lots more column definitions ... 
        }; 
    }

    public override Index[] GetIndexDefinitions() 
    { 
        return new Index[] 
        { 
            new Index 
            { 
                Name = "IDX_EMPLOYEES_EMPLOYEEID_GUID",  
                SQL = "CREATE INDEX IDX_EMPLOYEES_EMPLOYEEID_GUID ON Employees (EmployeeID, GUID DESC)" 
            }, 
        }; 
    } 
}

So every table for an entity derives from Table, which looks like this (shorted a load for brevity in this post):

public abstract class Table : ITable 
{ 
    internal protected abstract ColumnInfo[] GetColumnInfo();

    public abstract string Name { get; } 
    public abstract ColumnInfo KeyField { get; }

    public virtual string GetCreateTableSql() 
    { 
        // default implementation - override for different versions 
        StringBuilder sb = new StringBuilder(); 
        sb.Append(string.Format("CREATE TABLE {0} (", Name));

        ColumnInfo[] infoset = GetColumnInfo(); 
        int i; 
        for (i = 0; i < (infoset.Length - 1); i++) 
        { 
            sb.Append(string.Format("{0},", infoset[i].ToColumnDeclaration())); 
        }

        sb.Append(string.Format("{0}", infoset[i].ToColumnDeclaration())); 
        sb.Append(")");

        return sb.ToString(); 
    }

    public virtual Index[] GetIndexDefinitions() 
    { 
        return null; 
    }

    public virtual IDbCommand GetInsertCommand() 
    { 
        SqlCeCommand cmd = new SqlCeCommand(); 

        // long, manual generation of the SQL and then creating the command

        return cmd; 
    }

    public IDbCommand GetUpdateCommand() 
    { 
        SqlCeCommand cmd = new SqlCeCommand(); 

        // long, manual generation of the SQL and then creating the command 

        return cmd; 
    }

    public IDbCommand GetDeleteCommand() 
    { 
        SqlCeCommand cmd = new SqlCeCommand(); 

        // long, manual generation of the SQL and then creating the command 

        return cmd; 
    }


Sure, I get a few bonus points for using inheritance so that each table doesn’t have to do all of this work, but it’s still a pain.  Adding a new Table required that I understand all of this goo, create the ColumnInfo right, know what the index stuff is, etc.  And what happens when I need to add a field to an existing table?  It’s not so clear.

Now how about consuming this from the app?  When the app needs to get an Employee  you have code like this:

public IEmployee[] GetAllEmployees(IDbConnection connection) 
{ 
    List list = new List();

    using (SqlCeCommand command = new SqlCeCommand()) 
    { 
        command.CommandText = EMPLOYEES_SELECT_SQL2; 
        command.Connection = connection as SqlCeConnection;

        using (var rs = command.ExecuteResultSet(ResultSetOptions.Scrollable | ResultSetOptions.Insensitive)) 
        { 
            GetEmployeeFieldOrdinals(rs, false);

            while (rs.Read()) 
            { 
                IEmployee employee = EntityService.CreateEmployee();

                employee.BadgeNumber = rs.IsDBNull(m_employeeFieldOrdinals["BadgeNumber"]) 
                    ? null : rs.GetString(m_employeeFieldOrdinals["BadgeNumber"]); 
                employee.BasePay = rs.IsDBNull(m_employeeFieldOrdinals["EmployeeNumber"]) 
                    ? 0 : rs.GetDecimal(m_employeeFieldOrdinals["BasePay"]); 
                employee.DateOfHire = rs.IsDBNull(m_employeeFieldOrdinals["DateOfHire"]) 
                    ? DateTime.MinValue : rs.GetDateTime(m_employeeFieldOrdinals["DateOfHire"]); 
                employee.EmployeeID = rs.GetInt32(m_employeeFieldOrdinals["EmployeeID"]); 
                employee.FirstName = rs.GetString(m_employeeFieldOrdinals["FirstName"]); 
                employee.LastName = rs.GetString(m_employeeFieldOrdinals["LastName"]); 
                string middleInitialStr = !rs.IsDBNull(m_employeeFieldOrdinals["MiddleInitial"]) 
                    ? rs.GetString(m_employeeFieldOrdinals["MiddleInitial"]) : String.Empty; 
                employee.MiddleInitial = String.IsNullOrEmpty(middleInitialStr) ? '\0' : middleInitialStr[0]; 

                 // on and on for another 100 lines of code) 

                 list.Add(employee); 
            } 
        } 
    }

    return list.ToArray(); 
} 

Nevermind the fact that this could be improved a little with GetFields – the big issues here are that you have to hard-code the SQL to get the data, then you have to parse the results and fill out the Employee entity instance.  You do this for every table.  You change a table, you then have to go change the SQL and every method that touches the table.  The process is error prone, time consuming and just not fun.  It also makes me uneasy because the test surface area needs to be big.  How do I ensure that all places that access the table were fixed?  Unit tests help give me some comfort, but really it has to go through full integration testing of all features (since Employees are used by just about every feature on the clock).

Now what would the ORM do for me here?  Without going into too much detail on exactly how to use the ORM (we’ll look at that in another blog entry), let’s just look at what the ORM version of things would look like.

We’d not have any “Table” crap.  No SQL.  No building Commands and no parsing Resultsets.  We’d just define an Entity like this:

[Entity] 
internal class Employee 
{ 
    [Field(IsPrimaryKey = true)] 
    public int EmployeeID { get; set; }        
    [Field] 
    public DateTime DateOfHire { get; set; } 
    [Field] 
    public string FirstName { get; set; } 
    [Field] 
    public string LastName { get; set; }

    // etc. 
}

Note how much cleaner this is than the Table code I had previously.  Also note that this one class replaces *both* the Table class and the Business Object class.  So this is much shorter.

What about all of that create table, insert, update and delete SQL and index garbage I had to know about, write and maintain?  Well, it’s replaced with this:

m_store = new DataStore(databasePath);

if (!m_store.StoreExists) 
{ 
    m_store.CreateStore(); 
}

m_store.AddType<Employee>(); 

That’s it.  Adding another Entity simply requires adding just one more line of code – a call to AddType for the new Entity type.  In fact the ORM can auto-detect all Entity types in an assembly with a single call if you want.  So that’s another big win.  The base class garbage gets shifted into a framework that’s already tested.  Less code for me to write means more time to solve my real problems and less chance for me to add bugs.

What about the long, ugly, unmaintainable query though?  Well that’s where the ORM really, really pays off.  Getting all Employees becomes stupid simple.

var allEmployees = m_store.Select<Employee>();  

Yep, that’s it. There are overloads that let you do filtering.  There are other methods that allow you to do paging.  Creates, updates and deletes are similarly easy. 

Why did I create my own instead of using one that already exists?  Simple – there isn’t one for the Compact Framework.  I also find that, like many existing IoC frameworks, they try to be everything to everyone and end up overly complex.  Another benefit to the OpenNETCF ORM is that it is fully supported on both the Compact and Full Frameworks, so I can use it in desktop and device projects and not have to cloud my brain with knowing multiple frameworks.  I even have a partial port to Windows Phone (it just needs a little time to work around my use of TableDirect in the SQL Compact implementation). 

Oh, and it’s fast.  Really fast.  Since my initial target was a device with limited resources, I wrote the code for that environment.  The SQL Compact implementation avoids using the query parser whenever possible because experience has taught me that as soon as you write actual SQL, you’re going to pay an order of magnitude performance penalty (yes, it really is that bad).  It uses TableDirect whenever possible.  It caches type info so reflection use is kept to a bare minimum.  It caches common commands so if SQL was necessary, it at least can reuse query plans.

So that’s why I use an ORM. Doing data access in any other way has become insanity.

Monday, November 21, 2011 11:08:06 AM (Central Standard Time, UTC-06:00)  #     | 
# Friday, November 04, 2011

Marshaling UI access to the proper thread is a very common task in app development, yet it still tends to be a pain in the ass.  You have to check if InvokeRequired is true (well you probably don’t *have* to, but not doing it feels dirty to me) and even using an anonymous delegate tends to be verbose.  And then there are also the simple bugs that are not always easy to spot.

So, like any good developer, I stole someone else’s idea and put it into the OpenNETCF Extensions.  Now, instead of doing this:

void MyMethod()
{
    if (this.InvokeRequired)
    {
        this.Invoke(new EventHandler(delegate
            {
                MyMethod();
            }));
        return;
    }

    // do stuff with the UI
}

You do this:

void MyMethod()
{
    Invoker.InvokeIfRequired(i =>
    {
        // do stuff with the UI
    });
}

Less code.  Less potential for error.  More readable.  What’s not to like?


The OpenNETCF Extensions library is a collection of extension methods and helper classes that I find useful in a lot of different projects. It's compatible with the Compact Framework, Tirethe full framework and Windows Phone.

Friday, November 04, 2011 12:10:04 PM (Central Standard Time, UTC-06:00)  #     | 
# Monday, October 31, 2011

This post is part of my "Software Development" series.  The TOC for the entire series can be found here.


Developing good software is hard.  Really hard.  Sure, anyone can buy a book on writing software or pull up some code samples and get something that compiles and runs, but that’s not’s really developing software.  A lot of code in the wild – I’d bet a vast majority of it – just plain sucks.

It’s hard to point out where the blame lies.  It seems that most developers are environmentally or institutionally destined to write bad code. Schools teach how to write code, but not how to architect it or to follow reasonable design practices.  In the zeal for clarity, publishers churn out books, blogs and samples that show bad practices (when is it ever a good idea to access a data model from your UI event handler?).  Managers and customers alike push hard to get things done now, not necessarily done right – only to find months or years later that doing it right would have saved a boatload of time and money.  And let’s face it – many developers are simply showing up to work to pull a paycheck.  You know who they are.  You’ve no doubt worked with them in the past.  You’re probably working with them now.

I was watching Gordon Ramsay the other day and it occurred to me that he and I are alike in our own peculiar way.  I’m not saying that I see myself as the “Gordon Ramsay of Software Development” – hardly -   but we share a common trait.  Just as Gordon gets angry and starts spewing colorful language when he walks into a crap kitchen, it bothers the hell out of me to see complete idiots in my chosen field out there just making a mess of things.  When I see bad code – not necessarily minor errors, or code that could be refactored and made better – but just outright shit code that should not have occurred to a developer in the first place it pisses me off.  By the nature of my work, often getting called in only when the project is off the rails, I see it all the time. Code that, on review, a peer or mentor should have seen and said “Whoa!  There’s no way that’s going into our code base”.  Code that just makes it harder for the next person to do their job.

In an effort to simplify things for my own code, for my customers’ code as well as anyone who is willing to listen to my ravings, I’ve spent a lot of time building, testing, fixing and extending tools and frameworks that many of which I turn around and give away.  This isn’t out of altruism, no, it’s largely because I’m a lazy developer.  I hate writing the same thing twice.  When I start a project, I don’t want to spend large amounts of time building up the same infrastructure that every project needs. Building up a framework for handling UI navigation isn’t what I’d call interesting, but just about every project needs it.  Handling object dependencies and events is common.  Writing a DAL for serializing and deserializing entities is not just drudgery, I find it’s highly susceptible to errors because you end up doing a lot of copy and paste.

I have these cool tools and frameworks that I use in literally every project I work on now.  That’s great for me, but it doesn’t really help others, right?  Without reasonable documentation or explanation, only a small handful of people are going to go through the effort of getting the tools and trying to understand them – even if they are deceptively simple and could potentially save you weeks of effort. 

So I’ve decided to put together a series of blogs over the coming weeks and months that explain, hopefully in simple terms, what these frameworks do, how to use them, and most importantly, why they are worth using.  There’s nothing groundbreaking here.  I didn’t invent some new way to do things.  I’ve simply appropriated other peoples’ ideas and extended them to work in the environments that I work.

Generally I’ll be covering the following topics and frameworks:

  • Dependency Injection and Inversion of Control (using OpenNETCF IoC)
  • Event Aggregation (using OpenNETCF IoC)
  • Plug-in Architectures and interface-based programming (using OpenNETCF IoC)
  • Software features as services (using OpenNETCF IoC)
  • Data Access through an ORM (using OpenNETCF ORM)
  • Parameter Checking (using OpenNETCF Extensions)
  • Exposing data services over HTTP (using Padarn)
  • Whatever else I think of

If there’s a topic you’d like me to talk about, feel free to send me an email.  I may turn on comments here and let you post ideas, but I find that when I enable comments on my blog, I start getting more comment spam than I really want to deal with, so if comments are turned off just drop me a line.

Monday, October 31, 2011 10:11:24 AM (Central Standard Time, UTC-06:00)  #     | 
# Tuesday, August 23, 2011

We've been heavily dogfooding the IoC project (and others) lately and I finally took the time today to back-port the fixes and updates to the public code. This is being used for a solution that runs on both the desktop and the compact framework, so it's been heavily tested under both of those environments. The new release (1.0.11235) is now available on Codeplex.

Tuesday, August 23, 2011 1:23:26 PM (Central Daylight Time, UTC-05:00)  #     | 
# Thursday, September 16, 2010

I'm a big fan of writing less code or even actively deleting existing code.  Less code means less bugs, and who doesn't like shortcuts to getting around writing mind-numbing, repetitive code?  One place that I find a whole lot of repetition in my code is in calling event delegates.  Before calling an event delegate you always have to make sure it's not null, and a generally accepted practice is to make a copy of the delegate in case a subscriber unhooks the event after you've checked.  So a typical call to raise an event looks like this:

virtual void OnMyEvent(EventArgs args)
{
    var handler = MyEvent;
    if (handler != null) 
        return;

    handler(this, args);
}

Sure, it's small enough, but when you have a lot of events in a large solution, you have a whole lot of repetitive code.  Admit it - you've used CTRL-C/CTRL-V to copy this for a new event. There's got to be a better way, right? 

Well how about an extension method (well a pair, since you might have EventHandler<T>)?

public static class EventHandlerExtensions
{
    public static void Fire(this EventHandler h, object sender, EventArgs args)
    {
        var handler = h;
        if (handler == null) return;
        handler(sender, args);
    }

    public static void Fire(this EventHandler h, object sender, T args) where T : EventArgs
    {
        var handler = h;
        if (handler == null) return;
        handler(sender, args);
    }
}

Once you've done this your code becomes a simple one-liner:

virtual void OnMyEvent(EventArgs args)
{
    MyEvent.Fire(this, args);
}
Thursday, September 16, 2010 9:24:41 AM (Central Daylight Time, UTC-05:00)  #     | 
# Tuesday, August 17, 2010

I've been using the OpenNETCF.ORM library on a shipping project for a while now.  As expected, as I add features to the product, I've found problems and limitations with the ORM that I've addressed.  This morning I merged that branch back with the trunk available on Codeplex, so there's a whole new set of code available.  New features include:

  • Better handling of reference fields
  • Cascading inserts
  • Cascading deletes
  • Expanded capabilities for filtering on deletes
  • Added support for more data types, including the "object" type
  • Support for ROWGUID column

What it really needs now is a definitive sample application and documentation.  If you'd like to volunteer to work on either, I'd really appreciate it. 

Tuesday, August 17, 2010 8:29:37 AM (Central Daylight Time, UTC-05:00)  #     | 
# Monday, August 02, 2010

Today I decided to finally get around to testing out the IoC core library on Windows Phone 7.  Of course I couldn't be lucky enough for it to just compile out of the box and work. The usage of the Control class for marshaling events made it a little bit challenging, but it really didn't require a whole lot of code changes to get the code base to continue to work for the Desktop, the Compact Framework and Windows Phone.  The latest release now has a solution and a Silverlight project for WinPhone.

Why would you want to use this IoC container?  Well I use it becasue it's lightweight and because I can use the same framework everywhere.  I don't have to learn a new framework when I'm using the desktop, the CF and now the phone.  It keeps my life simpler and allows better code reuse for me.

Monday, August 02, 2010 4:35:50 PM (Central Daylight Time, UTC-05:00)  #     | 
# Wednesday, July 28, 2010

Since I use the OpenNETCF.IoC framework in just about every project I do any more, you can imagine I've created a pretty good collection of Modules and Services for common business problems I run into.  I've decided that I'm going to start putting some of these out in the public domain along with the framework and my first release is the OpenNETCF.Location module.  It's basically a module that prvides a GPS location service (GpsService to be exact). 

The default implementation is wrapper around the GPS intermediate driver, but it's not using the CF classes that Microsoft ships with the WinMo SDKs.  I looked at Microsoft's implementation and it felt really ugly to me, so I rewrote it the way it should have been done in the first place.  I don't yet have a simple sample application extracted for it (I have apps that use it, but they're too complex for a sample), but I'll add one as time permits.

The code is part of the latest change set (49823) - it's not yet in the release download - so if you want it, get it off of the Source Code page.

Wednesday, July 28, 2010 11:45:25 AM (Central Daylight Time, UTC-05:00)  #     | 

In my continuing effort to get code that I have lying around out to where it's publicly available and easy to find, I've pushed my old FTP library up to Codeplex.

Wednesday, July 28, 2010 10:45:16 AM (Central Daylight Time, UTC-05:00)  #     | 
# Monday, July 12, 2010

One drawback to the OpenNETCF.IoC framework was the difficulty in making object generation loosely coupled.  This is especially true when object types you want to create change depending on your runtime environment.  For example let's say we have an interface IAccelerometerService.  Different devices have different implementations, and the emulator and your integration tests don't even have hardware so they need a simulator.  So you create some classes that derive from the interface like this:

public interface IAccelerometerService
{
}

public class DeviceAAccelerometer : IAccelerometerService
{
// handles the accelerometer by using APIs for device A
}

public class DeviceBAccelerometer : IAccelerometerService
{
// handles the accelerometer by using APIs for device B
}

public class SimulatedAccelerometer : IAccelerometerService
{
// simulates an accelerometer (emulator, test use, etc)
}

That's all well and good, but let's say we have a generic infrastructure module that does the object creation and injection.  We don't want it to have to know about the concrete class types. They might be in separate assemblies that may not even exist - you certainly don't need (or want) to ship emulator implementation for your hardware. 

How would you handle this? The IoC framework doesn't like the following construct:

RootWorkItem.Items.AddNew<IAccelerometerService>();

Because it has no idea what concrete type you want it to create.  In this case it will throw an IOCException.

Today I added a "registration" process to the framework.  You now can do the following:

RootWorkItem.RegisterType(typeof(SimulatedAccelerometer), typeof(IAccelerometerService));

This tells the RootWorkItem that when you call to create an item of type IAccelerometerService, it should actually create an object of type SimulatedAccelerometer.

Each ManagedObjectCollection (so Items, WorkItems, SmartParts and Workspaceas) keeps track of its own Dictionary of type mappings and calling RegisterType on a given WorkItem calls the registration for each.  You can explicitly call RegisterType on any one of the collections directly and "override" an existing registration.  This means that you could have Items create one type and SmartParts create another type for the same interface.  I'm not sure when you'd ever want to do that, but I've provided for it.

Hopefully this makes the IoC framework a little more friendly, especially for testing (which is already painful enough for devices), and helps you, as a developer, develop your solutions faster without having to think about the underlying framework.

Monday, July 12, 2010 5:37:14 PM (Central Daylight Time, UTC-05:00)  #     | 
# Wednesday, June 30, 2010

I've written about your DWR before.   While deleting code is certainly a way to increase it, it's not really the entire point.  The real point is that you should be writing less code.  I'm a huge fan of writing less code - especially less of the redundant, mind-numbing, why-can't-I-hire-an-intern-to-write-this code.  You know what I'm talking about - all of that data access layer garbage that we churn out to get our class data into and out of our relational databases.

If your job is primarily working on one application, you probably don't do this a whole lot, but when you are frequently starting new projects, you find yourself getting into this tedious stuff frequently, and I really, really hate doing it.  Not only is it torture, it's highly prone to errors since it's typically a copy, paste and adjust-the-names process.  How often have you have to write code to generate your database?  Does code like this look familiar?

public Book[] GetAllBooks()
{
  var books = new List<Book>();

  using (SqlCeCommand cmd = new SqlCeCommand("SELECT * FROM Book", Connection))
  {
    using (var results = cmd.ExecuteResultSet(ResultSetOptions.Insensitive))
    {
      while (results.Read())
      {
        if (m_bookOrdinals.Count == 0)
        {
          for (int i = 0; i < results.FieldCount; i++)
          {
            m_bookOrdinals.Add(results.GetName(i), i);
          }
        }

        books.Add(new Book
        {
          BookID = results.GetInt32(m_bookOrdinals["BookID"]),
          AuthorID = results.GetInt32(m_bookOrdinals["AuthorID"]),
          Title = results.GetString(m_bookOrdinals["Title"])
        });
      }
    }
  }

  return books.ToArray();
}

Well, I finally got tired of it and decided to spend some time writing code that would free me from having to do that stuff any longer.  The result is a new, open-source project called the OpenNETCF.ORM Framework.  It's a simple, lightweight ORM that helps take care of this tedium.  For example, the above block of code now looks like this:

public Book[] GetAllBooks()
{
  return Store.Select<Book>();
}

And it pulls all of the books from the underlying SQLCE database. Yes, it's that simple.  Of course getting it to do that requires a little infrastructure work.  For this one the Book class has to look like this:

[Entity]
public class Book
{
  [Field(IsIdentity=true, IsPrimaryKey=true)]
  public int BookID { get; set; }

  [Field]
  public int AuthorID { get; set; }

  [Field]
  public string Title { get; set; }

  [Field(SearchOrder=FieldSearchOrder.Ascending)]
  public BookType BookType { get; set; }
}

But that's a small price to pay in my book.  We went from 11 lines of code (not counting brackets) to one.  Multiply that out by the number of entities, filtering logic, paging logic and all the other code you typoically write and you'd greatly decreased your LOC count.

Now I'm not saying that OpenNETCF.ORM does everything that something like the Entity Framework does.  Remember, this is a small scale framework (the core is only 14k and the SqlCE implementation adds 17k) designed for mobile and embedded systems.  It's also put together by a team of one and as a side project while doing other work.

What it does have, though, is performance. It's actually faster than using direct SQL calls in many cases because it avoid the query processor whenever it can).  It has extensibility. The source code has a full implementation for SQL CE but I've also included the skeleton for an XML implementation for anyone who wants to try their hand at it, and it would be pretty easy to do a MySQL or SQLite implementation as well.  Most important, though, is that it has my commitment.  Like the IoC framework, I've already rolled ORM into a production application.  That means that as I find problems, they are going to get fixed.  As I find features that are missing that would help me get my job done, I'm going to add them.  Bottom line is that this is not a science project that I'm doing purely for fun and that will get abandoned when I get bored with it.

So if you're as tired of writing DAL code as I am, give it a try.  If you like it, let me know, or better yet update the docs or a new implementation.

If you're ready to get started, pull down the latest code (there are no releases quite yet) and look at the test project.  There should be enough to get you going on how to use it, but if you have questions, feel free to post them.

Wednesday, June 30, 2010 10:54:38 AM (Central Daylight Time, UTC-05:00)  #     | 
# Monday, June 14, 2010

I just checked in another update to the OpenNETCF.IoC framework.  If you've used the framework for event aggregation you're probably aware that an EventSubscrition can set the ThreadOption to "UserInterface" but that had no effect.  We'll I've fixed that - at least partially.  Up until now I couldn't figure a way to wire up any arbitrary delegate without the availability of Emit. Today I had the idea that implementing a known subset could be done without Emit, but instead hard-coding a class into the framework that handles doing the Invoke call to get the event into the proper context.  Now if your event handler is of type EventHandler or, more importantly, EventHandler<T> (meaning that if you use the GenericEventArgs already present in the framework, you're all set), you don't have to call InvokeRequired and Invoke any longer - the framework handles it for you (and I really wish I'd done that 6 months ago - would've saved me a lot of headache).

Monday, June 14, 2010 6:10:10 PM (Central Daylight Time, UTC-05:00)  #     | 
# Friday, May 28, 2010

Every time we start a new project using our Padarn Web Server, I always like to see if we can improve the server's capabilities to make our job a little easier.  On the last project that turned into adding custom IHttpHandler support so we could easily serve up REST-based web services.

Well we started a new project last week, and unlike the last one, this one is UI-focused (the last one used Padarn strictly for services).  With that in mind, I went about looking at how to improve and simply building pages.

Of course I came back to our lack of support for server controls.  I did a little more playing and decided once again that it's a gigantic amount of work and it requires a boatload of RegEx and string manipulation - not necessarily a recipe for success on a low-memory, slow-CPU Windows CE device.

Still, there had to be other thing that full-blown ASP.NET offers that would be reasonable to add and that would help.  The existing samples we'd created in the past used overrode Page_Load method and then went about doing Response.Writes to emit page code.  The first time I did it I found it painful, so I created a class library that had objects for a lot of the basic HTML constructs and used that to at least help in generating well-formed code.

Still, I didn't really like the object model - it was still way too verbose - and it wasn't really like what anyone does on the desktop.  Additionally, rending in Page_Load really didn't feel right.

So I started looking around and found that the ASP.NET Page class provides a Render method.  That sounds a lot more like where I should be, oh maybe *rendering* a page.  Of course it required implementing the HtmlTextWriter, but that wasn't too terrible.

Once I implemented the Render method and started using the HtmlTextWriter, I quickly concluded that it, too, really sucked for generating page code.  It's just crazy verbose, it doesn't read anything like the page you're attempting to render and it's got things that just feel plain wrong (like having to add attributes before the tag they apply to? WTF is that?).

So I started looking at how ASP.NET developers who render their own controls with this monstrosity got around in.  It turns out that there is a pretty nice fluent interface to the HtmlTextWriter available on CodePlex.  It was missing a lot of stuff that I needed (and had a load of non-HtmlTextWriter stuff I didn't need), but it was a great start.  So after expanding the object model there I can now render a page in something that doesn't give me quite so much heartburn.

What originally looked like this:

protected override void Page_Load(object sender, EventArgs e)
{
  Response.Write(DoctypeTags.XHTML1);

  Response.Write("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
  Response.Write("<head>");
  Response.Write("<link rel=\"stylesheet\" type=\"text/css\" href=\"css/mystyle.css\" />");
  Response.Write("</head>");

  Response.Write("<body>");

  Response.Write("<h1>");
  Response.Write("Hello World!");
  Response.Write("</h1>");

  Response.Write("</body>");
  Response.Write("</html>");
  Response.Flush();
}

Ends up looking more like this:

protected override void Render2(HtmlTextWriter writer)
{
  writer.Write(DoctypeTags.XHTML1);

  writer
    .Tag(HtmlTextWriterTag.Html, t => t["xmlns", "http://www.w3.org/1999/xhtml"])

      .Tag(HtmlTextWriterTag.Head)
        .StylesheetLink("/css/mystyle.css")
      .EndTag() // head

      .Tag(HtmlTextWriterTag.Body)
        .H1("Hello World!")
      .EndTag() // body
    .EndTag(); // html
}

And it gets much cleaner looking the larger the page is.  I also find I'm doing a lot less searching for where I malformed my HTML.

I think the next Item I'll look into is the __doPostBack Javascript method that IIS injects into pretty much every page.  It's probably the next incremental step toward better productivity.

Friday, May 28, 2010 6:43:06 PM (Central Daylight Time, UTC-05:00)  #     | 
# Thursday, May 27, 2010

Introduction

Some time ago I explained to one of my friends the benefits of using GetInvocationList when raising events over simply calling the event handler delegate directly.  He understood my explanation and they implemented their events using the pattern.

Well today he was asked by another engineer why the code is always using "this GetInvocationList call for events" and so I figured I could revisit the explanation a little more formally both for his benefit as well as the other 3 people that read this blog.

The Challenge of Multicast Delegates

An event is, for all intents and purposes, a muticast delegate.  What that means is that you can have 0:n listeners listening for that event.  When you get you call the delegate directly in your code, the CLR iterates through all of the listeners and calls them for you without you having to know how many listeners there are.  This is all well and good *when things go right* but the problem is that things don't always go right.  This is especially the case if you're writing a class that will be consumed by someone else and you have no control over what their handler might be doing.

What happens if a handler throws an exception?  Well the CLR stops iterating through delegates an raises that exception to the method that invoked the delegate.  All handlers that were in the delegate list after the exception *will never see the event*.

To be a little more concrete, let's look at an example.

Let's say we have a class that publishes an event.  We'll call it Publisher and name the event the very original name "MyEvent".

class Publisher
{
  public event EventHandler MyEvent;

  public Publisher()
  {
  }
}

Now when we want to raise that event, the most common thing I've seen is to just get a handler and call it (ensuring it's not null).  Something like this:

public void RaiseDirect()
{
  var handler = MyEvent;
  if (handler == null)
  {
    Console.WriteLine("No listeners");
    return;
  }

  try
  {
    handler(this, null);
  }
  catch(Exception)
  {
    Console.WriteLine("A listener threw an exception in its handler");
  }
}

Now let's look at where this falls down.  First let's create a couple listeners.  Good ones that successfully run an EventHandler and bad ones that throw an exception in their EventHandler:

class Listener
{
  static int m_number = 0;

  public Listener()
  {
    m_number++;
    Name = this.GetType().Name + m_number.ToString();
  }

  public string Name { get; private set; }
}

class GoodListener : Listener
{
  public GoodListener(Publisher publisher)
  {
    publisher.MyEvent += new EventHandler(publisher_MyEvent);
  }

  void publisher_MyEvent(object sender, EventArgs e)
  {
    Console.WriteLine(string.Format("{0} handled event", Name));
  }
}

class BadListener : Listener
{
  public BadListener(Publisher publisher)
  {
    publisher.MyEvent += new EventHandler(publisher_MyEvent);
  }

  void publisher_MyEvent(object sender, EventArgs e)
  {
    Console.WriteLine(string.Format("{0} threw in handler", Name));
    throw new Exception("failure");
  }
}

Now let's wire these up and see what happens with some quick test code:

List<Listener> m_listeners = new List<Listener>();

Publisher publisher = new Publisher();

for (int i = 0; i < 5; i++)
{
  if (i % 3 == 0)
  {
    m_listeners.Add(new BadListener(publisher));
  }
  else
  {
    m_listeners.Add(new GoodListener(publisher));
  }
}

Console.WriteLine("Direct event");
Console.WriteLine("------------");
publisher.RaiseDirect();

We run this and we get the following:

directevent.png

You'll see that only 1 handler (a bad one) ran.  It threw an exception and no one else knew jack about the event.

Using the Invocation List

Now let's look at how we get past this.  The EventHandler delegate exposes a method called GetInvocationList which returns an array of all of the delegates.  Using this we can iterate across all of the EventHandlers manually.  Something like this:

public void RaiseIterative()
{
  var handler = MyEvent;
  if (handler == null)
  {
    Console.WriteLine("No listeners");
    return;
  }

  foreach (EventHandler h in handler.GetInvocationList())
  {
    try
    {
      h(this, null);
    }
    catch(Exception)
    {
      Console.WriteLine("A listener threw an exception in its handler");
    }
  }
}

Now when we run our test code, raising the events through the iterative handling routine, we get this

iteratedevent.png

As you can see, *all* of the EventHandlers ran.

Conclusion

We can't always control the code that other developers write (I'd argue we can't even really control our own code).  If you're writing code that's raising events to be consumed by any handlers (and most events I've seen are meant to be consumed) then you need to think defensively.  How can you protect your consumers from one another's bad behavior?  By coding defensively, that's how.  Simple patterns like calling GetInvocationList is a good defensive strategy.  It not only makes your own code more solid, it prevents those support calls from developers complaining that your assembly isn't raising events, even when they were the root cause.

Get the full source code here: InvocationTest.zip (27.37 KB)

Thursday, May 27, 2010 2:59:54 PM (Central Daylight Time, UTC-05:00)  #     | 
# Wednesday, November 25, 2009

Long, long ago I wrote an article for MSDN on creating a multi-Form CF application that used a Form Stack.  Since we all tend to grow and learn as developers, we find different ways to do things (and generally we scoff at code we wrote years before as inferior crap). 

Well Peter Nowak is giving a presentation of the OpenNETCF.IoC framework next week and I decided that a sample of using the UI elements of the library (Workspaces, SmartParts, etc) might be handy and so I decided to rewrite the Form Stack following my latest thinking.  Basically the idea is to allow a user to navigate through Forms (actually Views - you are separating your Views from the Model, right?) like you would on a browser.  You can move forward and back as well as "adding" to the end or top of the stack.  We also don't want to be constantly creating new instances of the View classes because we like applications to perform well.

Here's a look at the new application (yes, I know it's "developer ugly" but this is about architecture, not aesthetics):

You can see the stack in the list, and our current position is noted by the asterisk.  "Fwd" will move down to View B, "Back" will move up to Form A, or you can push a new A or B onto the stack at the current location, which will truncate everything currently above (after) the current position.  Again, think of how your browser works.  It's important to know, also, that there are only 3 total View instances created at this point (one of each specific type).

The code for this application is in source control over at the OpenNETCF.IoC Framework Codeplex site.  You'll notice it's called FormStackCS, hinting that there may be a FormStackVB coming.  If you'd like to volunteer to do that port, by all means let me know (meaning don't hold your breath waiting for me to do it).

Wednesday, November 25, 2009 11:21:11 AM (Central Standard Time, UTC-06:00)  #     | 
# Wednesday, June 24, 2009

It took a long time to get here, but we've finally release what I'm calling the version 1.0 (pervious version were 0.9.x) release of the OpenNETCF.IoC Framework.  In case you've not been tracking this project, it is a public-domain-licensed (you can't get any more free and unencumbered than that) framework that provides both inversion of control and dependency injection for .NET Compact Framework applications (it can be used on the desktop as well).  It's roughly modelled after Microsoft's SCSF and CAB frameworks, but it's scaled down and optimized for running on mobile and embedded devices, plus I "fixed" stuff that I think the SCSF got wrong (like having a static, globally available RootWorkItem and the ability to insert IMessageFilters into the application's message pump).

This framework is in use in a couple of commercial applications already, so it's been pretty heavily tested and vetted.  I still want to add a few more features as well and go back through it looking for performance optimizations, but it certainly has enough features to be used in applications today.

This release also ships with a full-blown, real-world sample application, not just the typical "Northwind" type of application.  The sample is called WiFiSurvey and it can be used to survey WiFi AP coverage of a site and to monitor associated AP changes as well as network addressability of a device.

WiFiSurvey has a Configuration service, a SQL CE 3.5-backed Data Access Layer, an Infrastructure module and a an application shell all of which are fully decoupled from one another and that are all loaded dynamically using an XML definition file.  The shell makes use of both a DeckWorkspace and a TabWorkspace, showing you not just how to use them, but also how to create your own workspaces if need be.

The WiFiSurvey application has a single source base for all target platforms and has been tested on the following platforms:

  • ARM-based CE 6.0 with a 320x240 (landscape) display.
  • Pocket PC 2003 240x320 (portrait)
  • WinMo 5.0 240x320 (portrait and landscape)

The IoC framework has additionally been tested on x86-based CE 5.0 and CE 6.0 devices.

As a side note, the WiFiSurvey sample application is also a good example of using the OpenNETCF Smart Device Framework for getting wireless information.

Wednesday, June 24, 2009 1:54:24 PM (Central Daylight Time, UTC-05:00)  #     | 
# Monday, March 30, 2009

I've pushed up a set of fixes for the OpenNETCF.IoC Framework. See the Project Site for details on what changed.

Monday, March 30, 2009 3:33:24 PM (Central Standard Time, UTC-06:00)  #     | 
# Monday, March 16, 2009
I've finally got the CodePlex project set up for the OpenNETCF.IoC framework, so that is now the "official" place to get it.  One thing to note is that my original intent was to publish under a Public Domain license, but evidently it's not one of the options in CodePlex (I'll email them and see what I can do about that).  In the meantime I set it to what looks to be the most permissable license they had - the MIT license.

Monday, March 16, 2009 3:15:30 PM (Central Standard Time, UTC-06:00)  #     | 
# Wednesday, March 11, 2009

Articles in this series
Part I: Inversion of Control and the Compact Framework
Part II: The OpenNETCF.IoC Framework: Items and Services
Part III: The OpenNETCF.IoC Framework: Events (this article)
Part IV: The OpenNETCF.IoC Framework: Performance (TBD)

Downloads
Code and Sample available through CodePlex.


In the Part II of this series we looked at how the OpenNETCF.IoC framework provides dependency injection for the lists of Items and Services and if you look at the sample application that ships with the framework you’ll see that the application creates and displays 3 separate Froms and a Service without a single call to the ‘new’ operator anywhere in the solution and, more importantly, without having to pass object references around yourself.

While I find that both fun and useful, the real thing I love about the OpenNETCF.IoC framework (and the SCSF that it’s modeled after) is the implementation of inversion of control through event publication and subscription.

A New Paradigm for Events

In the traditional managed development, an object exposes an event, something like this:

public event EventHandler OnMyEvent;

And when a subscriber wants to get notified of that event, they add a handler delegate like this:

publisherInstance.OnMyEvent += HandleOnMyEvent;

void HandleOnMyEvent(object sender EventArgs args)
{
  // do something useful here
}

That’s all well and good, but in my mind there are two problems with it. First it’s just plain ugly.  I have code in two places, first to attach the event, and second to handle it.  I like to keep related code close together, and this coupling of attaching the handler and the delegate implementation makes that hard (unless you use anonymous delegates). 

The second, and far worse, problem is that it requires that you have the instance of the event publisher to wire this up.  In some cases this is fine, but in others it seems rather pointless.  Let’s go back to one of our early examples of People and Cars and extend it ever so slightly.  We’ll add an event to the Car class :

public delegate void WreckHandler(ICar car);

class Car : ICar
{
  public event WreckHandler OnWreck;
}

And let’s say we have a specialized person – a PoliceOfficer – and he’d like to know any time there is a car wreck.

class PoliceOfficer : Person
{
  public void HandleCarWreck(ICar car) {…}
}

How would we wire this up?  Should we pass every Car instance in town to the officer so he can wire up the event?

class PoliceOfficer : Person
{
  public void HandleCarWreck(ICar car) {…}

  public void WatchCar(ICar car)
  {
    car.OnWreck += HandlerCarWreck;
  }
}

When would we call this?  Every time a Car instance is created?  How would the new Car instance know about the PoliceOfficer?  What if we have multiple Officers?  You can see that this gets real ugly, real fast.  Wouldn’t it be nice if any PoliceOfficer could just listen for the OnWreck event globally and any time any Car instance raised it, he would get notified?  Well that’s what the OpenNETCF.IoC framework’s eventing structure is all about. You publish and subscribe to events based on a unique string name for the event of interest.

So for the event publisher, the Car in this case, we use the same event definition but we add a simple attribute:

class Car : ICar
{
  [EventPublication(“CarWreck”)]
  public event WreckHandler OnWreck;
}

The important piece here is the text string that is sent in to the EventPublication attribute.  It can be any string at all, but it’s that string that event subscribers will use.

Over on the subscriber end it, hooking up the event looks like this:

class PoliceOfficer : Person
{
  [EventSubscription(“CarWreck”, ThreadOption.Caller)]
  public void HandleCarWreck(ICar car) {…}
}

Notice that I’m using the same text string in both.

Now there are a few important notes on using events in the OpenNETCF.IoC framework.  First all of the objects (publishers and subscribers) have to be actually in the framework (in either the Items or Services collection).  In fact with the version of the Framework that ships as I write this, the objects actually have to be created by the framework.  This means that if you create the object manually and then use the Add method to get it into the collection (as opposed to calling AddNew or using an InjectionConstructor or ServiceDependency), then the events won’t get wired up.  I intend to fix this in a future version, but if you pull down the code today, be aware of that limitation.

The second note is in relation to the subscriber.  You’ll see that the EventSubscription attribute takes a ThreadOption as a second parameter.  The idea behind this parameter is that it should dictate the thread on which the handler runs – either in the context of the caller or in the context of the UI.  Well that attribute, for now, is just a placeholder.  It’s not actually used anywhere, so don’t be surprised if your worker thread raises an event and your subscriber tries to update the UI and gets an exception whining about the use of Control.Invoke.  Again, this is something I intend to complete but when I looked at the options of releasing the framework either earlier with a few missing features or later and feature complete, I thought that just getting it out would be a lot more useful.


Next up: Looking at the performance implications of all of this IoC and DI stuff

Wednesday, March 11, 2009 9:23:45 AM (Central Standard Time, UTC-06:00)  #     | 
# Tuesday, March 10, 2009

Articles in this series
Part I: Inversion of Control and the Compact Framework
Part II: The OpenNETCF.IoC Framework: Items and Services (this article)
Part III: The OpenNETCF.IoC Framework: Events
Part IV: The OpenNETCF.IoC Framework: Performance (TBD)

Downloads
Code and Sample available through CodePlex.


The OpenNETCF.IoC Framework

 

Since I don’t expect that everyone has used the SCSF and since the OpenNETCF IoC framework is a very small subset, let’s walk through what it is and how it works.  First, the OpenNETCF.IoC framework is based on the concept of “Components.”  A Component is simply an instance of a class and our framework has two flavors of Components: an Item and a Service.  Generally speaking, the difference between an Item and a Service is that an Item is a uniquely-named instance of a Type (so you can have any number of them provided each instance has a unique name) whereas there can only be one Instance of a service per registered type (it acts somewhat like a Singleton).

Both Items and Services are contained as collections in a root container called the RootWorkItem (a name that comes from the CAB framework).  Let’s take a look more in depth at each of these components and how you might use them together.  For this example we’ll get a little more concrete that the Cars and People example from before, and instead look at classes more actual applications might use.

Items

As I mentioned, Items are simply uniquely named instances of objects.  They can be of any Type – the Items collection doesn’t need to contain only a set of a specific type.  The Items are contained, conveniently enough, in the RootWorkItem.Items collection.  So exactly what advantages to we gain by putting our items in this collection?  The primary benefit is that the RootWorkItem becomes an instance manager and, as we’ll see in a little bit, it can also be a factory.

Let’s assume that our application contains the following Forms: MenuForm, EntryForm and SettingsForm and to make things simple, we’ll assume that they are named with their type name.  If we have these forms in the IoC framework, then any time we need to reference one of them we can simply do something like this:

desiredForm = RootWorkItem.Items[“EntryForm”];

and ta-da, we get the instance of the Form.  We don’t need to pass around a reference to it or store it in some other application global location.  So that’s pretty useful right there.  But the RootWorkItem really is just an application global, right, so it must provide some other benefit.  Well it’s also a factory.  If we want to create the entry form we can use a basic create-and-insert mechanism like this:

EntryForm form = new EntryForm();
RootWorkItem.Items.Add(form, “EntryForm”);

But that really isn’t all that interesting.  Where it gets interesting is that you can let the framework do the construction for you by simply giving it a Type and name (the name is actually optional, as the framework will assign it a GUID if you don’t provide one):

RootWorkItem.AddNew<EntryForm>(“EntryForm”);

That’s handy.  No need to call the object contructor to get an instance and then stuff it into the collection.  Less code is always a good thing.  But what else can it do (right now I’m feeling a bit like Ron Popeil)?

Well that’s not all!  Where it gets fun is in its ability to do injection.  This requires a little more complex of a scenario.  Let’s assume that the MenuForm requires an instance of both an EntryForm and a SettingsForm.  Something like this:

class MenuForm
{
  public MenuForm(EntryForm entryForm, MenuForm menuForm) {…}
}
 

Well the OpenNETCF.IoC framework can actually do these injections for you – all you have to do it provide it a little direction with attributes.  If we simply decorate the constructor with the InjectionConstructor attribute, the framework will search the Items collection for existing items of the proper type to inject.  So the MenuForm looks like this:

class MenuForm
{
  [InjectionConstructor]
  public MenuForm(EntryForm entryForm, MenuForm menuForm) {…}
}

And construction now looks like this:

RootWorkItem.AddNew<SettingsForm>(“SettingsForm”);
RootWorkItem.AddNew<EntryForm>(“EntryForm”);
RootWorkItem.AddNew<MenuForm>(“MenuForm”);

And the magic of the OpenNETCF.IoC framework will inject the first two instances into the third.  An interesting note here is that the Injection Constructor does not have to be public.  The OpenNETCF.IoC framework looks for internal and private constructors as well so you can actually create objects that can only be generated via injection if you wish.

Of course the framework also supports Injection Methods as well, in the event that an InjectionConstructor doesn’t meet your needs:

class MenuForm
{
  public MenuForm() {…}

  [InjectionMethod]
  void InjectEntryForm(EntryForm entryForm) {…}

  [InjectionMethod]
  void InjectSettingsForm(SettingsForm settingsForm) {…}
}

But wait, there’s more!  In the examples so far the RootWorkItem.Items collection must contain the SettingsForm and EntryForm before the MenuForm is created.  Well what if we are lazy and don’t even want to do that?  Well the OpenNETCF.IoC framework can handle that too.  Just add the CreateNew attribute like this:

class MenuForm
{
  [InjectionConstructor]
  public MenuForm([CreateNew]EntryForm entryForm, [CreateNew]MenuForm menuForm) {…}
}

And the framework will create a new instance of the Type if it can’t find it in the Items collection. Construction of all three objects and injecting them now looks like this:

 

RootWorkItem.AddNew<MenuForm>(“MenuForm”);

Extremely simple and clean.

Services

The RootWorkItem also contains a collection of Services.  A Service is very similar to an Item except for the fact that there can only be one service of any given registered type (we’ll covered what “registered” means in a moment).  The collection provides a very similar set of methods and attributes as items.  Again, let’s consider a more concrete example.  Assume your application has a class that handles reading and setting configurations.  There really would only be one instance of this class and in a lot of classic cases people would use the global-wrapped-in-a-new-name called a Singleton.

In the OpenNETCF.IoC framework this would be a service.  Since there can only be one pre registered type, there’s no need to name a Service – the registration type becomes the identifier.  So as a simple construct/add/retrieve a Service operation would look  like this:

Configuration config = new Configuration();
RootWorkItem.Services.Add<Configuration>(config);

Configuration retrievedConfig = RootWorkItem.Services.Get<Configuration>();

As with the Items collection, there is a lot more power and convenience in the framework.  First, we can have the framework do construction for us:

RootWorkItem.Services.AddNew<Configuration>();

Like the Items collection, InjectionConstructor or InjectionMethod attributes can be used to control which constructor for the service class gets called.

The OpenNETCF.IoC framework also offers lazy loading of services, so the service instance isn’t actually created until it is first accessed (instead of when it’s added).

RootWorkItem.Services.AddOnDemand<Configuration>();

We saw earlier that the OpenNETCF.IoC framework would walk the Items collection looking for instances to use during injection.  Well what if an object depends on a Service rather than another Item?  The framework also provides a mechanism for that as well using the ServiceDependency attribute.  So to inject a Service into a consumer class using Constructor Injection it would look like this:

class ServiceConsumer
{
  [InjectionConstructor]
  public ServiceConsumer([ServiceDependency]Configuration config) {…}
}

And of course there is a way to do setter injection instead of constructor injection.  Here it injects into a property instead of using a method like the Items collection:

class ServiceConsumer
{
  public ServiceConsumer() {…}

  [ServiceDependency]
  public Configuration Config { set; get; }
}

And if you want the framework to construct the service if it doesn’t already exist, you simply set the EnsureExists member of the ServiceDependency attribute like this:

[ServiceDependency(EnsureExists=true)]
public Configuration Config { set; get; }

The only other aspect of a Service that an Item does not have is a “registration type”.  This allows you to register a service instance as a type other than its actual base type.  For example you may have a Configuration class that you want to register as a service, but you want to register it as an IConfiguration (this would allow consumers to extract the service by the interface type without ever knowing about or having a reference to the concrete implementation).


Up next: The OpenNETCF.IoC Framework: Event Publication and Subscription

Tuesday, March 10, 2009 7:17:43 AM (Central Standard Time, UTC-06:00)  #     | 
# Monday, March 09, 2009

Articles in this series
Part I: Inversion of Control and the Compact Framework (this article)
Part II: The OpenNETCF.IoC Framework: Items and Services
Part III: The OpenNETCF.IoC Framework: Events
Part IV: The OpenNETCF.IoC Framework: Performance (TBD)

Downloads
Code and Sample available through CodePlex.


Introduction

 

Periodically the software industry goes through a shift in underlying programming practices.  In the 80s the shift was from procedural code to object oriented.  In the 90s we saw the rise of things like “extreme” and “agile” programming.  Recently I’ve seen a shift toward using dependency injection (DI) and inversion of control (IoC).  They’ve been around long enough now that I think they’ll stick, and since any programmer should try to maintain some level of understanding of the latest technologies, I decided to dive into them.

What came out of my investigation were the following:

1.       I was already doing a lot of the stuff, I just didn’t know it

2.       That there really isn’t a reasonable framework in existence for the Compact Framework

3.       Dependency Injection and Inversion of Control, when followed well, can greatly improve extensibility, maintainability and testability of code.

4.       My own IoC framework

Definitions

Before we can talk about all of the benefits of using a framework for Dependency Injection and Inversion of Control, we really need to define them. 

Dependency Injection

Though the name sounds complex, Dependency injection really is what the name implies and is really simple, but explaining it in abstract terms tends to get convoluted.  For example, it could be defined as “with dependency injection you inject dependent objects into the object which depends on them.” Doesn’t really roll of the tongue, does it?  I read that I tend to see “blah, blah, object, blah, depend, blah” and want to move on to something else altogether.  But really, it is simple.  So let’s use an actual example and a picture.

Let’s say we have a couple classes,  Car and Person, and a person can own and drive a car. So it’s something like this:

class Car
{
  public Car() {…}
}

class Person
{
  private Car m_car;

  public Person() {…}

  public void Drive () {…}
}

Now the question here is how does the Drive method “get” or “know” what car to Drive?  One way would be to have the Person instance create the car along these lines:

 

 

public Person()
{
  m_car = new Car();
}


 

So the Person class knows what its dependency is.  It knows at compile time that it needs a Car and creates it.  That’s all well and good, and sure, it work, but it’s certainly not extensible.  To make it a little more extensible, we could use an interface for the Car instead:

 

class Person
{
  private ICar m_car;

  public Person()
  {
    if(this.IsAMoparGuy)

      m_car = new ShinyDodgeChallenger();
    else
      m_car = new RustBucket();
  }
}

 

This is a bit more extensible – the Person has some opportunity to decide what type of car it wants, but it still puts that decision in the Person class and the Person class still has to know about the concrete types of Car. So how do we make it even more extensible so that Person needs to only know about the interface?  Simple – we pass in the object.  That can be done, generally speaking, in two ways.  Either in the constructor:

 

class Person
{
  private ICar m_car;

  public Person(ICar car)
  {
    m_car = car;
  }
}

Or using a method to set it:

 

class Person
{
  private ICar m_car;

  public Person() {}


  public SetCar(ICar car)
  {
    m_car = car;
  }
}

It’s very likely that you’ve used patterns like this in the past, and in fact these are dependency injection.  The first is called “constructor injection” and the second is called “method injection.”  I’ve also seen references to “property injection” which you can probably guess sets the dependency using a Property instead of a method, but a Property really is nothing more than syntactic sugar around a pair of methods.  If you really want to consider it separate, then we can lump the Property and Method injections into something I’ll call “setter injection.”

Inversion of Control

Inversion of Control is a lot like Dependency Injection in that the name puts me off immediately because it sounds like an attempt to use overly large words to describe a likely simple thing, and indeed it is.  In “old school” programming you might have an object (like a Person) that controls another object (like a Car) and when you want to know if some state has changed, you simply query it.

So the Person instance might do something like this

if(m_car.HasCrashed) Call911();

Well Inversion of Control simply turns that around.  Instead of us asking the object for state, the child object (the Car in this example) will inform us of a change.  Sound familiar?  .NET events and delegates are a classic, and really often used, case of Inversion of Control.

So you might hook it up like this

m_car.OnCrash += new CrashHandler(
    delegate { Call911(); }
  );

It’s nothing more complex than that.

IoC and the Compact Framework

When I started out looking into IoC and DI, I was a little put off.  I dislike following programming fads or chasing after some technology simply because it’s all the rage and there are conferences touring the country talking about them.  But I was working on a desktop project and a friend said that I should check out Microsoft’s Smart Client Software Factory (or SCSF) as he thought it would be a good framework to achieve the goals we were after.

Well it turns out that SCSF is built on Microsoft’s Composite UI Application Block (also called CAB) and together they really are just a library that provides a very robust IoC framework.  I’m currenly working on porting that desktop project to use the SCSF and it’s turning out to be very, very useful.

When I needed an IoC framework for the CF, I found that Microsoft’s Patterns and Practices team ported the CAB/SCSF framework a few years back.  I also quickly found out that the people who did the port appeared to do a literal port of the code.  So while it compiles and runs, it certainly does not take into consideration the limited memory and processor power of a typical Windows CE device.  A very common complain about the Mobile Client Software Factory is that its performance sucks.  And I can attest to that.  It does suck.

So what to do?  There are a couple (and really only two that I could find) IoC frameworks that claim to be CF compatible.  I looked at them briefly, but I pretty quickly abandoned them because I really don’t feel like learning the object model for a whole new framework.  I’m using the SCSF and I’m comfortable with it, and I don’t like having to constantly have to think about object models depending on what my code targets.  I also like to keep my code as reusable as possible, and changing frameworks certainly wouldn’t help on that front.

So what I decided to do was to build my own framework based, mostly, on the object model of the SCSF.  The goal was to implement only the bare minimum of what I needed and to build it specifically considering that it would be used on CE devices. What I ended up with is a simple, lightweight dependency injection framework that I called OpenNETCF.IoC. 


Up Next: The OpenNETCF.IoC Framework: Items and Services

Monday, March 09, 2009 12:48:36 PM (Central Standard Time, UTC-06:00)  #     | 
# Wednesday, December 03, 2008
It seems that just about every project I work on requires that I write classes that expose events.  Of course this isn't surprising or new.  What has always bothered me was the fact that this tends to generate lots of custom delegates - especially if you have multiple developers working on a project.  Often, the event is simply passing a single data item, and so we end up with ugliness like this, especially when we want the delegate to be strongly typed:

delegate void StringDelegate(object o, string item);
delegate void IntDelegate(object o, int item);
delegate void BoolDelegate(object o, bool item);
delegate void StringListDelegate(object o, List<string> item);

...

public event StringDelegate StringEvent;
public event IntDelegate IntEvent;
public event BoolDelegate BoolEvent;
public event StringListDelegate StringListEvent;


It's ugly, it's a pain in the ass to maintain, and it's just terribly redundant.

Lately I've started using a much simpler pattern heavily leveraging generics.  First, the only declaration outside of the event is a single type:

public class GenericEventArg<T> : EventArgs
{
   public GenericEventArg(T value)
   {
     Value = value;
   }

   public T Value { get; set; }
}

Using this, I can create a strongly-typed event to pass any form of argument like this:

public event EventHandler<GenericEventArg<MyClass>> MyClassEvent;
public event EventHandler<GenericEventArg<List<string>>> StringListEvent;
public event EventHandler<GenericEventArg<int>> IntEvent;

No custom delegate required since we use the EventHandler<> delegate for them all.

Wednesday, December 03, 2008 11:28:08 AM (Central Standard Time, UTC-06:00)  #     | 
Calling Control.Invoke tends to be a problem, especially for developers who are new to the .NET world.  I think the primary struggle is how to call Invoke without writing a custom delegate, creating a member variable and/or some helper methods.  Here are a couple patterns that I use pretty regularly:

Using an anonymous delegate

if (this.InvokeRequired)
{
   this.Invoke(new EventHandler( delegate (object o, EventArgs a)
   {
     // do your work here
   }));
}
else
{
  
// do your work here
}

Reusing the existing EventHandler

void MyEventHandler(object sender, EventArgs e)
{
   if (this.InvokeRequired)
   {
     this.Invoke(
       new EventHandler(MyEventHandler), new object[] { sender, e }
     );
     return;
   }

   // do your work here
}


Wednesday, December 03, 2008 11:12:37 AM (Central Standard Time, UTC-06:00)  #     |