# Monday, September 17, 2012

I’ve recently started refactoring a customer’s code base for a working application.  They recognize the need to make their code more extensible and maintainable so I’m helping to massage the existing code into something that they will be able to continue shipping and upgrading for years to come without ending up backed into a corner.

One of my first suggestions was to start eliminating the abundance of static variables in the code base.  In this case, static classes and methods abound, and it looks like it was used as a quick-and-dirty mechanism to provide singleton behavior.  Now I’m not going to go into depth on why an actual singleton might have been better, or the pitfalls of all of these statics.  Write-ups on that kind of thing about in books and on line.

Instead, let’s look at what it means to migrate from a static, an instance or a singleton over to using a DI container, specifically OpenNETCF’s IoC framework.

First, let’s look at a “service” class that exposes a single integer and how we might consume it.

   1: class MyStaticService
   2: {
   3:     public static int MyValue = 1;
   4: }

And how we’d get a value from it:

   1: var staticValue = MyStaticService.MyValue;

Simple enough.  Some of the down sides here are:

  • There’s no way to protect the Field value from unwanted changes
  • To use the value, I have to have a reference to the assembly containing the class
  • It’s really hard to mock and cannot be moved into an interface

Now let’s move that from a static to an instance Field in a constructed class:

   1: class MyInstanceService
   2: {
   3:     public MyInstanceService()
   4:     {
   5:         MyValue = 1;
   6:     }
   7:  
   8:     public int MyValue { get; set; }
   9: }

Now we have to create the class instance and later retrieve the value.

   1: var service = new MyInstanceService();
   2:  
   3: // and at a later point....
   4: var instanceValue = service.MyValue;

We’ve got some benefit from doing this.  We can now control access to the underlying value, making the setter protected or private, and we’re able to do bounds checking, etc.  All good things.  Still, there are downsides:

  • I have to keep track of the instance I created, passing it between consumers or maintaining a reachable reference
  • I have no protection from multiple copies being created
  • The consumer must have a reference to the assembly containing the class (making run-time plug-ins very hard)

Well let’s see what a Singleton pattern buys us:

   1: class MySingletonService
   2: {
   3:     private static MySingletonService m_instance;
   4:  
   5:     private MySingletonService()
   6:     {
   7:         MyValue = 1;
   8:     }
   9:  
  10:     public static MySingletonService Instance
  11:     {
  12:         get
  13:         {
  14:             if (m_instance == null)
  15:             {
  16:                 m_instance = new MySingletonService();
  17:             }
  18:             return m_instance;
  19:         }
  20:     }
  21:  
  22:     public int MyValue { get; set; }
  23: }

And now the consumer code:

   1: var singleTonValue = MySingletonService.Instance.MyValue;

That looks nice from a consumer perspective.  Very clean.  I’m not overly thrilled about having the Instance accessor property, but it’s not all that painful.  Still, there are drawbacks:

  • The consumer must have a reference to the assembly containing the class (making run-time plug-ins very hard)
  • If I want to mock this or swap implementations, I’ll got to go all over my code base replacing the calls to the new instance (or implement a factory).

How would all of this look with a DI container?

   1: interface IService
   2: {
   3:     int MyValue { get; }
   4: }
   5:  
   6: class MyDIService : IService
   7: {
   8:     public MyDIService()
   9:     {
  10:         MyValue = 1;
  11:     }
  12:  
  13:     public int MyValue { get; set; }
  14: }

Note that the class is interface-based and we register the instance with the DI container by *interface* type.  This allows us to pull it back out of the container later by that interface type.  The consumer doesn’t need to know anything about the actual implementation.

   1: // Note that the Services collection holds (conceptually) singletons.  Only one instance per registered type is allowed.
   2: // If you need multiple instances, use the Items collection, which requires a unique identifier string key for each instance
   3: RootWorkItem.Services.AddNew<MyDIService, IService>();
   4:  
   5: // and at a later point....
   6: var diValue = RootWorkItem.Services.Get<IService>().MyValue;

Mocks, implementation changes based on environment (like different hardware) and testing become very easy.  Plug-in and run-time feature additions based on configuration or license level also are simplified.

Monday, September 17, 2012 1:07:54 PM (Central Daylight Time, UTC-05:00)  #     | 
# Tuesday, August 21, 2012

If you needed another excuse to try out IoC, here it is.  It’s now even easier to create intuitive UIs. I just checked in a new feature to the OpenNETCF.IoC.UI assembly.  Workspaces now have basic gesture support, so you get an even on a swipe in the four primary directions (up/down/left/right). 

Tuesday, August 21, 2012 2:44:08 PM (Central Daylight Time, UTC-05:00)  #     | 
# Tuesday, August 14, 2012

One limitation with using the SmartClientApplication as a basic for your IoC application is that it locks you in to the type of Form that’s going to be displayed when your app starts up.  In most cases that’s really not an issue, but sometimes you’d like to decide at runtime what UI to display.  You might even want that UI to come from a dynamically loaded DLL.

Well I just added a new capability to the SmartClientApplication.  During the startup process, the framework now looks in the Services collection to see if you’ve already registered a Form deriving from the new ShellReplacement base class.  If it finds one, that form will be shown instead of the type passed into the SmartClientApplication.  The effectively gives you a “default” main shell form, with the ability to dynamically load a different one based on whatever criteria you want.  We’re using it to support vertical-specific UIs for the Solution Engine, meaning that if you have the HVAC module installed you’ll get one UI but if you have the Telematics module installed you’ll get another.

The implementation details are as trivial as I could think of making them.  First, create your new shell Form like this:

   1: public partial class HVACMainView : ShellReplacement
   2: {
   3:     public HVACMainView()
   4:     {
   5:         InitializeComponent();
   6:     }
   7: }

Then register it as the replacement when your Module loads:

   1: public class Module : ModuleInit
   2: {
   3:     public override void AddServices()
   4:     {
   5:         RootWorkItem.Services.AddNew<HVACMainView, ShellReplacement>();
   6:     }
   7: }

That’s all there is to it.  You can disable the feature by using the EnableShellReplacement property (defaults to true) of the SmartClientApplication.  Get the latest change set (69942 or later) to try out the new feature.

Tuesday, August 14, 2012 3:05:29 PM (Central Daylight Time, UTC-05:00)  #     | 
# Wednesday, August 08, 2012

I’ve released version 1.0.12221 of the OpenNETCF IoC framework.  Not a whole lot new going on – it was primarily bug fixes – but binaries for all supported Platforms (Full framework, Compact Framework, Windows Phone and Mono for Android) are included.  If you’re using it, how about showing me some love and rating it (other than “Have not used it yet” – what kind of review is that?).

http://ioc.codeplex.com/releases/view/82674#ReviewsAnchor

Wednesday, August 08, 2012 10:38:34 AM (Central Daylight Time, UTC-05:00)  #     | 
# 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, February 20, 2012

In my push to get our fundamental libraries up and working on Mono for Android we've added support for OpenNETCF Extensions and OpenNETCF IoC.  What that means is that now you can have a common code for a lot of application infrastructure that works on the Compact Framework, the desktop, Windows Phone, MonoTouch for iOS and Mono for Android.  So you can now create a single, common code base for your applications that includes data access, event aggregation, dependency injection and inversion of control.

Get the latest code over on Codeplex.

Monday, February 20, 2012 12:36:44 PM (Central Standard Time, UTC-06:00)  #     | 
# Monday, November 28, 2011

Lately it seems that I’m been doing a lot of posts referring to “a customer”.  Often they are different customers, but it really sounds impersonal, so in this one I’m going to name names and point fingers – in a friendly way, of course.

Last week Nicolas emailed me to get some advice on the Visual Studio 2008 Forms designer and the Compact Framework.  Specifically he wanted to know if it’s possible to get a custom TabControl to be designable.  My assumption is that either he’s inheriting from the stock version or they’ve created a fully custom control inheriting from ContainerControl – I didn’t ask because in either case the answer is simple: it’s not going to work in the designer.

I told him that it won’t work, but in retrospect I feel I’ve short-changed him a bit.  As a developer, I like to hear a bit more than an “abandon all hope, ye who sail here for there be sea monsters” kind of response.  Why doesn’t it work?  More importantly, what are my options for a workaround?

In this case it’s interesting to note that even if he could get the designer to work for this control, I’d recommend that he not do it.  And they why to that recommendation is far more interesting.

So, Nicolas, here’s the longer answer to your question.

First, you have to understand that the Studio Designer is very, very brittle.  Any little quirkiness tends to send it into fits, and once broke you often spend large amounts of time unloading things, resetting the toolbox, restarting Studio or even restarting the PC.  This is a huge time drain, so avoiding situations that break the designer is the first order of business.

Getting the designer working for a CF component is even worse.  CF controls often make use of things that the desktop doesn’t even have, which the designer really hates.  You also have to build the Controls for both versions of the CF (for Nicolas this is important since, at least last time I was with his team, they had versions of the application targeting CF 2.0 and CF 3.5).  A control built against CF 3.5 will never show up in the designer of a CF 2.0 project.  There’s also a major bug in the designer that limits CF 3.5 controls that I’ve written about before.

For designer support you also have to maintain an XMTA file and often end up having condition compiler statements which really make the code less readable.  Workarounds for most of these issues exist.  You can create separate set of “designer” assemblies that provide only stuff for the designer and minimal actual control logic.  The problem with this is that you then have to maintain these things, which sucks up developer time that should be spent actually solving your business problem.

You can’t create a desktop assembly and use it for the designer because the designer will then suck in the full .NET framework as a reference and attempt to deploy that to the device when you want to debug.

So if the designer is so brittle and worthless, what’s a developer to do?  Well, my general attitude is to provide “support” only for basic Controls, and by “support” I mean the inherent capability of the designer to show a box with the location and bounds of your control.  No rendering.  No styling.  No collection editing. 

Really the designer’s primary use for me is to aid in basic layout.  I need to put a Control on a Form, set it’s location and Size and that’s it anyway.  Anything else is done via code, and there’s nothing wrong with this.  Embrace it as how you must work and your life becomes much simpler.

That’s all well and good for a simple Control, but what about a container like Nicolas is after?  His team would like to be able to drop on a Tab control and design each individual Tab, right?  So what are they to do?

Well, I think they’re looking at the problem wrong to begin with.  I don’t blame them, people have been looking at this wrong for some time, and the simple existence of the TabControl tend to push people to look at it wrong.  In general, my recommendation is to not use the TabControl in the first place. 

First of all, it’s 2011.  That ass-looking TabControl would have been ok back in 1995 (if the devices had existed then) since it looks just like the ass-looking Windows 95 interface. 

It’s was an ok solution in 2000 when these devices were new and people thought of them as just “mini PCs” so extending the desktop paradigm to the device was what we did.    Yes, we wished we could do a little more to make it pretty by adding icons and custom drawing, but it worked and users really didn’t expect anything more.

But it’s 2011.  Users don’t use a stylus if they can avoid it.  They know an elegant UI when they see one because they’ve been using a smartphone.  Just because they have no choice in the app they use (this is an LOB app, so the user is locked in) is no excuse to not deliver something that is actually nice to use.  The TabControl does not meet that.  It’s tiny, it scrolls weird, and it’s ugly with no options to make it non-ugly.  Plus it’s  Tab motif.  Name the last mobile app you used on a phone that used tabs.  That’s what I thought. Abandon the piece of crap.

So what would I use?  Obviously this will be subjective, as it’s what I would personally do given a blank slate.  Nicolas is trying to put something into an already-existing, very large code base, so his mileage may vary, but I’m betting it won’t be too bad, and implementing this might actually do a lot toward getting other gains they really need like better transition time between views.

I’d start using the OpenNETCF IoC project.  I’d split each of the existing “tabs” into individual SmartParts, which are now fully designable since they’re just UserControls.  So there you are – the designer requirement is solved.  I’d then place on the Form a pair of DeckWorkspaces.  One would display the “selected” view and the other would replace the “tabs” of old with buttons or clickable images that would be used to select the current view.  It would look something like this in the designer for the Form:

tabs

And then the SmartPart that goes into the bottom workspace might be something like this in the designer (well it would probably be a bit different, but you get the idea):

tabs2

See, the designer works.  It meets the business requirement that it provides a “tab-like” capability where the user selects an item across the bottom and the upper view changes.  But now it’s not just usable with a stylus but it’s also likely to be usable with a finger (gasp!) and aesthetically it doesn’t make my want to poke my own eyes out.  It’s a win-win.  Plus now you can lazy-load the views *on demand* rather than loading up every damned control on every tab when the Form is brought up, so the user is going to be pleasantly surprised there too.  Oh, and now it’s easy to change out “tabs” based on user rights or workflow and probably other benefits that I’m not thinking of.

Occasionally we’ve got to break out of the “what we know” and the “what we’ve always done” routine and look out at the horizon.  By doing so we can often make some simple changes and make things easier for both the developer and the user, and that is how we make progress.

Monday, November 28, 2011 12:24:00 PM (Central Standard Time, UTC-06:00)  #     | 
# Tuesday, November 01, 2011

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


In this post, we’re going to look, at a higher level, at the reasons for and benefits of using a framework for Inversion of Control (IoC), Dependency Injection (DI) and Service Location. I’m not going to spend a large amount of time in this blog series describing the intimate details of what IoC, DI and Service Locators are.  Martin Fowler did a fantastic job of it and there’s no point in me just regurgitating his work.

Instead, I’ll give my vision of what they are and how they are relevant to how I architect and develop solutions.  It’s important to note that I’m starting out this series with high-level thoughts about architecture and design.  I’m not just laying down some code, leaving the decisions about how things will interact to some arbitrary, organic process.  This is how software development gets done. 

You’ve got to think about not just the next step, but visualize the end point several months, or even years out and try to connect the dots back to where you are today.  If I implement something in a certain way today, is it going to screw me 3 months down the road?  Spending an extra day now thinking about architecture is going to turn into saving weeks of the customer breathing down your neck and you pull out your hair and work late night trying to hammer a square peg into a round hole.

So let’s look at IoC, DI and Service Location and how they’re going to help us build better software.  Inversion of Control as a concept is something that’s really broad.  It’s really anything that turns the older procedural way of developing upside down (i.e. inverts program control, hence the name).  Moving from a console app to a windowed, event-driven app is technically inversion of control, so you’ve already been using IoC. 

To talk about IoC as a useful concept that’s actually going to be of use, we’ll be using some smaller units/principals of IoC.  The two we’re going to look at are Dependency Injection, or DI, and Service Location.  Neither one is complex or arcane, and you probably already use them to some degree.

Let’s assume we have two arbitrary classes, A and B, and that A uses an instance of B internally.  There are, essentially, 3 ways that A can get the instance of B. 

First, it can directly create it by calling new B().  While this is simple, it’s the least preferred, and generally worst, way to do it.  By directly creating B, A is now tightly coupled to B’s implementation.  B can’t be easily changed out to something else.  If B is in another assembly, A has to have a reference to it.  It’s also difficult to test A by itself. 

The second way that A can get B is that whoever created the instance of A could pass into it an instance of B.  Maybe through a constructor

var b = new B();
var a = new A(b);

or through a property

var b = new B(); 
var a = new A(); 
a.B = b;

This is called Dependency Injection. The former is constructor injection, the latter is property injection – not so complex, eh?  This is useful because, if B is an interface, it’s really easy to swap out the implementation passed to A and the assembly containing A doesn’t necessarily have to have a reference to the assembly holding the implementation of B – it only needs a reference to the interface.  This is really nice when we want to do mocking.

The third way that A can get B is to go get it from some central repository or “factory”.

B B { get; set; }

public A() 
{ 
   this.B = MyClassFactory.GetB(); 
}

This is service location.  A doesn’t really know what B is, it lets the service locator (MyClassFactory) resolve that.  This is really helpful for plug-in architectures as well as for lazy loading objects.

Generally speaking, your code should only be doing #2 (DI) and #3 (service location) for objects of any complexity.  This is not to say that you shouldn’t ever call the new operator in your code.  There’s obviously a grey line out there below which it would be pretty stupid to not just use new for.  If you need to use a simple entity class or structure, then creating one makes sense.  If you need access to the DAL and I see you creating a DAL object in your View, you’re fired.

There are plenty of framework out there that provide DI and service location -  Ninject, Unity, CastleWindsor, StructureMap, Autofac – the list goes on and on.  Instead of using one of them, however, I chose to roll my own.  Normally I wouldn’t recommend such a drastic action – after all reinventing the wheel isn’t usually wise – but in my case it was essentially required, so I’ll give you the short back story.

My team and I had been working on a large desktop application.  We had designed it from the start using Microsoft’s SCSF/CAB framework, which provide DI, service location and a load of other stuff.  It turned out that we were using maybe 10% of the framework, and that the framework’s Studio plug-ins were causing fits with some installations of Studio.  Spending time screwing with Studio plug-ins and trying to get things to compile is a terrible waste of manpower, so we were already getting close to jettisoning it when we decided that we wanted the core of our app logic to be Compact Framework compatible.

Well Microsoft’s “port” of the SCSF to the Compact Framework, called the MCSF, turns out to be a bloated, unbelievably slow, steaming pile of dog crap.  Side note: just because something compiles under the Compact Framework does not mean it should be used in the Compact Framework.  Well, I didn’t want to refactor everything we’d done to some other IoC framework, plus I couldn’t find one at the time that actually worked for the Compact Framework, so I decided to create one. 

I took the tack that I’d create it for the CF first, with a high emphasis on small footprint, minimal resource usage and speed and I simply matched the SCSF object model where our code base interfaced with it and where it made sense – in some places I didn’t like how the SCSF had done things, so I “fixed” their mistakes.  The end result was the OpenNETCF.IoC framework, which turns out to stack up quite well against the other frameworks.  It also has the huge benefit of working on the Full Framework, Windows Phone 7 and MonoTouch (probably MonoDroid as well, though I’ve not tested that). We’ll be looking at OpenNETCF.IoC in a lot more depth in this series.

Tuesday, November 01, 2011 9:50:17 AM (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)  #     | 
# Friday, April 29, 2011

Last night I was browsing around the Net on a back tracking a visit to the OpenNETCF Inversion Of Control (IoC) project.  I came upon a page where someone had done a quick set of benchmarks for many of the popular IoC engines out there [http://www.iocbattle.com/].  This got me wondering.  How would OpenNETCF IoC stack up against these, after all I've never done any performance comparisons against any other framework.

Well I downloaded the benchmarking code the original author had put together and added added an IoC version of the test (which was really easy to do).  I then ran the singleton test, which essentially registers a set of dependent classes by interface name (in theRootWorkItem.Services collection) and then uses the IoC engine to extract the from the store 1,000,000 times.  It then reports how long it took to do the extraction.  Simple enough.

Here are the results:

The hard numbers are not really important - the actual number is going to depend on your hardware - what is interesting is how they look relative to one anotehr.  You can see that if you exclude the new operator (which isn't IoC, it's just there for reference), then the Dynamo engine (which is the test author's engine) preforms the best.  Now I know nothing about that engine, so if you're interested, I'll let you investigate that further.

What was interesting to me is that IoC is three times faster than the next fastest IoC engine (AutoFac), five times faster than Structure Map, roughly 6 times faster than Castle Windsor or Unity and a whopping 25 times faster than the ever-popular Ninject engine.  Evidently my focus on performance when developign the engine paid off.

How about the time it takes to register all of the types that get created?  Are we paying the piper at creation time in order to save it at resolution?  Here are the time results for setup (instantiation of singletons):

Again, IoC is at near front of the pack.

Binary size isn't overly relevent any longer, I mean if you're using managed code then you've already made the decision that file sizes aren't critical, but it's still interesting to look at.  Here's a breakdown of the sizes of each of the libraries.  The libraries marked with an asterisk also have configuration files that are *not* included in the resported size (so deployment would actually be larger than what the graph shows).

All in all, I'm pretty pleased with the results.  We dogfood the OpenNETCF IoC framework for all of our projects, both desktop and Compact Framework, so it gets a fair amound of testing and beating and you can be assured that if there are bugs I'll do my best to resolve them.  If you've not taken a look at the project, give it a try.

 

Friday, April 29, 2011 11:23:10 AM (Central Daylight Time, UTC-05:00)  #     | 
# Monday, March 14, 2011

One complaint I see a lot about apps built using the Compact Framework is that they look terrible.  It doesn't have to be that way, and honestly the Compact Framework really isn't at fault here.  Generally speaking the problem is that developers are lazy and want to just use what's in the off-the-shelf toolbox.  If you do that, then yes, you'll have something that looks like a Windows 95 application.  But again, I don't fault the CF for that, I fault developers (or more likely their managers).

If you want an app to have good aesthetics you need two things:

  1. To hire a real graphic designer to at least produce collaterals
    At the risk of making broad generalizations, I'll state that developers suck at producing graphics (it's OK, graphic designers suck at writing code).  You wouldn't hire a plumber to hang drywall, why on earth are you having developers create UI?  Hire a designer that has experience building UI collaterals and you'll find that not only will your app look a thousand times better, it will get done faster than having your devs hack at it.
  2. To break your developer's reliance on the off-the-shelf controls
    Using the controls that install with the CF is a sure-fire way to end up with a dated-looking app.  This doesn't mean you have to go buy a 3rd-party set of controls; that may help, but don't just assume it's going to solve the issue.  What we've done internally is to build a set of controls that we use.  Most people would be surprised to know that we have a very small set. We wrote the entire device application for a commercially-available time clock that you'd never know was based on CE by looking at it and I believe that the number of Control types used (other than a Form and SmartPart) was one.  That's right - we used a single control type for everything.  We use it as a Button, a Label, a CheckBox and stacked together to make a List (it's a touch device with only 5 or 6 items visible at a time).

There's not much I can do for you on point #1, but for #2 I can at least give you the control we use.  It's called ImageButton due to it's genesis as a button that, surprisingly, held an image.  It got more complex as we needed and added new capabilities and features.  You can set the up and down images (to get that nice "inverted" look on click), put align text left, center or right (with an appropriate margin if you'd like), put text and images together, and several other features.

Here are some quick screen shots:

The first screen shows rounded buttons (the change to a blue background when clicked) with the grey ">" and the text aligned in different ways.  Note that the right and left justified text have a fairly large margin; this is settable.

The second is probably not the greatest picture as it looks a lot like a normal checkbox, but those checkboxes are actually images.  You could easily change them to a round "bubble" or a box with a check that extends beyond the box border.

The third is a simple drawn-gradient background.  Note that the button in the upper middle (which again is an ImageButton) has rounded corners and the gradient background is visible through the transparent corners of the button (this was a real challenge in the CF).  The "State1" text on this view is actually another ImageButton control so it can respond to clicks.  Again note that the gradient background is visible through the control.

The final view shows yet another use of the control.  The two-state capability is actually done with two images. The control is a single ImageButton and when it gets clicked, we swap the image to toggle the "on" or "off" selection. Notice that the text in the images is less pixelated becasue we don't have ClearType turned on.

Since I didn't really have a better place to put the code, and since the sample app showing it was using the IoC framework, I've simply put the code in the OpenNETCF IoC Framework tree on Codeplex (under Samples). Also note that the code for this is not yet in the release. That means you need to pull it from the source view (starting with change set 59250)

Monday, March 14, 2011 8:29:51 AM (Central Standard Time, UTC-06:00)  #     | 
# Friday, December 24, 2010

We've shipped a first version of a customer project.  That's always good news, but the benefit to the community at large is that updates, improvements and fixes to both the ORM and IoC projects from that project have now propagated to the public code bases.

The IoC changes are pretty minor, which tells me that it's a pretty robust and mature library on the whole.

ORM had a load of changes in the SQL Compact implementation.  The interface for the DataStore has expanded by several methods due to use-cases I needed methods for and it's got a whole lot of performance improvements added.  ORM and is now shipping to real-world customers in a handheld product, so I consider it "release" quality.

Be aware that neither project has these changes rolled into a release package yet, so if you want these changes, grab the latest change set from the "Source Code" tab on the appropriate project page.

Friday, December 24, 2010 11:27:44 AM (Central Standard Time, UTC-06: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)  #     | 
# Tuesday, July 20, 2010

Codeplex recently updated the server hosting the IoC project to TFS10.  Since we still have to use Studio 2008 for device development, I had to do some client changes for bindings to get to the server.  TFS 2010 added the concept of a "Team Project Collection", which Codeplex is using - but Studio 2008's Team Explorer dialog has no provision for it.  It took me a while with a search engine to figure out how to actually attach - basically you have to manually type the full path into the connection dialog in Team Explorer like so:

http://<serverName>:<port>/<vdir>/<collectionName>

So for the new TFS10 on Codeplex, it looks like this:

https://tfs.codeplex.com:443/tfs/tfs10

Tuesday, July 20, 2010 10:46:45 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)  #     | 

Codeplex is in the process of upgrading their servers to TFS2010.  It isn't very clear, however, how to attach to the upgraded servers from older versions of Studio (like Studio 2008, which is required for all device development).  The answer is that you have to install a "forward compatibility update".

Monday, July 12, 2010 11:58:02 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)  #     | 
# Thursday, May 13, 2010

Nick Randolph and I have been kicking around the idea of adapting the OpenNETCF.IoC project to Silverlight Mobile on Windows Phone 7 (and by "discussing" I mean I'm trying to convince him to do it for me).  I just noticed over on the IoC stats page that we've had some referrals from someone who apparently has either already done it or is in the process of adapting it for PRISM.  I've contacted him to see if we might collaborate, but this is exciting news. Having a dependency injection framework right out of the box for phone development can only help the community provide solid applications.

Thursday, May 13, 2010 6:19:01 PM (Central Daylight Time, UTC-05:00)  #     | 
# Thursday, May 06, 2010

We recently ported a desktop SCSF/CAB application over to use the OpenNETCF.IoC framework.  The primary thinking here was that the SCSF has way, way more stuff than we really need, want or use and the SCSF wizards had done wacky things to a few Studio installations, so we wanted to get rid of all of that as well.

I've checked in the fruits of the labors into the Codeplex project, including new desktop project and solution files.

Now you can be even closer to one codebase for both desktop and device projects.  If nothing else, it allows you to not have to remember two different injection frameworks if, like me, you end up doing a lot of work on both platforms.

Thursday, May 06, 2010 5:48:28 PM (Central Daylight Time, UTC-05:00)  #     | 
# Wednesday, January 06, 2010

For those following the OpenNETCF IoC Framework, I've checked in another set of fixes.  So yes, it's still an active project.

Wednesday, January 06, 2010 12:42:12 PM (Central Standard Time, UTC-06: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)  #     | 
# Friday, November 20, 2009

If you've ever done mstest unit testing with a Smart Device project, then you're painfully aware of how badly Microsoft dropped the ball on this one.  Debugging a unit test requires making device registry modifications, adding a call to Debugger.Break in your code, then telling Studio to Attach to Remote Process once the breakpoint has been hit.  Seriously, that's their officially published answer to how you debug a Smart Device unit test!

If you know anything about testing, you know that keeping the cycle time for a test to a minimum.  The longer it takes a developer to go from "start testing" to a break point where they can step, then the less productive they're going to be.  Even worse, if the process is painful, slow and convoluted (check, check and check for Microsoft's recommendation), they're likely to just skip writing tests altogether.

Internally we get around this by using our own test runner which uses Reflection to load up and run tests.  I've decided to once again give back to the community and publish this gem as part of Project Resistance (it will get checked in to the IoC Framework as well).

It does not support everything that mstest does, but it's got enough to get you going, and I think it's at least reasonably easy to modify if it doesn't meet your needs.  The currently supported attributes are:

It also might now be obvious how to set it up for your own app.  You need to add a reference to your test assemblies (so VS will deploy them - for some stupid reason you can't tell it to do so via the Configuration Manager) and make sure all projects are set to deploy to the same place.

As usual, if you have feedback or updates, please let me know.  Submitting a patch right on one of the project portals is probably the easiest way (hint, hint).

It's probably worth noting here that the code for this is the CFTestRunner project, and you have to pull it from the source tab on the project site (it's not in the release download yet).

Friday, November 20, 2009 12:36:06 PM (Central Standard Time, UTC-06:00)  #     | 
# Thursday, October 22, 2009

Today I did some of the preliminary work for Project Resistance (well I did it yesterday and today, but we'll call it Day 1).

As usual Smith, my go-to graphics guy for things like this, turned out images that were better than expected, so the app won't look like I did the graphics.  That's the first key to this project looking professional.

I did some preliminary inrastructure work for the application, setting up file layouts and the like.  I also did some quick work for drawing the blank resistor on a background as well:

As usual this was pretty painful - way more painful than it should be.  Trying to get alphablending/transparency working on Windows Mobile can be a huge chore.  It's even worse if you want a control (which is what the resistor is) to have a transparent background through which you can see the parent Form (which is where that green PCB image is drawn).

It involves calling back up to the parent and having it draw the clipping region under your control when the control paints itself.  Fortunately I'd run into this before and I had the code readily available.  Many thanks to Alex Feinman for figuring this out in the first place.

This is certainly something Microsoft needs to work on simplifying if they want the average developer to be able to achieve success.

Thursday, October 22, 2009 12:58:24 PM (Central Daylight Time, UTC-05:00)  #     | 
# Tuesday, October 13, 2009

Recently I got feedback from Nick Randolph, another device developer MVP, regarding the OpenNETCF.IoC framework and handling the lifecycle of IDisposable objects (well we taked about a few things, but this is the one I tackled first).  The problem is that if you add an IDisposable object to any DI container (be it OpenNETCF.IoC, Unity, Ninject or whatever) the container knows nothing about the object's Disposed state.  Unfortunately the IDisposable interface doesn't expose an IsDisposed property or OnDisposed event. 

SO what, exactly, is the problem?  Well, let's assume we create an IDisposable object and add it to the DI container.  AT some point later, we're done with the object, so we call Dispose.  Well that internally releases the object's native resources, but the object itself still has a root (the reference from the container) and so the GC will never actully collect the object and its managed resources.  On an embedded device this could be a problem.

The solution that we came up with is to create a wrapper for IDisposable objects and a new set of methods for the container for adding.  So now you can do something like this:

var instance = RootWorkItem.Items.AddNewDisposable<MyDisposableType>();

Now instead of this returning an instance of MyDisposableType, it returns a container object that holds it.  You access the MyDisposableType object itself via the Instance property of the container, which requires some small code work on the consumer's part, but the nice thing is that when you call Dispose on that container, it in turn calls Dispose on the contained instance *and* it removes the object from the DI container so the GC can do it's work on the object.

I've not rolled a new framework release with these changes because they really are just a proposed solution for now.  If you're interested, go ahead and pull the latest code from the source code page (change set 32718) on the project site and give it a try.  There are a load of new unit tests that show the general idea on usage.

Tuesday, October 13, 2009 3:51:31 PM (Central Daylight Time, UTC-05:00)  #     | 
# Wednesday, October 07, 2009

It's been a while since I did any check-ins to the OpenNETCF.IoC framework.  It's not due to lack of interest or lack of thought on my part.  I've just been very, very busy lately.  We've now using the IoC project in a few commercial applications with very good results, so there isn't a whole lot more to add (though I do want to add some sort of lifecycle management capabilities).

In the hope of getting a little more adoption of the framework, I've added an adapter to OpenNETCF.IoC for the Microsoft Patterns and Practices CommonServiceLocator (CSL).  You can use CSL code to extract object instances from the Items collection.  My hope is that this makes it easier for development teams using CSL to integrate OpenNETCF.IoC into their mobile and embedded projects.

If you have any other ideas or feature requests for OpenNETCF.IoC, by all means submit a request or start a discussion on the project site.  And if you're using it, I'm always interested to see how it's working out.

Wednesday, October 07, 2009 1:13:45 PM (Central Daylight Time, UTC-05:00)  #     | 
# Friday, October 02, 2009

Very often we here at OpenNETCF work on projects that are internal to companies that is seen by relatively few people or we do infrastructure work that helps an app succeed, but it isn't the app itself. Sometimes, though, we do get an opportunity to write public, commercial applications.  We've just finished version 1 of Trapster for Windows Mobile, which chould hit the Windows Marketplace this month.  For more info on what Trapster is and how it works visit their website, or read one of their reviews such as that on PocketNow or CNET.

The pieces of note here are that we used the OpenNETCF IoC Framework for dependency injection and the Bing Maps web services for all of the mapping and navigation work.

Friday, October 02, 2009 7:58:57 AM (Central Daylight Time, UTC-05:00)  #     | 
# Wednesday, August 26, 2009

I've pushed another ode update for the OpenNETCF IoC Framework into Codeplex.  Highlights in this one are the fact that I've added a WorkItems collection to the WorkItem class, meaning there's now the potential for parent/child relationships.

Wednesday, August 26, 2009 8:11:29 PM (Central Daylight Time, UTC-05:00)  #     | 
# Wednesday, July 15, 2009

I've been using the OpenNETCF IoC framework for several new projects lately, and I really like it.  I think my favorite feature is the fact it gives you the ability to subscribe to events from other objects without requiring an instance of the event publisher.  In fact you don't even need to know the publishers type or even of its existence - you simply need to know the name of the event that might get raised.

The only downside I've hit lately is that the performance for creating objects is not fantastic.  Of course that's to be expected.  To achieve all of this really loosely coupled architecture, we have to rely heavily on Reflection.  Not only do we have to do object creation through Reflection, but we have to do a lot of complex querying looking for type names and attributes, and this can take a while.

In an effort to improve things a bit, I'm working on updating the internal ObjectFactory class that is responsible for all of this heavy lifting.  I've added caches for most of the items that get queried through Reflection.  For example now when we want to find all of the published events from a specific Type, we use reflection the first time, but every subsequent time we pull the list from a cache.

A unit test for creating a single object that both publishes and subscribes to events yields nearly a 5,000% improvement in creating speed for the second object of the same type.  Yes, you read that right - it is 50 times faster creating the exact same object type the second time around.  There's no avoiding the pain the first time we have to inspect a Type, but I've already noticed a marked improvement in app startup time using the new changes.

Wednesday, July 15, 2009 12:27:27 PM (Central Daylight Time, UTC-05: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)  #     | 
# Wednesday, June 10, 2009

I've released yet another version of the OpenNETCF.IoC Framework.  This release has a few minor fixes over what I shipped last week, but more important is that it includes the start for a more complete example.  The new sample shows how to dynamically load modules based on a configuration XML document and how to use the DeckWorkspace.

If you're using the framework, please let me know.  I see that it's been downloaded and we're getting some questions and bug reports, so I know that people are at least testing it out, but I've gotten no feedback as to whether anyone finds it useful of not.

Wednesday, June 10, 2009 3:51:53 PM (Central Daylight Time, UTC-05:00)  #     | 
# Friday, June 05, 2009
I've pushed up a new set of features and fixes for the OpenNETCF.IoC Framework as well as rolled a new release. See the Project Site for full details on what changed, but the general feature additions are that the framework now supports loading modules from configuration XML (you can now really decouple your app modules) and I added support for a DeckWorkspace and all the trappings around starting your app from a workspace.
Friday, June 05, 2009 1:21:56 PM (Central Daylight Time, UTC-05:00)  #     | 
# Wednesday, April 01, 2009

I'm in the middle of adding a Passive View Model-View-Presenter(MVP) framework to the OpenNETCF IoC Framework.  I just checked in a working version (it's in the source downloads, not as a release).  If you're interested and want to have a say in how it ends up, go ahead and download it and give me your feedback.  There's a simple usage example in source control.

Wednesday, April 01, 2009 2:10:37 PM (Central Standard Time, UTC-06: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)  #     |