Archive for the ‘Programming’ Category

One of the nice things about Dependency Injection is that it can really help write a more flexible, modular application.  These days, it seems that there is no shortage of choice in the .NET community when it comes to IoC frameworks:

Ironically, when you first start using an IoC framework, you might find that in trying to make a loosely-coupled, modular, application you end up shackling yourself to the framework you’re using for IoC.

For example, you start off using your own homegrown IoC framework, and then decide at some point in the future to use a different framework, like say StructureMap.  Going through your codebase to make these changes can be quite the exercise in pain.

There are a couple of ways to isolate yourself from this kind of situation.  I won’t get into all of them but instead will focus on the Common Service Locator. What is Common Service Locator?  Well, allow me to cut and paste some text from the web site:

"The Common Service Locator library contains a shared interface for service location which application and framework developers can reference. The library provides an abstraction over IoC containers and service locators. Using the library allows an application to indirectly access the capabilities without relying on hard references. The hope is that using this library, third-party applications and frameworks can begin to leverage IoC/Service Location without tying themselves down to a specific implementation.

Blah blah blah – so what does all that mean?  Well, in my own words, CSL is basically a wrapper around your IoC container which separates how you  initialize/configure your IoC container from how you use it.  This separation allows you to use your IoC container without knowing anything about it.

This separation is achieved by use of adapters for the particular IoC container that you want to use.  These adapters are what do the dirty work of finding the service you need, in their own special way and totally transparent from your application code.  Currently, the Common Service Locator has adapters for StructureMap, Castle Windows, Unity, Spring.NET, and autofac.

Now, allow me an example of using the Common Service Locator with StructureMap. There is no special reason as to why StructureMap – it just happens to be what I find myself using these days.

Now, say I use the the following registry to configure StructureMap:

   1: public class DefaultStructureMapRegistry: Registry
   2: {
   3:     public DefaultStructureMapRegistry()
   4:     {
   5:         ForRequestedType<IDb4oConfiguration>()
   6:             .TheDefaultIsConcreteType<SimpleDb4oConfiguration>();
   7:     }
   8: }

In a nutshell this says that every time StructureMap is asked to provided an object of type IDb4oConfiguration, it should instantiate a SimpleDb4oConfiguration object and return that.  So, to get an instance of IDb4oConfiguration with StructureMap, I would do something like this:

   1: var db4oConfig = ObjectFactory.GetInstance<IDb4oConfiguration>();

Pretty simple, but it does kind of tightly couples me to StructureMap.  If I need/feel like/am forced at gunpoint to change my IoC container to something that is Not StructureMap, you can bet that there will be much wailing and gnashing of teeth on my part as I hunt through my code to make these changes.

Now enter the Common Service Locator.  First, let’s take a peek at some interfaces for CSL.  First an interface:

   1: namespace Microsoft.Practices.ServiceLocation
   2: {
   3:     public interface IServiceLocator : IServiceProvider
   4:     {
   5:         object GetInstance(Type serviceType);
   6:         object GetInstance(Type serviceType, string key);
   7:         IEnumerable<object> GetAllInstances(Type serviceType);
   8:         TService GetInstance<TService>();
   9:         TService GetInstance<TService>(string key);
  10:         IEnumerable<TService> GetAllInstances<TService>();
  11:     }
  12: }

The IServiceLocator is an interface that your application will use when it requests something from your IoC container.

Another thing that CSL provides is a static class that your application would use to use a current IServiceLocator to request services.  That static class looks something like:

   1: namespace Microsoft.Practices.ServiceLocation
   2: {
   3:     public static class ServiceLocator
   4:     {
   5:         public static IServiceLocator Current { get; }
   6:         public static void SetLocatorProvider(ServiceLocatorProvider newProvider) {};
   7:     }
   8: }

So, now lets see how we would request the default implementation of the IDb4oConfiguration service using CSL.  First, we would initialize CSL:

   1: var registry = new DefaultStructureMapRegistry();
   2: var container = new global::StructureMap.Container(registry);
   3: var smServiceLocator = new StructureMapServiceLocator(container);
   4: ServiceLocator.SetLocatorProvider(() => smServiceLocator );

What is going on here? Allow me to provide a quick line by line explanation:

Line 1 we instantiate a new StructureMap registry.  We then feed that registry to a StructureMap container in line 2.  With line 3, we see that StructureMap container is then fed to the StructureMapServiceLocator, which is the SM adapter for the Common Service Locator.  Finally, with line 4 we provide a lambda that CSL will use to fulfill future requests for services.

Now when our application wants to get an instance of IDb4oConfiguration it just politely asks CSL:

   1: var db4oConfig = ServiceLocator.Current.GetService<IDb4oConfiguration>();

Pretty simple and clean, eh?  Now, when radical group the Foundation for Unity as the Dominate IoC Container sneaks into your cube and forces you at the point of a nerf gun to switch to Unity, you can do so with minimal disruption to your application. With a properly layered application, it would be as simple as coding a new UnityConfiguration layer and then using that instead of your StructureMapConfiguration layer on application startup.

Now, granted this is pretty trivialized example.  There are other ways to solve this problem, but CSL does seem to take are of the grunt work for you so that you can just get going with things.

After a bit of tinkering, I managed to provision my ADP1 setup without a SIM card.  A bit of google, and here is what I did:

  1. Download the Android SDK.  In my case, I unzipped it to C:\android-sdk-windows-1.1_r1.
  2. Connection the phone via the USB cable to my computer.  When the phone asks for a device.
  3. You’ll get the new hardware dialog, when prompted for the drivers, you’ll need to specify the location.  The Android SDK has the drivers, in my case they were at C:\android-sdk-windows-1.1_r1\usb_driver\x86.
  4. Once you have the drivers installed cd to c:\android-sdk-windows-1.1_r1\tools.
  5. Type adb devices.  This should list all the Android devices that you have connected.  If you don’t see any devices listed, then you have a problem.
  6. Type adb shell.  This will direct your commands to your ADP1
  7. Now while at the adb shell, su to root, then : 
  8. cd /data/data/com.android/providers.settings/databases/
  9. sqlite3 settings.db
  10. INSERT INTO system (name, value) VALUES (‘device_provisioned’, 1);
  11. .quit
  12. Reboot the phone
  13. adb shell
  14. am start -a android.intent.action.MAIN -n com.android.settings/.Settings

Once all that is done, you should be enable to use your ADP1 as if you had a SIM card in it (we’ll except for the phoning part).

Useful link:  FAQ: Unlocking/Activating a G1 or ADP1 Without A Sim Card.

After an uneventful flight from YEG to PSP, I’m settled in with my family.  After spending some time with beer at the pool, I’m sitting down with my Android Dev Phone 1 that I ordered last week (ship to PSP).

First impressions:  it seems like a nice phone, and I like the fact it has a keyboard.  I don’t have a SIM card to help with provisioning the phone, so all I get is this message saying "No SIM in phone" and "Emergency call".A quick search on Google tells me that how to get around this and use WiFi.  So, that’s my task for tonight.

Tomorrow we’re heading to the farmer’s market at the College of the Desert where I hope to refresh my collection of quality shirts.

image001_2

If you using a unit testing framework such as NUnit, you’re no doubt familiar with the [Ignore] attribute.  (Note:  I haven’t used MbUnit in a while, but I’m pretty sure that all this applies there as well.) For those who aren’t, when you adorn your [Test] with this attribute, then your test runner should pay no heed to this particular [Test].  Instead of going green or red, your test turns up as yellow in your test runner. At first blush, this seems handy – rather than deleting a failing or broken test you can have it [Ignore]d, much like your typical computer geek at a high school dance before the punch get’s spiked. Now you can deal with the wayward test on your own time with the pesky failure cluttering up your CI build (you do have a CI build box set up, right?).

Please bear with me while I submit to you: This isn’t a good idea. This is a bad idea. An ugly idea. The kind of bad, ugly idea than even Belcham-esque quantities of scotch couldn’t make pretty. Why? Well, the whole point to having a unit test is to test something. If your test is failing, that means something is broken.  You should be addressing the cause of the failure and dealing with the problem now. Covering up the failure with some attribute kind of defeats the purpose of having the unit test in the first place. I mean, really, if you had open, festering lesions on your skin would you just cover them up with a band-aid and pretend nothing was wrong?  Odds are you’d go to a doctor and get that checked out.

Alternately, perhaps the test isn’t valid anymore: your application has changed/evolved and the code that you were testing isn’t around anymore. Then, get rid of the test! Delete it from your test fixtures, and don’t look back.

Granted the world we live in is not black and while.  Sometimes we’re working on things, and we only want tests to run when it is explicitly asked to run.  To handle this scenario, NUnit provides the [Explicit] attribute.  This is a kinder, more gentle kind of ignore.  This instructs NUnit to only run the test when it is told to run the test.  If you add a comment to the attribute, then it helps those going through the build log understand why the test is being run.  However it is still possible to run the test if desired.

[Explicit("This test takes a really really really long time to run so we don't want to run it in this test suite every time")]
[Test]
public void My_very_important_test()
{
    // Test valuable things here
}

I know some people are going to protest my advice. So I will offer up this one last piece.  If you are going to [Ignore] a [Test] then please take advantage of the fact that you can add a comment to the Ignore which will show up when NUnit ignores the test:

[Ignore("This test is ignored as I wish to incur the wrath of Cthulhu (or his proxy)")]
[Test]
public void My_very_important_test()
{
    // Test valuable things here.
}

Now when your CI server runs your unit tests, you will have a nice friendly message that will inform others as to why the test is not running.

Update November 20th:  Well, a quick search of StackOverflow.com, and it turns out that I’m not exactly alone in this matter.  According to this post (and Grant in the comments of this post), in versions of IE < 8, one must use the click event, and not the change event.

I ran into an interesting issue today.  I don’t really know the answer, but I figured I would blog about it so that I don’t completely forget it.  While I highly doubt the two readers of my blog (my brother and sister) have any idea of what I’m talking about, I’m sure that eventually somebody (smart) will stumble upon this via Google.  What will happen in that case is anybodies guess, but I digress…

I had some JavaScript (note that I’m using jQuery too):

   1:  $(document).ready(function() {

   2:      $('#myCheckbox').change(myCallBackFunction);

   3:  }

   4:  

   5:  function myCallBackFunction() {

   6:     // unwrap protein strings and cure cancer in parallel on a single core system

   7:  }

For the sake of completeness, here is a sample HTML snippet to go with the above jQuery:

<input id="myCheckBox" type="checkbox"  >

Now, in FireFox 3, when you clicked on the checkbox, myCallBackFunction gets executed (as I would expect).  However, in IE7, that doesn’t seem to happen.  This has me stumped.

Now, at work, I asked "Who is an expert in Javascript and jQuery?".  Crickets chirped.  Dead silence.  A tumbleweed rolls on by.

I then asked "Who wants to make Tom look stupid?" – everybody jumps at the opportunity.  Go figure.  Anyway, back to our exciting tale.  To get around this, I couldn’t rely on the collective brainpower of myself and my co-workers to figure out what the problem is.  Instead, we deduced that it is better to go around the problem and try something different.  I had  to use the click event like so:

$('#myCheckbox').click(myCallBackFunction);

This works in both IE7 and FireFox 3 – not sure why.

Based on my past experiences with things, I’m sure it’s something I’m doing (or not doing).  Going over my past experience, I’m sure it won’t be me who figures out what I’m doing wrong.

Well, in a scant few hours I’ll be off to Austin, Texas, for KaizenConf.  It will be a fun packed couple of day dealing with some very interesting topics.  In all honestly, I don’t exactly know which of the topics I want to attend – the pretty much all are of interest to me.  Makes me wish I could clone myself.

My plane lands early afternoon, so if you’re kicking around Austin and want to entertain an easily amused Canuck, give me a holler (comments here, or on twitter).

Lately I’ve been experimenting with TypeMock Isolator,  and it’s new AAA syntax.  For the past two years I’ve been a diehard Rhino.Mocks kind of guy, but figured that it’s time to check out other tools.  Anyway, I had a situation where a unit test of mine was failing when I ran it with TestDriven.NET, but would pass when I ran it using the unit test runner in Resharper 4.1.

Usually when I develop, I write individual tests and then run individually with TestDriven.NET and collectively with Resharper.  In this case, as I was writing one unit test, it kept failing with TestDriven.NET.  At first I thought it was just me being stupid (always a good place to start), and then I was worried that perhaps the documentation for TypeMock was to blame.  So, I sent a email to Avi at TypeMock, mostly expecting confirmation of my stupidity.

Turns out the problem in this case was pretty obscure one (to me).  At home, I do my development in a VM running Windows 2008 64 bit.  When Resharper runs your unit tests, it does in a 32 bit process.  TD.NET, on a 64bit OS,  runs as a 64 bit process.  If you get TD.NET to run as a 32 bit process, then your tests will run fine under TD.NET.

To do so, from the Visual Studio 2008 Command Prompt, change to the directory that you have TD.NET installed in.  Then use corflags:

corflags /32bit+ ProcessInvocation.exe

Note that it’s probably best to do this when logged in as the Administrator.

I will say that I was happy with the support I got from the guys (Avi, Gil and Ohad) at TypeMock.  Given the fact that we’re about a half a world apart (western Canada vs. Isreal), they provided prompt, excellent support.  My thanks to them.

As I was driving home today, I couldn’t help notice something.  Microsoft’s ASP.NET MVC framework is still in beta, and was only announced last October.  To my knowledge, there are currently three projects in the Edmonton area based off this framework.

Castle Monorail has been around for much longer, three years or so?  It’s still listed as a release candidate on it’s website, but I’d say Monorail is suitable for production.  Currently, I am not aware of any projects in the Edmonton that are based off this framework.

I guess this is anecdotal evidence that you won’t get fired for sticking with Microsoft. :)

The two frameworks have quite a few similarities.  IIRC, in Austin last fall Scott Guthrie did mention that the ASP.NET MVC framework was influenced to some degree by Monorail.

Regardless, it’s good news.  Personally, I like both frameworks, and would prefer either of them to Web Forms.  YMMV.

Well, I don’t know why it’s taken me so long to get to get around to this: but I must say that there are now a couple of "must haves" in my web developer’s tool box.  One of them is jQuery, and now the other is QUnit.

Chad Myers has a good, quick, post introducing QUnit, I’d strongly suggest checking it out if you do web development (which, IMHO, implies some use of JavaScript, right?).  Chad’s post covers the basics pretty good, and I think I would just be duplicating/plagiarizing Chad’s work if I were to blog the hour or two I spent getting to know QUnit here.

It is nice to see that JavaScript is slowly being recognized as first class citizen of the web programming world, and is gradually having it’s good name cleared of certain falsehoods.  It’s been my belief and observation for a while now that ASP.NET has done a pretty good job of stunting and retarding the adoption/use of JavaScript amongst .NET developers, at least in the Edmonton region.  Good to see that this attitude is starting to change.

At the last Edmonton Agile Methods User Group meeting, we had a brief discussion around code coverage, and what should be an acceptable number to shoot for.  Is it okay when the unit tests cover 80% of the code?  Or should 100% be the only acceptable value?  After all, how can you be confident in your code knowing that 20% of it isn’t tested.

Allow me to go out on a limb here, and state with absolute certainty that the correct answer is "It depends on your situation".  Allow me to elaborate.

  1. The number sends a wrong message.  If your team decides that they need some arbitrarily value to shoot for, that is what they will concentrate on.  Developers will worry more about how many tests they need to write, rather than on the quality of their code.
  2. Unit tests can suffer from the law of diminishing returns.  To achieve that mythical number of 100% coverage would require a large amount of effort.  I argue that in many cases, the high effort required drains away from the teams ability to keep delivering value in their software.  In particular, exception testing comes to mind.  You can spend a lot of time writing tests to cover parts of your code that, in theory, should never be executed.
  3. Unit tests do not replace other forms of testing, so functionally speaking, you should still be covered.  Sure, you may have some code that isn’t covered with a unit test, but hopefully your crack team of functional testers will exercise that code as part of their efforts.  If your functional testers find a problem, and you don’t have a unit test that covers the code in question, then you will obviously write a test and fix the problem.  If your functional testers don’t find a problem, then you don’t worry about it. 
    • Remember that as a part of agile, you have short iterations with working software at the end of each iteration.  So, if there is some problem code that is not tested, your users will find out about it fairly quickly.  The power of rapid feedback at work.
  4. The test part of TDD is a useful side-effect. The true value of TDD is that it helps you craft out a better design for your code.  If you ask me, TDD should stand for Test Driven Design, not Test Driven Development (I do believe credit for this observation belongs to Roy Osherove – at least that is where I heard from first).