This blog is moving. I’ve decided to make a fresh start at Coffee Driven Developer. Please join me over there.
I’m finally ready to say goodbye to Hungarian notation. I’m not just talking about strFirstName, nIndex, or even wcstrzCategoryCode. Those kinds of attacks on readability have finally disappeared like polio and small pox. I’m talking about prefacing an interface with an upper-case ‘I’.
I recently had a discussion with a respected co-worker on this. His argument was that folk expect to see an interface prefixed with an ‘I’. I get it. I even like to use it myself for humor: ICanBeClicked, ICanBeTypedIn, etc… However, my counter-argument was particularily good I thought. The ‘I’ adds nothing in terms of its meaning or readability. Moreover, it doesn’t matter if the interface happens to be an interface or an abstract class (or even a concrete class for that matter). The ‘I’ is a hold over from the dark days of VB4, COM programming, and other things that shall not be named.
It’s taken a while for me to get here. Hi, my name is Jeff, and I’m a recovering Hungarian notation user.
Using an IoC is one of those things that can take a time or two to understand where it fits in and how it’s useful. Once you cross the energy barrier, it’s a color in your palette you can’t imagine missing.
Imagine having a QuestionController that takes an interface called DomainRepository. The job of any concrete implementation of the DomainRepository will be to fetch various domain entities from a backing store.
public class QuestionController : Controller
{
private DomainRepository _repository;
/// <summary>
/// Initializes a new instance of the <see cref="QuestionController"/> class.
/// </summary>
/// <param name="repository">The domain repository provides a source for the domain model</param>
public QuestionController(DomainRepository repository)
{
_repository = repository;
}
//
// GET: /Question/List
public ActionResult List()
{
var questions = _repository.GetQuestions();
return View("List", questions);
}
You’d like to use dependency injection to provide the concrete implementation so that you could switch it up for a mock or stub when testing, a Linq to SQL implementation during production, and to make switching to something else an easy task if needed in the future.
The gotcha is that ASP.NET MVC, by default, requires its controllers to have default constructors. Luckily, ASP.NET MVC uses a ControllerBuilder to instantiate the controllers using a ControllerFactory. This is an extension point where we can provider our own factory, one that uses the IoC of choice to resolve the controller.
First create the new ControllerFactory. Here, I’m using StructureMap as my IoC of choice, but this is all it takes.
public class StructureMapControllerFactory : DefaultControllerFactory
{
protected override IController GetControllerInstance(Type controllerType)
{
return ObjectFactory.GetInstance(controllerType) as IController;
}
}
Then in your bootstrapper, or in application start of your Global.asax, simply set the ControllerFactory
ControllerBuilder.Current
.SetControllerFactory(new StructureMapControllerFactory());
An IoC container is a wonderful tool. It will now figure out how to construct the requested controller, and if that controller requires something else, how to make that, and if that something else requires something else, and so on, and so on…
The way concrete types are registered to their interfaces varies based on the container. For structure map, the following entries in the bootstrapper suffice for this example.
ObjectFactory.Initialize(factory =>
{
factory.ForRequestedType<DomainRepository>()
.TheDefaultIsConcreteType<FakeDomainRepository>();
});
I’ve been working on a high-level “DSL” for automating acceptance tests on web sites. Currently, the two drivers that manipulate the browser can be either Selenium RC or SWAT.
When using IE7 as the browser on Selenium I received that arcane message: “Permission denied on session b08dbc4413c34824ad65a61115845b8a”. The forums were a little obtuse, but one thing that helped was changing the browser string from *iexplore to *iehta. It was still a little flaky. The key was calling WaitForPageToLoad.
Perhaps it was a case of RTFM, but after changing the browser command to *iehta, I noticed this message:
you appear to be changing domains from http://localhost to http://www.google.com
Permission denied’ from the browser (unless it is running as *iehta or *chrome
The combination of using the right browser command and calling WaitForPageToLoad did the trick.
Visualizing Your Blog
I've been into data visualizations lately. I'm inspired by code_swarm and wordle.
Here's the wordle of my blog:
There are a lot of really great detailed posts about databinding in your XAML application, in both Silverlight and Avalon (WPF). This isn't one of them :). This post will focus on the mechanics for a couple of ways you can make databinding work. There are many other, and arguably better, ways of doing these same simple things. I'm constantly suprised by how flexible WPF and XAML are in how they can be programmed; which is great when your wild and creative ideas work, and horrible when you can't accomplish the simpliest thing.
Binding Syntax
The basic syntax is pretty simple. This little snippet of XAML sets the Text property of the TextBlock to whatever the value of the LocalTime property is.
The curlies inside the attribute tell the XAML parser there's some magic code inside. Binding is one of the keywords. Where did the LocalTime property come from? Enter the DataContext.
Setting and Changing the DataContext
The DataContext is the name of the control's (page's) property for the source of the data. This little application:
consists of an un-named TextBlock and a button called the announceTimeButton. The DataContext is set in two places; the constructor and in the button's event handler.
The LocalInformation class is a little class which serves as this application's "ViewModel" (i.e., the thing you bind your XAML controls to). For reference, here's the source for that class:
What if you didn't want to new up a different instance for some reason? What if the LocalInformation class was expensive to construct, or if, gosh darn it, you were just tickled
to be programming in a statefull environment again. Enter INotifyPropertyChanged
Implement INotifyPropertyChanged
I'll change the page's code to use a statefull instance of the LocalInformation class. I'll set the DataContext initially in the constructor, but leave it alone after that. Don't worry the binding
defined in the XAML will stick.
When the announceTimeButton is clicked the LocalInformation object will be tickled, and the magic that comes from having your "ViewModel" implement the INotifyPropertyChanged interface will kick into action. All elements bound to the affected properties will be, ummmm...re-bound? Notice the special new UpdateLocalTime method:
For the purpose of this example, I put the firing of the PropertyChanged event inside this method. Most of the time you'll see this refactored into it's own method so that all the properties of the class can take advantage it. The name of the property that is being updated is passed through the PropertyChangedEventArgs. The only other important change to our LocalInformation class is the addition of the interface itself, which forces the edition of the PropertyChanged event.
Automatic Updates
So, what if you wanted some thread or timer to update the local time automatically. After all, pushing that button is awfully tedious. I know what you're thinking, you'll make some sort of "timer", and on it's callback you'll call UpdateLocalTime. Well, you're close. A plain old timer will work, you just have to be carefull that the call to fire the PropertyChanged event makes it back on to the same thread that's running the UI (like good ol' WinForms). This is completely possible with a class called the Dispatcher, so if you wanted to but it in your model, you'd need to pass it in or get it...yadda, yadda, yadda.
Luckily, this common scenario is all encapsulated by another class called the DispatcherTimer (clever name isn't it). I'll make this part of my view model and initialize it in the constructor.
Then I'll add the tick handler and public methods to start and stop the timer.
Notice the smooth databinding in the following application:
The point here is that the property update won't be seen unless it happens on the UI's thread.
Magical Databinding
There's a lot not covered here. It's just the basics as I've learned them. We didn't talk about the binding mode or dependency properties or a thousand other things that come into play when building a Silverlight UI out of XAML. In Silverlight, there are definitely more than one way to do just about anything. Databinding in general is one of the cornerstone concepts around WPF and Silverlight.
Note: This app was created using Silverlight 2.0 Beta 2
Help Me. I See Spots
Something you'll hear over and over again about Avalon (WPF) and Silverlight is how different it is when compared with more established UI platforms: like WinForms, HTML, ASP.NET, etc... I came face to face with this when I wanted to write a little spike that placed a dynamically generated user control wherever I clicked the mouse. Here's a screenshot of the application in all it's splendor:
Wait a minute! Go ahead and try it out in the little blue area below.
How This Works
The page is really simple.
Notice that it doesn't contain any elements other than the TextBlock with the instructions. The Canvas element ties the MouseLeftButtonUp event to an appropriately named event handler which will serve as our click event.
Next is the XAML markup for the "ball". This is the user control that we'll create dynamically.
The Width and Height are "intentionally left blank" because we're going to dynamically set the size of the ball as well as it's position.
Positioning the user control is the tricky part. If you were declaring the user control in the page's XAML, you could simply use the attached properties of Canvas.Top and Canvas.Left. The trouble with the dynamic control, is that in the code behind there are no positioning properties like you might expect (X, Y, Left, and Top), and the attached properties are nowhere to be found.
My solution was to supply the control with a render transformation. Specifically, I tie a TranslateTransform at construction time. I explose an X and Y property on the control itself, and alter the transform in the setters.
15 public partial class Ball : UserControl
16 {
17
18 private const double DefaultRadius = 25.0;
19 private const double DefaultX = DefaultRadius;
20 private const double DefaultY = DefaultRadius;
21
22 private double _x;
23 private double _y;
24
25 private TranslateTransform _translation =
26 new TranslateTransform();
27
28 public double X
29 {
30 get
31 {
32 return _x;
33 }
34 set
35 {
36 _x = value;
37 _translation.X = _x - Radius;
38 }
39 }
40
41 public double Y
42 {
43 get
44 {
45 return _y;
46 }
47 set
48 {
49 _y = value;
50 _translation.Y = value - Radius;
51 }
52 }
53
54 public double Radius { get; private set; }
55
56 public Ball() : this(DefaultRadius)
57 {
58 }
59
60 public Ball(double r)
61 {
62 validateConstructor(r);
63 Radius = r;
64 Width = 2 * r;
65 Height = 2 * r;
66 RenderTransform = _translation;
67 InitializeComponent();
68 }
69
70 private static void validateConstructor(double r)
71 {
72 if(r <= 0.0)
73 {
74 throw new ArgumentException("Please provide...
75 }
76 }
77 }
The page simply news up a Ball and sets the x and y according to the mouse click.
21
22 private void LayoutRoot_MouseLeftButtonUp(object sender, ...
23 {
24 Point clickPoint = e.GetPosition(LayoutRoot);
25 Ball b = new Ball( );
26 b.X = clickPoint.X;
27 b.Y = clickPoint.Y;
28 LayoutRoot.Children.Add(b);
29 }
30
Download the Code
I decided, I'd try out Preview 4 tonight. In honest to goodness TDD form, I wrote the following test:
13 [TestFixture]
14 public class EmployeeControllerTests
15 { 16 [Test]
17 public void List_Should_Render_View_Of_Employees()
18 { 19 var controller = new EmployeeController();
20 var result = controller.List() as ViewResult;
21 Assert.IsNotNull(result);
22 Assert.AreEqual("List", result.ViewName); 23 }
24 }
The code for the controller is:
9 public class EmployeeController : Controller
10 { 11 public ActionResult List()
12 { 13 return View();
14 }
15 }
The test fails. The name of the view is null (assertion on line 22 of the test method). Why in the name of all that is ScottGu would this basic test fail? In the actual view, when rendered through the view engine, the view name is "List" as expected (that's the job of the parameter-less call to the controller's View method).
Testing of the controller in isolation is still not fully baked. There still seems to be some disconnect in one of the fundamental goals of the framework: make it easy for Morts like me to write testable code.
Generic List Doesn’t Support the Query Pattern
I recently wrote similar code to this little fragment (this is a sanitized version for the purpose of this example).
12
13 List<int> nums = new List<int> { 0, 1, 1, 2,
14 3, 5, 8, 13, 21 };
15
16 var evenQ = from n in nums
17 where n % 2 == 0
18 select n;
19
I was shocked when I received this error message

WTF! What do you mean, a list doesn’t support the query pattern!? That’s absolutely ridiculous. I’m quiting C# development, and I’m converting to writing Rails apps on the Mac….
We interrupt this moment of panic for the following public service announcement:
Developers, do you get tired of reading those pesky error messages? Me too, but remember the compiler team has gone through a lot of trouble to tell you when you’re an idiot and help you recover. Take it from me, if you read the entire error me sage instead of the first half sentence, you’ll be better informed of why you’re such a bonehead and more likely to recover. Now back to our regularly scheduled moment of sanity.
...”missing a using directive?”. Yes, as it turns out I prematurely used one of my favorite VS features: remove and sort using statements.

All is well, and the universe is in a causal state again. Turns out that if you don’t have any dependencies on statements or extensions in System.Linq “remove and sort” will remove the LINQ using statement (duh), and thus all the LINQ goodness will be hidden from the compiler.
Simply adding using System.Linq; fixed this particular goof. Yes, perhaps I’ll read the entire error message next time.
The Post I Should Never Have Written
I spent the entire month of April, writting and re-writting this post. You see, I used to work for Motorola. As a matter of fact, all combined I worked for them for a total of nearly 13 years. Some of my original drafts blasted middle management, upper management, CEOs, and pointed out all that was wrong with the company.
I finally decided to shelve the burn Motorola post. Motorola is burning by itself without any additional help from me. I will say one thing, the one thing that I feel doomed Motorola, more than any of its problems with management: Motorola forgot that it survived by providing a place for people to innovate. The company started treating everyone like an interchangeable commodity. The company turned its back on being loyal towards its people, and as a result the company lost the loyality of its people—mainly through fear. The end result was the company cutting its own lifeline: innovation.