Code Magazine article on ASP.NET MVC 2 source code download

In the Nov/Dec 2009 issue of CODE Magazine, I submitted an article entitle “ASP.NET MVC 2 in Action”.  You can read the full article online here.  I wanted to write this short post to let the public know where to get the source code used for the article.  You can download the code here.

Windows 7 brings new life to devices that don’t have Vista drivers

MiniVox USB SpeakerphoneBack in 2005, I purchased an mVox 100 (mv100).  This device worked great on Windows XP, and I used it in various VOIP application.  Really great USB speakerphone.  It’s tiny, also, and I kept it tucked in my back for the last 5 years.

When I upgraded my computer to Windows Vista, I was rather disappointed that this useful little device no longer worked.

I could not find any Vista drivers.  From what I gleaned from forums, it relied on usbaudio.sys, which was overhauled in Windows Vista.  Even though I couldn’t use the device, it stayed in my computer bag for 2 years!  I switched computer bags today and uncovered this little speakerphone.  I decided to give it a shot on my Windows 7 computer.  Lo and behold, it worked!  No driver install.  I plugged it in, it detected it, and registered both the built-in microphone and sound card/speaker.  I happened to have Skype open, and Skype immediately registered the device as the microphone and speaker.  Bottom line:  I am impressed by Windows 7 once again!

image My mobile telephony kit now contains this mVox 100 USB speakerphone as well as my trusty Logitech notebook headset.

IE, Firefox, Chrome, Safari, Opera – what browser does a .Net developer choose?

The short answer:  all of them.

According to NetMarketShare, Internet Explorer still has, what is considered in politics, a 62.18% complete landslide domination of the other browsers.

image

So we can read:  62% IE, and 38% “not IE”.  But that doesn’t work in practice because the other 38% is fragmented among at least 4 other major players (major being defined as more than 1% market share, or about 17,300,000 installations).  Think about it.  Opera has over 41 MILLION users.  So that 2.38% is still not anything to sneeze at. . . unless you are serving the 1,075,714,000 IE users.  Wow.  over 1 billion Internet Explorer users.  (Internet stats from “Internet World Stats”)

At Headspring, most of the current market wants a mix of web, windows, and mobile business applications with a heavy, heavy lean towards web applications.  As a Microsoft shop, ASP.NET is dominating the line-of-business space for us.  We have to decide which browsers to support (which really means which browsers to heavily test).  Yes, the client might have some browser preferences, but most of our clients trust us to do the right thing for them.  So what do we do, and what browser do “I” run?  See above (I run them all).

First, we have to look at the base of users and what browser they are typically running.  A really popular combination is IE 7 and Firefox 2.  Yep.  Version numbers.  We have successfully deprecated IE 6 support down to the functional level (must work in IE 6, but visual discrepancies won’t be fixed) because clients have either migrated or they plan to migrate within a year, and we present the cost/benefit of the alternatives.  Any clients needing Chrome support?  Nope.  none.  not even a mention.  Now, in our experience, if a web application works properly in IE 7 AND Firefox 2, it is highly likely to be just fine in the other browsers.

Now for me.  Yes, I run all the browsers, but I have chosen one for my day-to-day browsing needs.  That browser is Google Chrome 4.  Not Chrome 3 or 2.  But 4.  And it’s only today.  Why?  Because I think Microsoft is going to wake up and deliver a really killer Internet Explorer that will push it’s market share back to 90% in the coming years.

Let me back up:  for running software applications, it is critical to use the browser that the client will be using (and if it requires a different version of IE, then just run it from Windows 7 XP Mode).  If your client is predominantly Firefox (like some timid IT departments now), then you must test your app predominantly in Firefox.  Same for IE.  Ignoring the dominant browser at your client is a really good recipe for obvious bugs to slip through.

Now, why Google Chrome 4?  Because of the architecture of the browser coupled with new support for extensions.  Each tab runs in its own process.  This is critical because it delegate memory isolation and threading to the operation system instead of trying to manage them all within a single browser process.  Next is extensions.  First, and my favorite, is the IE Tab extension, ported from IE Tab as a Firefox extension.  It runs the page in the IE rendering engine but inside a Chrome tab (which is isolated to one process).  Note that this cannot fully replace actually TESTING with IE proper for your clients.

Below is an image of two Chrome tabs.  The top is regular, and the bottom is with IE Tab.

image

My next favorite extension is just named “Keyboard Navigation”.  It’s just like the really great Numbered Links Firefox extension that makes it possible to really browse the web without the mouse.  You press the comma(,) hotkey to pop up the shortcuts, then choose your link.  The enter key directs your browser to follow the link.  All while keeping your fingers on the home row.

image

I don’t use IE and Firefox anymore for my normal browsing for one single reason:  The process architecture.  Having all the tabs in a single process produces a slow browsing experience (when contrasted with the alternative).  Does Chrome slurp up more memory?  Absolutely.  Here is a screen shot of all the processes.

image

A quick glance produces over 500MB or RAM used just for the browser.  If I was worried about RAM (and willing to spend my time waiting in order to save RAM) I would probably make another decision.  But, when all my guys are equipped with 8GB of RAM in the company computers, it’s just not a constraint to worry about.

I’m not an Internet Explorer MVP, so I don’t get early access to IE information and roadmap plans, but I do expect a big breakthrough on that front to be announced in 2010.  I think the sleeping browser giant is about to wake up.

AutoMapper hits 1.0! Download now

Jimmy Bogard just made the announcement that AutoMapper is now 1.0.  Babies grow up so fast.  Jimmy has cultivated this project since it’s infancy, although I think almost everyone from Headspring has at least one commit (I think I had a total of 3 commits, perhaps).

Anyway, go download and upgrade now.

For those who don’t know, AutoMapper is an object-to-object mapper, and you can read more about it on the CodePlex documentation wiki as well as inside the book, ASP.NET MVC in Action.  AutoMapper is very, very useful when mapping from persistent objects to view model objects, but that is just one of the uses.

Architecture Analysis: Onion Architecture webcast

Here is a portion of a webcast I did for the International Association of Software Architects (IASA).  There are more webcasts available on their website:

My ASP.NET MVC in Action talk from Houston TechFest (webcast)

Here is a talk I gave on 26 September 2009 at the Houston TechFest.  Thanks to Shawn Weisfeld for recording it!

Architecture Analysis Webcast 9am Friday

The International Association of Software Architects is hosting a webcast Friday, January 22, 2010 at 9am.  You can register here:  https://www2.gotomeeting.com/register/579164130

It will be a 1.5 hour talk about architecture, but specifically structure of an application.  Here are the full details:

Architecture Analysis - Reasoning About Structure


This presentation is about fundamentals. Layering is a basic concept of IT architecture. Layers help to seperate dependencies and to decouple concerns. Most of the industry does layering in name only. It's lip service. In these slides and accompanying commentary we will explore the concepts of layering and isolation of dependencies and it's impact on the success of your architecture.

When:
Friday, January 22, 2010
9:00 AM - 10:30 AM CST

Constructor over-injection smell – follow up

This is a follow up to my article: “Constructor over-injection anti-pattern”.  I’ve title this a bit differently because as with any heuristic, there are degrees of goodness and smelliness.  Constructor over-injection, therefore, is a code smell, I believe.  Without concrete do’s and don’ts, I believe it doesn’t deserve the explicit title of “anti-pattern”.

I have expanded the code sample (and it is available as a zip or tar file here).

I’ve modified the OrderProcessor as shown here.  I believe this is more egregious and is more of an obvious example.  Small samples get so trivial, that the pain show doesn’t seem like a problem at all, but when injected constructor arguments increase (think 5, 10, 20), the pain is greater.

   1:  namespace DIAntiPattern
   2:  {
   3:      public class OrderProcessor : IOrderProcessor
   4:      {
   5:          private readonly IOrderValidator _validator;
   6:          private readonly IAccountsReceivable _receivable;
   7:          private readonly IRateExchange _exchange;
   8:          private readonly IUserContext _userContext;
   9:   
  10:          public OrderProcessor(IOrderValidator validator,
  11:                                IAccountsReceivable receivable,
  12:                                IRateExchange exchange, IUserContext userContext)
  13:          {
  14:              _validator = validator;
  15:              _receivable = receivable;
  16:              _exchange = exchange;
  17:              _userContext = userContext;
  18:          }
  19:   
  20:          public SuccessResult Process(Order order)
  21:          {
  22:              bool isValid = _validator.Validate(order);
  23:              if (isValid)
  24:              {
  25:                  Collect(order);
  26:                  IOrderShipper shipper = new OrderShipperFactory().GetDefault();
  27:                  shipper.Ship(order);
  28:              }
  29:   
  30:              return CreateStatus(isValid);
  31:          }
  32:   
  33:          private void Collect(Order order)
  34:          {
  35:              User user = _userContext.GetCurrentUser();
  36:              Price price = order.GetPrice(_exchange, _userContext);
  37:              _receivable.Collect(user, price);
  38:          }
  39:   
  40:          private SuccessResult CreateStatus(bool isValid)
  41:          {
  42:              return isValid ? SuccessResult.Success : SuccessResult.Failed;
  43:          }
  44:      }
  45:  }

Notice specifically that IRateExchange is NOT a dependency of OrderProcessor at all.  It is actually needed by an aggregate root, Order, so that it can do the price conversion based on exchange rates and prices.  This particular design attempted put put that logic as close to the domain model as possible (inside an aggregate).  This code works, but it requires the caller to pass through the dependency.  Here is the Order class:

   1:  using System;
   2:   
   3:  namespace DIAntiPattern
   4:  {
   5:      public class Order
   6:      {
   7:          public DateTime Placed { get; set; }
   8:          public string OtherInfo { get; set; }
   9:          public Price GetPrice(IRateExchange exchange, IUserContext userContext)
  10:          {
  11:              User currentUser = userContext.GetCurrentUser();
  12:              Currency currency = userContext.GetSelectedCurrency(currentUser);
  13:              int priceInSelectedCurrency = exchange.Convert(GetPrice(), currency);
  14:              var price = new Price{Currency = currency, Value = priceInSelectedCurrency};
  15:              return price;
  16:          }
  17:   
  18:          private int GetPrice()
  19:          {
  20:              //do work to aggregate prices from line items, and total up order.
  21:              return 1000;
  22:          }
  23:      }
  24:  }

There are plenty of options to fix this code, and I’m sure you will comment on the one you prefer.  The SMELL here is constructor over-injection.  The injected dependency isn’t a dependency, and another dependency is sometimes a dependency of a particular supported operation of a class.

However you fix this example, IRateExchange does not deserve to be constructor-injected into OrderProcessor.  Next, LineItem will need a dependency to calculate something, and then the dependency has to flow through from an object that is managed by the IoC container.

IoC containers are just tools, but we still have to be careful of constructor over-injection. 

I welcome the comments, and don’t forget to download the code (and fork it to post about your own counter example). 

Constructor over-injection anti-pattern

Check out http://jeffreypalermo.com/blog/constructor-over-injection-smell-ndash-follow-up/ for a follow-up

I’m interested in structure.  We hear lots of talk about convention over configuration.  I’m all for structure over convention (over configuration).  This post is about laying out some code that is an anti-pattern.  It uses 100% constructor injection.  This code makes it easy for a container to bootstrap the construction of the objects, but let’s take a look at why this specific scenario is an anti-pattern and what design would be better.

Example

I have an order processing application that gets 10 orders at a time and tries to process them to shipping.  There are some validation steps, and then there is some work to ship the order.  Here is our Main() method:

   1:  public static void Main()
   2:  {
   3:      DateTime startTime = DateTime.Now;
   4:      Console.WriteLine("Begin: " + startTime.TimeOfDay);
   5:      IEnumerable<Order> orders = GetNextTenOrders();
   6:   
   7:      foreach (var order in orders)
   8:      {
   9:          IOrderProcessor processor =
  10:              ObjectFactory.GetInstance<IOrderProcessor>();
  11:          SuccessResult successResult = processor.Process(order);
  12:          if (successResult == SuccessResult.Success)
  13:          {
  14:              RecordSuccess(order);
  15:              continue;
  16:          }
  17:   
  18:          ReportFailure(order);
  19:      }
  20:      DateTime endTime = DateTime.Now;
  21:      Console.WriteLine("End:   " + endTime.TimeOfDay);
  22:      Console.WriteLine("Total time: " + endTime.Subtract(startTime));
  23:  }

Let’s just run it:

image

Hmm.  This little example code took over 7 seconds to run.  Given that I’ve stubbed out all implementations, it should just breeze through.  Here is the code of OrderProcessor, which is the class that is wired up to IOrderProcessor.

 

   1:  public class OrderProcessor : IOrderProcessor
   2:  {
   3:      private readonly IOrderValidator _validator;
   4:      private readonly IOrderShipper _shipper;
   5:   
   6:      public OrderProcessor(IOrderValidator validator, IOrderShipper shipper)
   7:      {
   8:          _validator = validator;
   9:          _shipper = shipper;
  10:      }
  11:   
  12:      public SuccessResult Process(Order order)
  13:      {
  14:          bool isValid = _validator.Validate(order);
  15:          if (isValid)
  16:          {
  17:              _shipper.Ship(order);
  18:          }
  19:   
  20:          return CreateStatus(isValid);
  21:      }
  22:   
  23:      private SuccessResult CreateStatus(bool isValid)
  24:      {
  25:          return isValid ? SuccessResult.Success : SuccessResult.Failed;
  26:      }
  27:  }

 

 

Ok.  Standard constructor injection.  The anti-pattern is that one of these constructor arguments is really not a class dependency.  The problem is that the constructor of OrderProcessor is too greedy.  It doesn’t need IOrderShipper all the time, but it requires it ALL THE TIME.  In fact, this company finds that 30% of orders are not valid the first time around.  This particular implementation if IOrderShipper is a little bit expensive to create (like ISessionFactory of NHibernate is expensive to create).  Forcing the creating when the false branch of the IF statement would render it useless is the smell.

Just for transparency, here is OrderShipper:

   1:  public class OrderShipper : IOrderShipper
   2:  {
   3:      public OrderShipper()
   4:      {
   5:          Thread.Sleep(TimeSpan.FromMilliseconds(777));
   6:      }
   7:   
   8:      public void Ship(Order order)
   9:      {
  10:          //ship the order
  11:      }
  12:  }

If you are truly coupling yourself to an abstraction (the interface), you should now care how the abstraction is implemented.

You might say:  “What?  Just move that long-running work to the Ship()

method!”

I would agree with that if you were designing the OrderShipper class.  That only puts very elusive semantic coupling on all your classes.  What you are really assuming is:  I will code to interfaces. . . AND. . . as long as all of the implementations have constructors that don’t do much work, my whole application should work. 

I am not decrying constructor injection as a useful method.  In fact, we at Headspring do more constructor injection that abstract factory resolution.  However, constructor arguments are API artifacts that shout loudly: “I can do NOTHING unless you pass these things in.”  If that isn’t true, then don’t make the constructor announce a lie.

Cleaning up the smell

We can modify OrderProcessor to use an abstract factory and only require an IOrderShipper if the order is valid.  Here is the new run:

image

Down from 7 seconds to less than 1.  Why?  Because the invalid order did not need to be shipped. 

Here is the new OrderProcessor:

   1:  public class OrderProcessor : IOrderProcessor
   2:  {
   3:      private readonly IOrderValidator _validator;
   4:   
   5:      public OrderProcessor(IOrderValidator validator)
   6:      {
   7:          _validator = validator;
   8:      }
   9:   
  10:      public SuccessResult Process(Order order)
  11:      {
  12:          bool isValid = _validator.Validate(order);
  13:          if (isValid)
  14:          {
  15:              IOrderShipper shipper = new OrderShipperFactory().GetDefault();
  16:              shipper.Ship(order);
  17:          }
  18:   
  19:          return CreateStatus(isValid);
  20:      }
  21:   
  22:      private SuccessResult CreateStatus(bool isValid)
  23:      {
  24:          return isValid ? SuccessResult.Success : SuccessResult.Failed;
  25:      }
  26:  }

 

 

Because we don’t require any implementation of IOrderShipper (line 15) unless the order is valid, our code is simpler.  The class itself has 1 fewer class-level dependency, and only one method has the extra dependency.  We employ a new type, OrderShipperFactory  to keep the Inverted Control where OrderProcessor still doesn’t know the concrete implementation.  There is one more step because factories need start-up configuration.  If you are currently using an IoC container, you are familiar with start-up configuration because you configure the container’s global factory at start-up time.  Here is the code for the factory:

 

   1:  public class OrderShipperFactory
   2:  {
   3:      public static Func<IOrderShipper> CreationClosure;
   4:      public IOrderShipper GetDefault()
   5:      {
   6:          return CreationClosure();//executes closure
   7:      }
   8:  }

 

And here is the method that configures this factory at start-up time:

   1:  private static void ConfigureFactories()
   2:  {
   3:      OrderShipperFactory.CreationClosure =
   4:          () => ObjectFactory.GetInstance<IOrderShipper>();
   5:  }

 

Notice that the IoC container is still in control over creating the concrete implementations, but the abstract factories keep the production code dependencies inverted without being greedy toward optional dependencies.

Counter Argument

Ok, well, then I’ll just create ONE factory like this and use it everywhere:

   1:  public class GenericFactory
   2:  {
   3:      public static Func<object> CreationClosure;
   4:      public T GetDefault<T>()
   5:      {
   6:          return (T) CreationClosure();//executes closure
   7:      }
   8:  }

 

This factory will ONLY work with an IoC container that has the same semantics as the one you are currently using.  For instance, you still need to unit test the code that uses the factory, so you will have to implement a stub for the factory (and unit tests don’t have expensive dependencies like IoC containers).  Bottom line:  this API is hard to implement by coding by hand.  Any API that is hard to implement is a bad API.  You want factories to be explicitly, and a method or class that can create anything????

Hmm.  Isn’t that Activator.CreateInstance()?  But even that is limited because it doesn’t do constructor argument chaining. 

Bottom Line

Architecture and structure are agnostic of tools.  IoC containers are just tools.  Your design should be robust with or WITHOUT them.  Taking away the IoC container should not make the structure of the application crumble.

Why do we use an IoC container, then?  Because of the DRY Principle.  It keeps us from having to write lots of abstract factory implementations that are essentially the same except for one line.  It keeps each class from having a factory call from the no-arg constructor passing in the dependency to the greedy constructor.  IoC containers have limited the need for hand-coded factories, but they have not eliminated the need.

The inspiration for this article came while I was sitting in a workshop where Matt Hinze was teaching a class about Inversion of Control (one of the public workshops that Headspring puts on each month).  I thought about the response to Robert Martin’s recent blog post (which I quite like).  Then a student in the class recalled a project where constructor injection was used everywhere.  They felt the pain that is sure to come from this constructor over-injection anti-pattern.

One final word:  Don’t be in a hurry to agree or disagree with me.  Take the time to ponder.

UPDATE: Good discussion below.  I've expanded the code sample in an attempt to make this code smell more obvious (because in reality, we don't fret over 2 constructor arguments.  We fret about 5, 10, 20).  New post here: http://jeffreypalermo.com/blog/constructor-over-injection-smell-ndash-follow-up/

Headspring MVC Boot Camp review

Jimmy Bogard taught the last installment of Headspring’s ASP.NET MVC Boot Camp training class last week.  Charlie Solomon wrote a thorough review of the class.  It was a very interesting read.  Here is an excerpt:

“Great training, I would highly recommend anything these guys offer. I enjoy a fast pace, hands on (lots of programming exercises) style of training, and that's what I got. Jimmy is a good teacher... I already knew that, since I've been reading his blog for the past year or so and I've picked up a lot a good pointers to things that help me in my work. He is also a good communicator teaching in front of a room full of diverse programmers. If you are new to MVC like I am, this course is great for introducing concepts that may be new to web forms programmers... but like the MVC book that Jimmy co-authored, the class goes way beyond the introduction by showing how they leverage some of the features in MVC (ActionFilters and ResultFilters, HtmlTemplates, Model binding and validation...) to build applications quickly that are easier to maintain. We used the release candidate of ASP.Net MVC 2 in class.”