Archive for the ‘Uncategorized’ 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.

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).

Last night (Thursday, June 26th) Rod Paddock gave a talk on using Silverlight 2.0 to the Edmonton .NET User Group.  I’d say that Rod did a pretty good job, despite the fact that the beta of both Silverlight and Expression Blend didn’t exactly want to play nice all the time.  It’s definitely perked my interest in the technology, and I can see a lot of business potential for it.

The rich user experience that Silverlight brings to the web-browser, will, I think raise the bar for what web applications will do for businesses.  Forget all the buzz about ASP.NET MVC or MonoRail or ASP.NET 3.5.  This is just another layer of makeup on the tired, old, hooker that is application development in .NET.  Silverlight is what will make business users oh and ah and get excited about web apps again.

Those who were at last night’s talk will remember that Rod was using a fairly large database that he got from freedb.  It’s fairly large, not quite 7GB of data.  I did get a copy of it, in MS-SQL Server format.  When I compressed it (tar.gz), I got it down to 2GB in size.  If you’re interested in a copy of the database for your own purposes, leave me a comment here and we’ll work something out.

Note:  I would like to state that Don is usually drunk, and as such you shouldn’t believe some of the wild things he said last night, especially about me.

Just a quick recap of days 3 & 4 of running with openSUSE 11 as my primary OS.  By far and large, not a lot of complaints.  As I do most of my work on a laptop, I tend to keep my VM’s on external HDD’s connected via USB2.  I’ve been doing this for a while now, under Windows.

I’m not to sure I’m a big fan of how openSUSE mounts (or tries to mount) my external HDD.  It just doesn’t seem as…seamless…as how Windows XP does it.  I’m use to just plugging in my external HDD, and not worrying about it until it’s time to disconnect.  openSUSE seems to get a big confused with automounting, and I always seem to have to help it along.  It’s something I can live with for now.

The other thing I notice is that openSUSE doesn’t seem to want to share the sound card with VMware.  I’m getting more than a few alerts from VMware that the sound card is not available and can’t be used.  Again, nothing to critical – for now.

The third thing I’m noticing is that some HDD enclosures seem to work better than others.  I’m noticing that at least one HDD enclosure (a SmartDisk FireLite with a 250GB HDD inside) doesn’t seem to want to consistently and reliably work.  I did have VMware (and openSUSE) complain that they could not write that particular HDD as it could no longer be found.

So far, I am pleased with how Linux is handling NTFS as well.  I remember back five or six years ago that NTFS support for Linux was pretty much read-only.  Read-write was for people who were delusionally insane or who go to the same hair stylist as Justice Grey.

A couple of lessons learned:

  • Get lots of disk space.  I’m thinking it may be time to get a 320GB HD for my laptop, and keeping my "working" VM’s there.  I’d have something like a 100 GB partition for Windows XP, and then 220GB for openSUSE.
  • Backups – I’m very happy that I made copies of my VM’s and worked off those. 
  • Fear not the command line.  But if you’re a *nix guys, you’re probably there already.

I’ve decided to try a little experiment, and see how things will go, computing-wise, if I minimize my dependence on Windows.  Now, I don’t want to run out and buy a Mac (not yet, anyway), so I’m taking a middle ground.

I first repartitioned my hard drive (thanks gparted), and set aside a 15GB partition.  On this partition, I installed OpenSUSE 11.

My plan is to run OpenSUSE 11 as the host OS, and then use VMware to run VM’s for my work and such.

I’m curious as to how it will work out.  I know the one hurdle I would like to come is the stupid DRM that Apple iTunes uses.  Anybody have some suggestions, so I can do this while it’s still legal to format-shift in Canada (or perhaps I should spell it Kanada if bill C-61 passes).

Today is the 64th anniversary of D-Day.  If you are a Canadian, take a moment today and read up about 3rd Canadian Infantry Division and the 14, 000 Canadians which went ashore at Juno Beach (the 2nd most heavily defended beach of the invasion).

Likewise, if you’re British, I would suggest taking a moment today and reading up on Sword and Gold beach.

And, if you are American, then perhaps read up on Utah and Omaha beach (the most heavily defended beach of the whole invasion).  And no, watching Saving Private Ryan doesn’t count.

Granted military history (which I read a lot of) can be kind of boring and slow sometimes, but D-Day was a very important day in the 20th century, and some of the troops involved had been training for almost a year for just this one day.

As far as web developer’s go, I’ll freely admit that my Javascript is not one of my strong points.  I don’t have a real good reason for this, it’s just that over the past few years I haven’t had much call/need to polish and hone my Javascript skills.  Recently I discovered jQuery, and I must say that I wish I had know about this library earlier.  The more I use jQuery, the more I like it.  The simple things are simple, and the hard things are possible.  Take calling a simple webservice when the user clicks a button on a form.

Client side, the user would click on a button in their browser, in order to "check out" or "check in" – pretty simple stuff.  Click a button, update a record in the database.  I wanted this done via AJAX, as the page itself is pretty heavy with data, and I didn’t want to go through the whole page lifecycle.  I spent some time Googling how to do this on the web, but I didn’t find anything that seemed to be suitable for something as simple as this.

So, enough boring stuff, on with the issue.  In my current application the ASP.NET web service that the client should call looks something like:

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class CampaignProductCheckoutService : WebService, ICampaignProductCheckoutService
{
  [WebMethod]
  public void CheckIn(int campaignProductId, int loginId)
  {
    // Do something...
  }

  [WebMethod]
  public void CheckOut(int campaignProductId, int loginId)
  {
    // Do something...
  }
}

Pretty simple webservice, nothing fancy.  Here is the corresponding Javascript on the browser:

$.ajax({
  type: "POST",
  url: "CampaignProductCheckoutService.asmx/CheckOut",
  data: "campaignProductId=3&loginId=4",
  beforeSend: function(xhr) {
    xhr.setRequestHeader("Content-Length", "campaignProductId=3&loginId=4".length);
    $("#progressBarContainer").show();
  },
  dataType: "xml",
  complete: function (xhr, msg) {
    $("#progressBarContainer").hide();
    if (xhr.status == 200) {
      alert("Happy Times!");
    }
    else {
      alert("Wailing and gnashing of teeth!");
    }
  }
});

This looks busy, but in reality, it isn’t. Now, for a detailed explanation of what is going on here, I’d suggest reading the book jQuery in Action.  It is a most helpful book for learning jQuery.

Anyway, here is a quick rundown of what is going on:  the $.ajax is a jQuery method that will perform the AJAX call, using the parameters that we provide it.  jQuery will perform an HTTP post to web service specified in url.  As part of the POST request, you can see that we’re passing in the parameters for the webservice call.  So far, pretty straightforward.

The next line, beforeSend, is a javascript method that jQuery will call before it does the POST.  In this case, we make sure that the request header has the length of the data being sent, and we show a progress bar to the user.  The funny syntax you see there is how we select the DIV element holding our animated gif and display it to the user.

Your standard ASP.NET web service will return XML to the client, and we inform jQuery of that with the dataType parameter.

By default, jQuery will perform the AJAX call asynchronously, so in the final line we provide another Javascript callback.  jQuery will call this function once the request is finished.  In this case, we hide the DIV element holding the progress bar, and we check the XMLHttpRequest object that is returned from jQuery. If the status is 200, then all okay and we display a happy message.  Otherwise we assume the request failed, and display a sad message to the user.

There you have it, a quick and dirty explanation of using jQuery to call an ASP.NET Web Service.