A Life Changing Event

After almost 8 years at Asynchrony, I resigned my position as VP of Engineering on Thursday to take a new position working with some of my old friends. The times at Asynchrony were some of the best times in my career, and I feel privileged to have worked with so many bright, driven, passionate people. The reason for this move has nothing to do with Asynchrony – I consider them to be one of the good guys in the industry. They get Agile there, they get Lean/Kanban, and they get delivering quality software. I will miss them, I will  miss the challenges, and I will miss calling myself an Asynchronite.

But, old chapters close in our lives, and new chapters open, and this is one of those times.

I have accepted a position with Tier3, working alongside my old Patterns and Practices friends, Jim Newkirk, Scott Densmore, Tim Shakarian, Brad Wilson, Ade Miller (I think there are one or two more that I’m leaving out, but I only heard the whole list once. Apologies if I left someone off), as well as other teammates I’m very eager to meet. In my new role, I will be Product Owner, community leader, and one of the public faces of Tier3’s Platform as a Service family of offerings. And I even get to write some code!

I have a ton to learn, about the space, the product, the team and people, and that’s probably just touching the surface. I’ve been consulting, mentoring, and training for half of my career, and I’m excited about moving back into the product world. I get to work with world class engineers and an exciting company to create, to quote Ron Jeffries’ words from oh, so long ago, Something Magnificent.

new Chapter().Next().Open();

– bab

Posted in Uncategorized | Comments Off

Re-energizing a Standup Meeting with Kanban

Problem: Standup meetings are more like status meetings than a collaboration meeting for the team.

Symptoms: 

  • The whole standup meeting is run by the Scrum Master, with no one doing or saying anything until called upon.
  • People on the team report their status back to the Scrum Master or team lead. No one or few people speak to the rest of the team, and interaction between people is pretty rare.
  • Its difficult for people to gain an integrated picture of team status and progress across all the user stories. Individuals report around a circle, describing their progress against individual tasks on user stories, but no one is reporting on or focusing on the progress of the stories themselves.

In summary, all the data reported in the standup meeting is focused on reporting task status back to the Scrum Master, little collaborative conversation occurs, and no complete picture of progress in delivering user stories is to be found.

Solution: Change the standup meeting to focus on collaboration and the flow of value through the team. Change the level of conversation from talking about tasks, which represent effort, to talking about the user stories promised for the current iteration. Doing this promotes cross-team member discussion about the work and how they can complete it. This takes the Scrum Master out of the middle of the conversations and lets the team talk about what matters to them.

Method: The way I help teams focus more on the flow of user stories and value is to make the stories more visible parts of the standup. The Scrum Task Board is fine for showing the flow of tasks through their workflow, but user stories have other elements to their workflow, such as any sort of code reviews or business focused reviews. After getting the team in the habit of talking about tasks and their states, just to get them used to talking about their work, I like to introduce a Kanban board.

Kanban boards are used to represent both the course user stories take from the time a team starts working on them through the time that a team delivers that story, and the current status of all of the stories in play for that sprint. Having this visual representation of the work has a drastic effect on the standup and the team. They stop looking at me, the Scrum Master, and they start looking at the board. They start talking about the stories, where they are, what issues they need help with, discussions about when they’ll be finished with their current phase of work and ready to be moved forward… In other words, they begin collaborating. Its magical :)

For those of you who have never seen a Kanban board, this is what one looks like:

image

This board models the workflow defined by the team. In this case, stories committed to the sprint begin in the Sprint Backlog column, and then move through Story Review, Development, Testing, Review, and then finally Done. During a sprint, small cards that represent each user story move across the board from left to right representing the work done to each item. Here is a board populated with work:

image

Here we see user stories in varies stages of completion. Having this board as the focus of the standup allows the team to talk about the progress of user stories, and not get overly concerned with low level details that confuse the big picture.

Conclusion: On the team that I’ve been coaching for the past couple of months, introducing a Kanban board was the key to changing the standup meeting from being an exercise in status reporting to a productive, useful collaborative event. We learned how to focus on issues and the flow of value throughout our sprint, and to ignore the noise of personal status. Unanimously throughout the team, we agree that our new standups are much more productive in helping us deliver on our promises each sprint.

Posted in Uncategorized | Comments Off

“You get what you measure” versus “What you measure, you can manage” – The Agile Metrics Dichotomy

(I just reinstalled Windows Live Writer and reconnected it to my blog, and it pulled down some drafts I wrote years ago. So, I have no idea when I actually wrote this, what the context was that was in my head, but it seems like a decent article. So I’m posting it :))

I’ve long been a fan of the “You get what you measure” school of metrics doubters, especially in agile projects. Its really easy to decide to measure something, have the people being measured act in a totally predictable and rational way, and screw up a team beyond belief. For example, if I measure how productive individual programmers are, then its to the advantage of individuals to focus on their own work and spend less (or no!) time helping others. Completely kills teamwork :(

On the other hand, in our environment, where we are responsible for delivering projects to clients on time, on budget, etc, we have a responsibility and an obligation to know what is happening in each of our project teams. Management needs to know if we’re going to make our deadlines, customers need to know what is coming, project leaders need to be able to manage and set expectations, we need to satisfy contractual obligations, etc.

The challenge is to come up with a set of metrics and an unobtrusive way to gather data that allows metrics to be reported to interested stakeholders, and yet does not disrupt the team.

This is my challenge. And what follows are the basic metrics I’ve been using as a way of meeting that challenge. These metrics are balanced between measuring things that meaningfully describe what’s happening inside teams, and creating the right environment and behaviors that will help the team reach its goals rather than incent poor behavior.

How Fast Are We Going?

The gold standard of progress on an agile team is its velocity. This can be measured in story points per week for teams following a more “traditional” agile process like Scrum or XP, or it be measured in cycle time for those teams that have evolved to a Lean or Kanban approach. The team I’m coaching now is somewhere in the middle, closer to Scrumban.

So our standard metric is points per week. We measure weekly, and our measurements are reasonably accurate, varying between 25 and 30 points a week. We have the occasional week when we’re significantly below this, and some weeks where we way overachieve. Our historical velocity chart looks like this:

At first, our velocity varied a lot, mostly because we were still learning the codebase (this project has a large legacy codebase that we are adding functionality to). As of late, though, we’ve become a lot more consistent in what we finish each week. Not perfect, but a lot better.

But What About Quality?

Measuring velocity is not enough, as teams can find ways to go faster when pressed to do so. This is a great example of measuring something that is going to create the wrong behavior. If a team is rated on how fast they go, they are going to go as fast as they need to. They’ll either cut corners and quality will slip, or they’ll inflate the estimates to make the numbers start to look better without actually accomplishing anything more.

What I’ve found is that the best way to avoid incenting the team to cut corners is to keep an eye on quality, too. So, in addition to tracking  velocity, I also track defect counts. These charts look like this:

 

This shows our weekly quality over time since the beginning of our project. We started off pretty high, put in some good effort to get our quality back under control, and have done a decent job of keeping it under control most of the time.

Looking at the Bigger Picture

What I do is to use these two metrics together to help me understand what’s happening on the team and to ask questions about what may be causing ebbs and flows in velocity or quality. We did a good job of keeping the defect count pretty low during February and March, but the count crept back up, pretty quickly, to 20 or so active defects by the beginning of April. It was towards the end of this relatively quiet period that the time began to feel pressure to deliver more functionality more quickly. They did what they thought was best and focused more on getting stories “finished” without spending quite a much time on making sure everything worked. They worked to what was being measured.

Up steps Project Manager Man (that’s me, for those of you following along at home), and I was able to point out what was happening with quality and, with their help, relate that back to the feeling of pressure they were feeling. Together, we came up with the idea that velocity and quality have to improve together or teams create false progress. I helped the team manage this mini-issue on their own by pointing it out to them through metrics.

The Final Velocity/Quality Metric

As a way to keep an eye on the general trend of where the work is going on the team, I also track time spent working on Acceptance Tests versus time spent fixing defects (defects include stories that are kicked back from QA or the Product Owners prior to acceptance) versus time spent developing. My feeling is that if we can maximize development effort and minimize defect remediation time, then the team is operating as effectively as it can, given its circumstances.

The Most Important Point About Metrics

Metrics should never be used to judge a team or used to form conclusions about what is happening. They should be treated as a signpost along the way, an indicator of things that are not easily observed in real time but can be measured to point out trends. They should always serve as the starting point for a conversation, the beginnings of understanding an issue. If a manager or executive begins to use metrics as a way to judge a team, the metrics will be gamed and played from that point on. They will become useless, because they will be a reflection of what reality the manager wants to see, rather than what is truly happening.

In each and every one of these cases, I have used the metrics to confirm what I thought I was seeing, as the starting point of a conversation with the team about what they saw happening, and a way to measure the impact of issues on the team. After speaking with the team, the metrics are also useful to judge whether the changes chosen by the team to improve are effective.

Metrics are no substitute for being on the ground with your team, in their team room, pairing with devs and testers, working with product owners, feeling the vibe in the room. Remember, its people over process, right? :)

– bab

Posted in Uncategorized | Comments Off

Looks like I’m speaking at SQE East in Boston, November 12th, 2013!

My good friend Mitch Lacey had to take a step back from a speaking engagement, and he asked me to cover for him to give a half day tutorial on Getting Started With Agile: An Experiential Workshop at the Better Software Conference in November. I’m very excited about doing this talk, both because of the opportunity to speak at this venue and to this audience, and because this kind of talk is so much fun to give.

This session is described as experiential because this talk about Agile and Scrum is planned and execute using Agile and Scrum, With the audience as the stakeholders and me as their “team”, we go through an initial story-gathering process, writing user stories for questions, estimate the questions, put them into a backlog, track metrics, replan and refine, and so on, all while answering the questions posed by the audience.

Doing this talk requires a bit of knowledge and a LOT of courage on the speaker’s part, as the questions can cover literally anything involved with the subject. I’m very glad Mitch has the confidence in me to be able to stand in for him, as his are some very big shoes to fill. Mitch, I’ll do my best not to let you down :)

– bab

Posted in Agile, Speaking | Tagged , , | Comments Off

New blog home

Hey, sorry for the inconvenience. We lost our hosting at our previous site (Thanks, Peter, for doing it for over 5 years!), so I’m reloading all content here, setting up a nice theme, etc. It might take a while, but it’ll eventually get done.

Thanks for your patience…

– bab

Posted in Uncategorized | Comments Off

Test Driving a WPF App – Part 3: Switching to new window

This is the third part in what I hope to be a four-part series about creating a WPF application using TDD to drive the functionality and MVVM to keep everything testable as we go. The idea is to use view models to split away functionality from the view and have it available for testing while not losing any capabilities along the way. If you haven’t read the first two parts,  you may want to do that.

In this part, we’ll see what it takes to have a user gesture, in our case, either a double-click on a row in our ListView or clicking a button, take us to a different page in our application.We’ll write the code to get you to the other window in this post and leave the corresponding code to get back for readers as an exercise, should they want to confirm they understand how this all works. So, here we go.

The end result

At the conclusion of this process, we’re going to be able to start from the opening page, showing players and their numbers:

image

and navigate to this second page:

image

About this time, I’m feeling pretty good about my screen design abilities as well, as these pages are beautiful! (One thing I’ve learned about myself over the years is that I have very little taste when it comes to designing UIs :))

Step 1 – Writing the command logic to command the pages to switch

As before, when we’re adding new behavior based on a user gesture, we start by writing the ICommand class. We do this because it fleshes out both the details of that class, but also because it drives us down the road of creating the interface that the command class is going to use. This interface is going to be eventually implemented by the view model class, the TeamStatControlViewModel in our case. We don’t “officially” know that at this point, though, so we work through this interface, which represents one of the growing number of roles our view model fulfills. Fo more information on this style of development, read this paper by Steve Freeman.

Let’s begin by writing our first test for the command class. This is the test that invokes the behavior that the role we’re collaborating with makes available to us. In keeping with my experiment of creating lots of little fixtures, each of which represents a complete, but individual, behavior of my system, I’ve created a fixture called InterPageNavigationFixtures. My idea is that this fixture will hold all tests that document how navigating between pages works. Our first test:

   1: [Fact]

   2: public void SwitchToPlayerViewStartedWhenViewPlayerCommandExecutes()

   3: {

   4:     var viewPlayerSwitcher = new Mock<IViewPlayerModeSwitcher>();

   5:     ViewPlayerModeSwitchCommand cmd = new ViewPlayerModeSwitchCommand(viewPlayerSwitcher.Object);

   6:  

   7:     cmd.Execute(null);

   8:  

   9:     viewPlayerSwitcher.Verify(s => s.SwitchToPlayerViewMode());

  10: }

Like the other test we created for a command, we define the interface that represents the role we’re going to use, IViewPlayerModeSwitcher, and then our command class. The rest of the test ensures that the correct behavior happens when we invoke the command’s Execute method.

To make this test compile, we have to create some things, including the interface, the command, and some very minimal method signatures in both.

In the ViewModels project, we add the interface:

   1: namespace ViewModels

   2: {

   3:     public interface IViewPlayerModeSwitcher

   4:     {

   5:         void SwitchToPlayerViewMode();

   6:     }

   7: }

as well as the skeleton of the command:

   1: namespace ViewModels

   2: {

   3:     public class ViewPlayerModeSwitchCommand

   4:     {

   5:         public ViewPlayerModeSwitchCommand(IViewPlayerModeSwitcher modeSwitcher)

   6:         {

   7:         }

   8:  

   9:         public void Execute(object parameter)

  10:         {

  11:         }

  12:     }

  13: }

Run test, test fails, implement minimal behavior to make test pass:

   1: public class ViewPlayerModeSwitchCommand

   2: {

   3:     private readonly IViewPlayerModeSwitcher modeSwitcher;

   4:  

   5:     public ViewPlayerModeSwitchCommand(IViewPlayerModeSwitcher modeSwitcher)

   6:     {

   7:         this.modeSwitcher = modeSwitcher;

   8:     }

   9:  

  10:     public void Execute(object parameter)

  11:     {

  12:         modeSwitcher.SwitchToPlayerViewMode();

  13:     }

  14: }

At this point, the test passes, and we can invoke the switching behavior that will be implemented in our view model shortly.

The last thing I was to do here before moving on is to expose the command through the view model so the view can bind to it. A simple test, much like others we’ve seen before:

   1: [Fact]

   2: public void ViewModelExposesSwitchToPlayerViewModeCommandAsICommand()

   3: {

   4:     TeamStatControlViewModel viewModel = new TeamStatControlViewModel(null, null, null);

   5:  

   6:     Assert.IsAssignableFrom<ViewPlayerModeSwitchCommand>(viewModel.PlayerViewMode);

   7: }

   8:  

and we implement this by simply adding an auto-property to our view model called PlayerViewMode.

Part 2 – Making the view model change application modes

In this next, the view model will begin to switch modes in the application between the Player Summary mode and View Player mode. I’m intentionally calling these modes here because I don’t want the view model to know about windows and views and other UI-ish specifics. As far as it is concerned, the application has two modes in which it can work, and someone else is going to be able to translate from the information about modes and transitions to swapping out views and controls. This is purely an example of separating concerns, where the view model only cares about the modes of the application and another class, more than likely in the same assembly as the view logic, will know how to act upon modes switching.

Starting down this road, we’ll write a test that drives out the interface for how we’ll tell something outside of the view model that a mode is changing. We’ll be talking to a role I chose to call the ModeController, commanding it through its PlayerViewMode. Here is the test:

   1: [Fact]

   2: public void ModeControllerCommandedToSwitchToPlayerViewByViewModel()

   3: {

   4:     var modeController = new Mock<IModeController>();

   5:     TeamStatControlViewModel viewModel = new TeamStatControlViewModel(null, modeController.Object, null);

   6:  

   7:     viewModel.SwitchToPlayerViewMode();

   8:  

   9:     modeController.Verify(nc => nc.PlayerViewMode(It.IsAny<Player>()));

  10: }

Since the TeamStatControlViewModel needs access to the mode controller, we had to modify its constructor to take an argument of that type. We call the method we’re trying to drive through the tests, SwitchToPlayerViewMode, and then comes our assertion. Our assertion is a bit interesting here – maybe I’m thinking too far ahead, but I’m considering how the view that is going to eventually be rendered is going to work. Its going to need to know about the player that was selected, so it can show it. In fact, that player is probably going to become its DataContext. To give the new view, which will be rendered by someone else at some other time, access to the player, I’m passing it along here. I’m not writing the code that will actually cause it to be passed yet, as you can see by the It.IsAny<Player> argument in the Verify statement, but I’m declaring that an object of that type is going to be passed to it when the system runs for real. Let’s implement this small step:

First, the IModeController, which sits in the ViewModel sassembly:

   1: namespace ViewModels

   2: {

   3:     public interface IModeController

   4:     {

   5:         void PlayerViewMode(Player player);

   6:     }

   7: }

and then the minimal code in the view model:

   1: public class TeamStatControlViewModel: IApplicationExitAdapter, IViewPlayerModeSwitcher

   2: {

   3:     private readonly IApplicationController applicationController;

   4:     private readonly IModeController modeController;

   5:     private readonly IPlayerRepository playerRepository;

   6:  

   7:     public TeamStatControlViewModel(

   8:         IApplicationController applicationController, 

   9:         IModeController modeController, 

  10:         IPlayerRepository playerRepository)

  11:     {

  12:         this.applicationController = applicationController;

  13:         this.modeController = modeController;

  14:         this.playerRepository = playerRepository;

  15:         ApplicationExit = new ApplicationExitCommand(this);

  16:         PlayerViewMode = new ViewPlayerModeSwitchCommand(this);

  17:     }

  18:  

  19:     public void SwitchToPlayerViewMode()

  20:     {

  21:         modeController.PlayerViewMode(new Player());

  22:     }

  23: }

Please not that I’m only showing the interesting bits here, and removing code that didn’t change from the last time we looked at this class. The bits that did change are an additional parameter to the constructor of this class and the addition of the SwitchToPlayerMode method. Since that method came from the IViewPlayerModeSwitcher, I also went ahead and implemented the interface here. (Note – Since this isn’t a lesson in TDD, I skipped the step of how I used the AddMethodParameter refactoring to slowly add the new constructor and move away from the old one. I didn’t do this in one big step, I did it in small steps, using the tests to guide me to what to change next.)

The next step is to get the player that is selected in the ListView and pass that along in the call, instead of passing an empty player. Here is the test used to drive that:

   1: [Fact]

   2: public void SamePlayerPassedToModeControllerAsSetInViewModel()

   3: {

   4:     var modeController = new Mock<IModeController>();

   5:     TeamStatControlViewModel viewModel = new TeamStatControlViewModel(null, modeController.Object, null);

   6:     Player player = new Player();

   7:     viewModel.SelectedPlayer = player;

   8:  

   9:     viewModel.SwitchToPlayerViewMode();

  10:  

  11:     modeController.Verify(nc => nc.PlayerViewMode(player));

  12: }

There are only small differences between this test and the one before it. The main one is that I’m defining a new property on the view model, SelectedPlayer. A ListView sets this property every time the selected item changes in its view, and this property will allow our view model to be informed about which player is selected at any time. Now we can pass along that player in the PlayerViewMode call, and all is well. Here are the minor changes in TeamStatControlViewModel:

   1: public Player SelectedPlayer { get; set; }

   2:  

   3: public void SwitchToPlayerViewMode()

   4: {

   5:     modeController.PlayerViewMode(SelectedPlayer);

   6: }

Part 3 – Hooking up what we have

Despite the fact that I write a lot of tests for my code, I still like to see it work every now and then! This would be one of those times. We’re at the point now where we should be able to wire up everything we have and get to the point where the mode controller would be able to swap out controls, were we to have implemented that last piece of functionality. Let’s hook up what we got and see what works.

Let’s start by making a couple of quick changes in the XAML. We’ll add a SelectedItem attribute and binding in the ListView and we’ll hook up the ViewPlayer button to the command:

   1: <ListView IsSynchronizedWithCurrentItem="True" Grid.Row="1" VerticalAlignment="Stretch" 

   2:     SelectedItem="{Binding SelectedPlayer}" ItemsSource="{Binding Players}">

   1: <Button Command="{Binding PlayerViewMode}" Grid.Column="0" Content="View Player Stats" 

   2:         HorizontalAlignment="Right" Style="{StaticResource NormalButton}"/>

That should be enough to have the user gestures be sent to our view model.

The view model itself is complete, but we need to make some class implement the IModeController. Again, I think the best place, at least for now, is the App class, so we’ll put that interface there – I do suspect that we’ll eventually pull that out of the App class and make it its own class, so that we can test it, but we haven’t had that need yet. Someday, maybe…

That leaves some very minor changes in App.xaml.cs. We add the interface to the class definition, implement the PlayerViewMode method, and tell the container that App implements the IModeController interface (line 8), which allows it to pass an object of that type to the view model’s constructor.

 

   1: public partial class App : Application, IApplicationController, IModeController

   2: {

   3:     private readonly IUnityContainer container = new UnityContainer();

   4:  

   5:     private void Application_Startup(object sender, StartupEventArgs e)

   6:     {

   7:         container.RegisterInstance<IApplicationController>(this);

   8:         container.RegisterInstance<IModeController>(this);

   9:  

  10:         container.RegisterType<IPlayerRepository, PlayerRepository>(new ContainerControlledLifetimeManager());

  11:         container.RegisterType<TeamStatControlViewModel>(new ContainerControlledLifetimeManager());

  12:         container.RegisterType<TeamStatControl>(new ContainerControlledLifetimeManager());

  13:  

  14:         container.RegisterType<MainWindow>(new ContainerControlledLifetimeManager());

  15:         

  16:         Current.MainWindow = container.Resolve<MainWindow>();

  17:         Current.MainWindow.Content = container.Resolve<TeamStatControl>();

  18:         Current.MainWindow.Show();

  19:     }

  20:  

  21:     public void ExitApplication()

  22:     {

  23:         Current.Shutdown();

  24:     }

  25:  

  26:     public void PlayerViewMode(Player player)

  27:     {

  28:         ;

  29:     }

  30: }

At this point, we’re good to try it out, so start up the application, click on a name, press View Player, and… OK, still nothing happens because we don’t have another window yet. I tested this by putting a breakpoint on line 28 and debugging it to see that I made it to here, which I did, and that the correct player was being sent here. I know my tests told me that this should work, but in the immortal words of Ronald Reagan, “Trust, but verify”.

Part 4 – Showing the other view

We’re in the home stretch now. Let’s show the other view. First, let’s just assume that I created another view. You can see it way back at the top – its the second window you see, with a big name and number in it. Once you’re at this point, all you need to do to enable the app to switch between the main view and this view is to implement the App.PlayerViewMode method correctly. I couldn’t find a way to test this, since I’m manipulating the UI directly, so I just wrote the code:

   1: public void PlayerViewMode(Player player)

   2: {

   3:     Current.MainWindow.Content = null;

   4:  

   5:     Current.MainWindow.Content = container.Resolve<PlayerDetailControl>();

   6:     ((PlayerDetailControl) Current.MainWindow.Content).DataContext = player;

   7: }

A couple things to note here. First, I didn’t register the type, PlayerDetailControl, with the container. The Unity container will do its best to create any object that hasn’t been registered with it by calling whatever constructor it can find that matches up with arguments it knows how to build. In our case, the class has a default constructor, so it knew how to build it. Since we didn’t register it, Unity will just create a new instance of the control for me every time I ask for it. I can then assign the player to be its DataContext, and we’re done. That turned out to be very easy :)

At this point, we should be able to select a player, click on the View Player button, and the other view should appear. Success! But we’re not quite finished yet… sorry! Two more points to make

Part 5 – Double clicking and CanExecute for the command

Before we finish, I want to cover two other things. The first is how to enable double click behavior for the ListView. There isn’t a simple way to attach a command behavior to the ListView in the version of WPF I’m using. I know that AttachedBehaviors are part of the new WPF version that’s in development now, but I don’t have that, so you’re stuck with this explanation :)

Since there wasn’t a way to attach a command to the double-click event, I had to put code into the code-behind page, which is the first time I’ve had to do that yet! I wired up an event handler to the double-click event through a small change in the XAML for the ListView:

   1: <ListView IsSynchronizedWithCurrentItem="True" Grid.Row="1" VerticalAlignment="Stretch" 

   2:     MouseDoubleClick="ListView_MouseDoubleClick"  SelectedItem="{Binding SelectedPlayer}" ItemsSource="{Binding Players}">

and added a trivial handler in the TeamStatControl.xaml.cs file:

   1: private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)

   2: {

   3:     TeamStatControlViewModel viewModel = (TeamStatControlViewModel) DataContext;

   4:     viewModel.PlayerViewMode.Execute(null);

   5: }

All this method does is to call the Execute method of the same command that the button runs. Trivial code. So now we can double-click on a player in the list and the right thing happens.

But what happens if no player is selected (OK, I couldn’t figure out a way to make this happen for the real list view, but it seemed like an interesting example and thought experiment!). We need to implement the CanExecute behavior for the ViewPlayerModeSwitchCommand. As usual, we do this through tests.

In our first test, we confirm that the command cannot execute if no player is selected:

   1: [Fact]

   2: public void ViewModelFunctionalityIsNotOnlyAvailableWhenNoPlayerIsSelected()

   3: {

   4:     TeamStatControlViewModel viewModel = new TeamStatControlViewModel(null, null, null);

   5:     ICommand playerViewModeCommand = viewModel.PlayerViewMode;

   6:  

   7:     Assert.False(playerViewModeCommand.CanExecute(null));

   8: }

and we implement CanExecute as simply as we can to make the test pass:

   1: public bool CanExecute(object parameter)

   2: {

   3:     return false;

   4: }

Our  next test is a little more interesting, as it requires that the CanExecute returns true if a player is selected:

   1: [Fact]

   2: public void ViewModelFunctionalityIsAvailableWhenPlayerIsSelected()

   3: {

   4:     TeamStatControlViewModel viewModel = new TeamStatControlViewModel(null, null, null);

   5:     ICommand playerViewModeCommand = viewModel.PlayerViewMode;

   6:     viewModel.SelectedPlayer = new Player();

   7:  

   8:     Assert.True(playerViewModeCommand.CanExecute(null));

   9: }

The only real modification here is that we use the SelectedPlayer method of the view model to set the player that would be selected through the real view. We expect that the command class is able to query this SelectedPlayer property through its reference to the view model using the IViewPlayerModeSwitcher interface. Well, that’s what we’d expect, anyhow…

   1: public bool CanExecute(object parameter)

   2: {

   3:     return modeSwitcher.SelectedPlayer != null;

   4: }

The SelectedPlayer property isn’t available through that interface, so as our final step along this long and tortuous path, we add it to the interface, our implementation code compiles, our tests all run, and we celebrate by going home early for the day.

Conclusion

I hope people are finding this case study to be useful. I found a lot of different resources on the web about doing bits and pieces of your WPF/MVVM application test-first, but I still had a lot of unanswered questions. First and foremost on that list was how to do simple navigation like I’m doing. By putting together most of a whole application, I hope its more clear to readers how the different pieces fit together.

I do plan on doing one more step along the way, probably posted tomorrow morning (8/25/2009). I want to show how to handle pop-up windows, including windows dialog boxes as well as custom WPF windows. I had to deal with this on my own project, and it took a bit of thinking to figure out how to do it in a testable way.

Until tomorrow!

– bab

Posted in Uncategorized | 1 Comment

Test driving a WPF App – Part 2: Adding some data

This is part two of the blog series about creating a WPF application using TDD to drive the functionality and MVVM to split that functionality away from the view into something more testable. You may want to read part one if you haven’t already.

In this part, we’ll see what it takes to display data on the front page about each player on the softball team. We’re not going to display all their stats, since we don’t need to for the example, but it would be very easy to extend this to do so. (N.B. I have a more full version of this that I’ll post that includes a database backend with more data in it than what I’m going to show here. The data backend is irrelevant to the layer being discussed here, so I’m going to ignore those details.)

The end result

At the end of this process, what we’re going to have is a list of players and their numbers. We could easily extend it to total stats for each of them, but that’s outside the point of the example, and is left as an exercise for the reader (I hated when college textbooks said that!).

image

So anyhow, you can see the 4 players listed and their numbers. This data came from the data repository that I created behind the view, in a class called PlayerRepository. I’m not going to go into the details of how this repository class was created, as the database layer is outside the scope of this article, so we’ll just assume that we created it when it was needed, and I won’t include discussion or tests for it. The important part of us to think about is how the data got into the view model and how it got from there onto the view. And that begins our (short) story.

Step 1 – Get data to the view

In order to get data to the view, the view model needs to expose an ObservableCollection that the view can bind to. I decided to create a property called Players on the TeamStatControlViewModel, driving it through tests. I created a test fixture in the ViewModelFixtures assembly called TeamStatControlPlayersDataBindingFixture, and I put my test into there (as an aside, I’m trying a different style of fixtures here, where I’m naming fixtures after behaviors or features and putting all the tests for those features in that fixture. I’m intentionally trying to break out of the app class <-> fixture class model and create tests around the behaviors of the system, regardless of where those behaviors may lie. Let me know if you like it, please.)

   1: [Fact]

   2: public void ViewModelExposesObservableCollectionOfPlayers()

   3: {

   4:     TeamStatControlViewModel viewModel = new TeamStatControlViewModel(null);

   5:  

   6:     Assert.IsType<ObservableCollection<Player>>(viewModel.Players);

   7: }

 
We have to add the Players property to the view model and create an empty Player class in our Model assembly to get this test to compile. Once it runs and fails, we implement the property in the view model to return an empty ObservableCollection<Player> collection. Run again, and the test passes.

   1: public ObservableCollection<Player> Players

   2: {

   3:     get { return new ObservableCollection<Player>(); }

   4: }

Step 2 – Get the data to the view model

Now that we have the data available to be shown on the view, we need to provide that data to the view model. We do this by giving the view model access to the PlayerRepository we spoke of earlier and letting it query the repository for the data as needed. Again, very simple. Here is the test in that same test fixture:

   1: [Fact]

   2: public void DataIsPulledFromModelWhenRetrievingPlayersFromViewModel()

   3: {

   4:     var playerRepository = new Mock<IPlayerRepository>();

   5:     TeamStatControlViewModel viewModel = new TeamStatControlViewModel(null, playerRepository.Object);

   6:     playerRepository.Setup(pr => pr.GetAllPlayers()).Returns(new List<Player>());

   7:  

   8:     ObservableCollection<Player> players = viewModel.Players;

   9:  

  10:     playerRepository.Verify(pr => pr.GetAllPlayers());

  11: }

The test start driving to define the behavior our system is going to need. We already know that the view model is going to need a reference to the repository, so we add the repository to the constructor arguments for the view model on line 5. (I like working backwards in a situation like this to discover the objects needed. I’ll write the constructor signature first and use that to drive object creation on previous lines, like you see here.) This forces us to create a mock version of the repository, which we do in line 4 by discovering an IPlayerRepository interface, details to be fleshed out. On line 6, we set up the behavior that we want the view model to invoke on the repository, which is the GetAllPlayers method, which for our purposes needs to return an empty collection of the appropriate type. Finally, we invoke the Players property and verify that the repository’s GetAllPlayers method is indeed called.

In getting this to compile, we create the IPlayerRepository interface and modify the signature of TeamStatControlViewModel to take the new IPlayerRepository parameter. Run test, test fails, and we finally implement:

   1: public interface IPlayerRepository

   2:     {

   3:         IList<Player> GetAllPlayers();

   4:     }

and

   1: public class TeamStatControlViewModel: IApplicationExitAdapter

   2: {

   3:     private readonly IApplicationController applicationController;

   4:     private readonly IPlayerRepository playerRepository;

   5:  

   6:     public TeamStatControlViewModel(IApplicationController applicationController, IPlayerRepository playerRepository)

   7:     {

   8:         this.applicationController = applicationController;

   9:         this.playerRepository = playerRepository;

  10:         ApplicationExit = new ApplicationExitCommand(this);

  11:     }

  12:  

  13:     public void ExitApplication()

  14:     {

  15:         applicationController.ExitApplication();

  16:     }

  17:  

  18:     public ICommand ApplicationExit { get; set; }

  19:  

  20:     public ObservableCollection<Player> Players

  21:     {

  22:         get { return new ObservableCollection<Player>(playerRepository.GetAllPlayers()); }

  23:     }

  24: }

At this point, we have data coming from the repository and available to the view. All that’s left is to hook up to the view.

Step 3 – Hooking up to the real view

I’m going to cheat a bit and not define a DataTemplate for this and just directly bind to the two columns I’m going to define, Name and Number. I have a ListView in the middle of my window, as you can see in the screencapture at the top if this post. I define a couple GridViewColumns in it and bind them to Name and Number:

   1: <ListView IsSynchronizedWithCurrentItem="True" Grid.Row="1" VerticalAlignment="Stretch" ItemsSource="{Binding Players}">

   2:     <ListView.View>

   3:         <GridView>

   4:             <GridViewColumn Header="Player" DisplayMemberBinding="{Binding Name}"/>

   5:             <GridViewColumn Header="Number" DisplayMemberBinding="{Binding Number}" />

   6:         </GridView>

   7:     </ListView.View>

   8: </ListView>

Obviously I wouldn’t do this on a real project, I’d use a DataTemplate. But for now, this will do. The ItemSource is set to the Players property, and the two columns are set to the fields I want to show.

We don’t have a real instance of our IPlayerRepository yet, so lets build a really simple one. In real life, this would be a repository over the top of a database, but we don’t need to go that far for now. Let’s just create the simplest repository we can for now:

   1: public class PlayerRepository : IPlayerRepository

   2:     {

   3:         public IList<Player> GetAllPlayers()

   4:         {

   5:             return new List<Player>

   6:                        {

   7:                            new Player

   8:                                {

   9:                                    Name = "Linsey",

  10:                                    Number = "42"

  11:                                },

  12:                            new Player

  13:                                {

  14:                                    Name = "Michelle",

  15:                                    Number = "31"

  16:                                },

  17:                            new Player

  18:                                {

  19:                                    Name = "Susan",

  20:                                    Number = "17"

  21:                                },

  22:                            new Player

  23:                                {

  24:                                    Name = "Joan",

  25:                                    Number = "26"

  26:                                }

  27:                        };

  28:         }

  29:     }

One thing we’re still doing is exposing the Player class to the view. This is not necessarily the best practice that has evolved, since the Player class is defined in the Model layer. The danger is that we may end up needing to add INotifyPropertyChanged behavior to the Player class, which would pollute our domain model with view-specific code. If that were to happen, it would force us to refactor the view model to return an observable collection of something else, like an ObservableCollection<PlayerViewModel>, so that we would have a place to put our view-specific code. We don’t need to yet, so we’re not going to bother. This is a potential refactoring to come, though.

And our final change is to add the PlayerRepository type into our Application_Startup method, so that Unity knows how to build the repository and pass it into the TeamStatControlViewModel:

   1: private void Application_Startup(object sender, StartupEventArgs e)

   2: {

   3:     container.RegisterInstance<IApplicationController>(this);

   4:  

   5:     container.RegisterType<IPlayerRepository, PlayerRepository>(new ContainerControlledLifetimeManager());

   6:     container.RegisterType<TeamStatControlViewModel>(new ContainerControlledLifetimeManager());

   7:     container.RegisterType<TeamStatControl>(new ContainerControlledLifetimeManager());

   8:  

   9:     container.RegisterType<MainWindow>(new ContainerControlledLifetimeManager());

  10:     

  11:     Current.MainWindow = container.Resolve<MainWindow>();

  12:     Current.MainWindow.Content = container.Resolve<TeamStatControl>();

  13:     Current.MainWindow.Show();

  14: }

Compile and run, and all should work.

Conclusion

This was a fairly easy step to take. We exposed a property on our view model to let our view see the data we want to publish. Our view model has a repository injected into it to let it get the data as needed. That was really all there was to it. Two tests, and we got to where we needed to be.

The next step along the way will involve navigating from the front page to a player detail page. Stay tuned for the next installment, coming right up!

– bab

Posted in 111, 112 | 1 Comment

Using Unity to make Singleton-ness an implementation detail

The most common, canonical use of the Singleton pattern irritates me. Every time I see it, I think, “The singleton-ness of a class is an implementation detail, and shouldn’t leak out through that class’s interface.” Yet, that’s what it always does.

In the usual implementation, someone decides that some new class they’ve written is so resource critical, or so standalone, or so useful that they can have only one instance of that class and that instance has to be visible everywhere. Ignoring the intricacies of threading and so on, a Singleton usually looks exactly like this:

   1: public class MyImportantResource

   2: {

   3:     private static MyImportantResource instance;

   4:  

   5:     private MyImportantResource()

   6:     {

   7:         // ...

   8:     }

   9:  

  10:     public static MyImportantResource Instance()

  11:     {

  12:         if (instance == null) instance = new MyImportantResource();

  13:         return instance;

  14:     }

  15: }

And it gets used everywhere like this:

   1: public class Consumer

   2:     {

   3:         public Consumer()

   4:         {

   5:             var importantResource = MyImportantResource.Instance();

   6:             importantResource.FooTheBar();

   7:         }

   8:     }

Now what happens when I decide I want two of these? Or I decide that I want to let people create as many of these resources as possible? Or, even more commonly, what happens when I want my Consumer class to use a mocked out version of MyImportantResource? I’m scre^h^h^h^hin trouble.

The trouble comes from the fact that Consumer is reaching out into the ether and grabbing the resource it needs on its own. It isn’t giving me, the developer, control over what type of ImportantResource to use or where the ImportantResource is coming from. The Inversion of Control principle is being violated by having the class gather its own resources rather than having its creator decide and pass resources to it.

My typical solution

What I typically have been telling people is that it is OK to have a singleton, treat it as a singleton, and love the singleton pattern… within reason. At the point in your code where you’re creating all your objects and wiring them up, you should feel perfectly free to use singletons. But no layer beneath that should have any knowledge of the singleton-ness of a class. Grab that singleton and pass it into whoever needs it, preferably as an interface, and you’ve restored order and testability to your system by again returning to the Inversion of Control principle.

My DI solution

Dependency Inversion containers solve this problem for you automatically. I’ve been using Unity lately, and I’ve grown to really like it. One of the things I really like about it, and I’m sure all DI containers have this property, is that I can register a type with the container and tell it that I only want it to create a single instance of this type and pass it around whenever someone asks for that type. Bam! I have a singleton again, but I’ve completely separated the singleton-ness of the class from its singleton-like usage. Major win. Here is the code that lets me do that.

First, the interface over the important resource:

   1: public interface IImportantResource

   2: {

   3:     void FooTheBar();

   4: }

Now the changes in the MyImportantResource class to bring it back to being a regular class. Note that all mention of singleton-ness is gone from this class. Its just a plain, old class again, which is how we like it.

   1: public class MyImportantResource : IImportantResource

   2: {

   3:     public MyImportantResource()

   4:     {

   5:         // ...

   6:     }

   7:  

   8:     public void FooTheBar()

   9:     {

  10:         throw new NotImplementedException();

  11:     }

  12: }

Next, the changes in the Consumer class that promote the loose coupling encouraged by Inversion of Control, by injecting an IImportantResource at construction:

   1: public class Consumer

   2: {

   3:     public Consumer(IImportantResource importantResource)

   4:     {

   5:         importantResource.FooTheBar();

   6:     }

   7: }

And finally, the object construction code I can write:

   1: public static class Configurator

   2: {

   3:     private static IUnityContainer container;

   4:  

   5:     public static void Main(string[] args)

   6:     {

   7:         container = new UnityContainer();

   8:  

   9:         container.RegisterType<IImportantResource, MyImportantResource>(new ContainerControlledLifetimeManager());

  10:  

  11:         Consumer consumer = container.Resolve<Consumer>();

  12:     }

  13: }

The interesting bit of code here is on line 9, where I register MyImportantResource. I’m telling the container that whenever someone asks for an IImportantResource, it should give them a MyImportantResource object, and that it should give it the same instance every time (that what the new ContainerControlledLifetimeManager()) says. I’ve magically turned my MyImportantResource into a singleton class without polluting the code of that class with statics and instance methods.

Conclusion

Operationally nothing has changed. Assuming people always go to the container for their object instances, MyImportantResource is still a singleton. I will only have one instance of it, it is still accessible from a single place. Should I ever decide to allow 4 instances of it, I can create my own lifetime manager class that will create up to four instances and manage them for me. But now all of my classes are just that, classes. The design decision of how many instances of the resource is separated from the operation of the resource, which allows the two different design issues to evolve separately. And I’ve applied Dependency Inversion to the Consumer class, which allows it to have mock versions of the resource injected to enable testing scenarios that were more difficult when it was using the singleton.

– bab

Posted in Uncategorized | 2 Comments

Test Driving a WPF application using MVVM and TDD

This is a preview of the material I’m going to be presenting at the St. Louis Day of Dot Net in a couple weeks.

Introduction

For those of you who are reading this blog for the first time, I’m pretty much the St. Louis Agile Zealot. Long hair, flowing robes… you get the picture :) I’ve been advocating Agile and XP in St. Louis since around 2000, through speaking at various user groups and local conferences, teaching at local companies, giving talks in the park, dropping leaflets from airplanes, and so on. I live Agile in my day job at Asynchrony Solutions, where I lead their Agile training and mentoring group. I am totally sold on Test Driven Development as the best way for me to write my code, and I’ve been occasionally known to share that opinion with others.

As far as WPF experience goes, I’m still pretty new in my learning curve.  I’ve been playing with a project on my own for a few months, trying new things, reading, and experimenting. When I first started out, I completely wrote a Winforms app in WPF. I used a full-on MVP/MVC architecture, had my button click methods in my window classes, etc. A complete mess… Then I started reading about MVVM and that sparked something inside me that realized that this finally made sense. This was something that gave me a lot of the advantages of the MVP-like architectures, such as being able to test my UI without actually running the UI, but without the overhead of wiring all that junk up myself.

What follows are the lessons I’ve learned in the process of rethinking my original app and in writing this sample app for my talk.

The Application

My daughter plays select softball for one of the organizations here in St. Louis. They have a web site that lists all their stats throughout the year, and I thought it would be fun to mimic that site as a desktop app. The application would list all the girls’ total stats on the front page and give you the ability to drill down into detailed stats for each game on subsequent pages. For fun, I wanted to be able to add stats for new games, and add and delete players. With that set of features, it seemed that I’d be able to drive out a lot of interesting opportunities to change around the design to let me write the code in a TDD manner.

Here is the main page of the application, in all its glory. Remember that I am but a poor developer, with a developer’s eye for style :)

image

The display of stats isn’t complete yet, but it was enough to validate that my data binding was working. Let’s look at what it took to get this far…

Note: If you want to skip the setup stuff and get right to the parts where behavior is added, jump ahead to Step 3.

Our Roadmap

As a quick review, before we dive in, here is an overview of the MVVM design pattern and the players involved.

MVVM Architecture

The View represents the surface that the user interacts with. It is the WPF code, the UI, and XAML… all that stuff that users see and that is hard to test in an automated fashion. Our goal is to take as much logic out of there as possible, to allow us to have the highest amount of confidence and the greatest amount of test coverage that we can achieve.

Next to the View is the ViewModel. The ViewModel represents the entire set of data and behavior contained in the View. It has properties to expose all the different pieces of data that the View will  need to display, and it exposes another set of properties for all the behavior that the View will need to invoke.

The View and ViewModel are tied together in two separate, but very similar, ways. Through Data Binding, data travels between the View and ViewModel automatically. WPF, through the wonders of its internal magic, keeps consistent the data shown in the View and the data held in the ViewModel. There is a bit of work that we have to do to ensure this happens, but it mostly all automatic. The Commands are representations of the behavior that users invoke through the View. Individual commands are exposed through properties on the ViewModel and tied to controls on the View. When the user presses a button, for example, the command attached to that button fires and something happens. You can think of Commands as little controllers, focused on a specific topic, whose responsibility it is to respond to a user action in a particular manner by coordinating the response to that action between the View and ViewModel.

Our goal here is to put all logic about the View into the ViewModel. The View should be very thin and code-less, and the Commands should be thin shims that merely provide an execution conduit between the gesture being made and the behavior being invoked in the ViewModel. Code in the View or in Commands should be looked up with suspicion, with an eye towards trying to move it into someplace more testable. Sometimes you can move that code, and sometimes its entirely appropriate where it is, but the question should always be asked.

Step 1 – Modify the template to support TDD

When you create a WPF application using the Visual Studio New Project dialog, you get the framework of an empty application. There is no code anywhere, other than an InitializeComponent() call here and there. Most of the interesting behavior, at this point, takes place through XAML – things like instantiating the Application object, creating the main window and causing it to display, and other basic things like that. While this works, and works fine for the empty application, we’re going to need more control over how this initiation process occurs, for reasons we’ll discuss later in this post or a subsequent one.

So, to control the initial creation, there are a few changes we need to make. The first step is to put ourselves in control of when and where the main window is created. As time goes on, there are aspects of this creation process that we’re going to want to control, like wiring together other objects, so we’ll need full control over the how windows and controls are born.

App.xaml

When first created, App.xaml looks like this:

   1: <Application x:Class="WpfApplication1.App"

   2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

   3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

   4:     StartupUri="Window1.xaml">

   5:     <Application.Resources>

   6:          

   7:     </Application.Resources>

   8: </Application>

The StartupUri attribute of the Application element is what causes the class defined in Window1.xaml to be instantiated. We want to prevent this from happening until we’re ready for it, so we have to take this out. We’ll still need to create this window, however, so we’ll need to arrange for another way to create objects as the system is starting. It turns out that WPF exposes and event that is perfect for this initialization, the Startup event. By providing a handler for the Startup event, we can have a place to put all our initialization code.

App.xaml now looks like this:

   1: <Application x:Class="WpfApplication1.App"

   2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

   3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

   4:     Startup="Application_Startup">

   5:     <Application.Resources>

   6:  

   7:     </Application.Resources>

   8: </Application>

Now we have to add some code into the App.xaml.cs file to create the objects we need and to wire them together. Please note that I’m not writing tests for this code, because this is configuration code, not business logic. I view logic such as this the same way I view a Main method, and I tend not to test Main’s. It is where objects are created and wired together and then told to go on their merry way. This is not meant to be reusable code and should be just simple declarations of objects and assignments of variables. If I manage to screw up Main, the application isn’t going to work anyhow, and I’m pretty sure I’ll know it :)

   1: using System.Windows;

   2:  

   3: namespace WpfApplication1

   4: {

   5:     public partial class App : Application

   6:     {

   7:         private void Application_Startup(object sender, StartupEventArgs e)

   8:         {

   9:             Current.MainWindow = new MainWindow();

  10:             Current.MainWindow.Show();

  11:         }

  12:     }

  13: }

The final step is to rename the template-provided window name of Window1 to MainWindow and make sure I instantiate it with the proper class name in the Application_Startup method, the handler for the Startup event. Once that is done, you can start the project, and an empty window should appear.

image

 One more change…

Before going further, I’d like to introduce Unity into the codebase. Unity is the dependency injection library from Microsoft, and I’ve found it to be very useful in my WPF applications. Here is the previous code after injecting Unity (injecting Unity – HA! I kill myself).

   1: using System.Windows;

   2: using Microsoft.Practices.Unity;

   3:  

   4: namespace WpfApplication1

   5: {

   6:     public partial class App : Application

   7:     {

   8:         private readonly IUnityContainer container = new UnityContainer();

   9:  

  10:         private void Application_Startup(object sender, StartupEventArgs e)

  11:         {

  12:             container.RegisterType<MainWindow>(new ContainerControlledLifetimeManager());

  13:  

  14:             Current.MainWindow = container.Resolve<MainWindow>();

  15:             Current.MainWindow.Show();

  16:         }

  17:     }

  18: }

Briefly, the point of this code is to register a type, MainWindow, with the Unity container, and then use the container to instantiate the MainWindow object as the application’s main window. The reason I introduced Unity is to separate myself from the semantics of object creation. Unity will take care of instantiating any objects I ask for, as well as any objects that the class being created needs. Its just a way of relieving myself of having to worry about constructor signatures, basically.

Step 2 – Adding the initial content

Its time to fill in the empty window with some content. We’ll avoid adding any behavior yet, we just want to see something. The strategy that we’re going to use is to keep the MainWindow class as the one window in our application, and we’ll swap in and out different pieces of content to show in it. In my projects I’ve found this pattern to be useful, because it lets me layer content to mimic a workflow in the application, and have the content always show up in the same place, be the same size, and not take extra work to manage.

So our goal now is to set the MainWindow’s content to be the initial view we want to show people when they first open the application. The design for this looks like this:

DesignWithTeamStatControlAndViewModel

And the implementation is easy, too.

First, I create my user control, TeamStatsControl:

image

At the same time, I create a ResourceDictionary to hold styles that I’ll be using around the app and merged that dictionary into my UserControl.Resources section. I created a menu, a somewhat attractive header, and a couple of buttons. There’s no behavior in it yet, but that’s coming shortly.

Now, for the fun part, let’s make the simple change to make the content show up in the MainWindow. Since we’re creating a new object, our TeamStatControl, we have to make a few simple changes in App.Application_Startup. We need to register the user control with Unity so that it can create it as needed, and then resolve an instance of it as the Content property of the MainWindow. Once that is done, WPF takes care of making it appear in the window.

   1: private void Application_Startup(object sender, StartupEventArgs e)

   2: {

   3:     container.RegisterType<MainWindow>(new ContainerControlledLifetimeManager());

   4:     container.RegisterType<TeamStatControl>(new ContainerControlledLifetimeManager());

   5:  

   6:     Current.MainWindow = container.Resolve<MainWindow>();

   7:     Current.MainWindow.Content = container.Resolve<TeamStatControl>();

   8:     Current.MainWindow.Show();

   9: }

And, by the way, I also changed the Width and Height properties in MainWindow to be 600 and 1000 respectively so that the entire user control would be visible.

Step 3 – Adding behavior

Now that the shell is in place, we can add the behavior that we want. First, lets add the basic behavior of exiting the application in an orderly way. We want to be sure to do this in a way that all the code that we write is testable, and that is going to require a bit of extra work over and above just writing the simplest code. This is the price one pays when writing code using TDD, but the extra effort pays off in systems that work.

Let’s start by writing our first test. This test will be a test of the Command object, which is the object that the view will interact with. An underlying force of the MVVM pattern is that the ViewModel encapsulates the visible data and behavior of the View. And the Command object acts as the conduit through which the gestures of the user are translated into tangible actions in the ViewModel. Here is a sequence diagram showing this behavior:

CommandExecutionSequenceDiagram

Clicking the button causes the Command.Execute method to fire, which calls a method in the ViewModel. That method does the real work of this system, with the calls coming before it just part of the plumbing to cause things to happen.

So lets write a test to show that the above sequence is what will actually happen – that calling the Execute method of some Command object will invoke some sort of behavior that causes the application to exit.

Our first test:

   1: namespace ViewModelFixtures

   2: {

   3:     public class ApplicationExitBehaviorFixture

   4:     {

   5:         [Fact]

   6:         public void ApplicationExitingBehaviorInvokedWhenExecuteCalled()

   7:         {

   8:             var exiter = new Mock<IApplicationExitAdapter>();

   9:             ApplicationExitCommand command = new ApplicationExitCommand(exiter.Object);

  10:             exiter.Setup(e => e.ExitApplication()).Verifiable();

  11:  

  12:             command.Execute(null);

  13:  

  14:             exiter.Verify(e => e.ExitApplication());

  15:         }

  16:     }

  17: }

For those of you unfamiliar with the tools used in this test, I’m using Moq as my mocking framework and xUnit for my tests. These are my two favorite tools for TDD as of now, and I highly recommend both of them.

Beginning on line 7, defines the behavior of the system when my ApplicationExitCommand.Execute method is called. I’m defining the interface that the command is going to talk to, IApplicationExitAdapter, and I’m doing this in total and complete ignorance of what class is ever going to implement that interface (OK, I’m lying – its going to be my view model, but let’s keep that our secret for now).

And the code that we write to get this test to compile:

   1: namespace ViewModels

   2: {

   3:     public interface IApplicationExitAdapter

   4:     {

   5:         void ExitApplication();

   6:     }

   7: }

   1: namespace ViewModels

   2: {

   3:     public class ApplicationExitCommand : ICommand

   4:     {

   5:         public ApplicationExitCommand(IApplicationExitAdapter exitAdapter)

   6:         {

   7:             throw new NotImplementedException();

   8:         }

   9:  

  10:         public void Execute(object o)

  11:         {

  12:             throw new NotImplementedException();

  13:         }

  14:  

  15:         public bool CanExecute(object parameter)

  16:         {

  17:             throw new NotImplementedException();

  18:         }

  19:  

  20:         public event EventHandler CanExecuteChanged;

  21:     }

  22: }

Strictly speaking, I went a little further than I had to here, choosing to implement ICommand, but all commands that are hooked through a View as we’re discussing need to implement this interface (or one of a couple of others that are more advanced), so I just went ahead and did it.

Short Aside – Projects and Solution Structure

Before we go further, we should discuss the projects I’ve chosen to use in this solution, and why they were chosen. I have one project that holds the view and a separate project that holds the view models. I intentionally kept the Views and ViewModels separate to enforce the direction of the relationship between them. The Application class and the other WPF controls need to have access to the ViewModels, if only to create them and assign them to DataContexts. ViewModels, however, should be 100% ignorant of their views. The simplest way to enforce this constraint is to put all view model code into another assembly, which is what I’ve done.

Now its a simple matter of implementing the code to make the test pass:

   1: public class ApplicationExitCommand : ICommand

   2: {

   3:     private readonly IApplicationExitAdapter exitAdapter;

   4:  

   5:     public ApplicationExitCommand(IApplicationExitAdapter exitAdapter)

   6:     {

   7:         this.exitAdapter = exitAdapter;

   8:     }

   9:  

  10:     public void Execute(object o)

  11:     {

  12:         exitAdapter.ExitApplication();

  13:     }

  14:  

  15:     public bool CanExecute(object parameter)

  16:     {

  17:         return true;

  18:     }

  19:  

  20:     public event EventHandler CanExecuteChanged

  21:     {

  22:         add { CommandManager.RequerySuggested += value; }

  23:         remove { CommandManager.RequerySuggested -= value; }

  24:     }

  25: }

I also went ahead and added some boilerplate code into the CanExecute and CanExecuteChanged method and event inside this class. This boilerplate code is what you start with every time you write a command. You can think of this as creating a command using a code template inside Visual Studio.

At this point, the command should be invoking the behavior that we want, as seen in this diagram:

ApplicationExitCommandSequenceDiagram

Now that the behavior is being called inside the IApplicationExitAdapter, we’ll need to make the giant leap and assume that it is, indeed, our view model class that is going to be implementing that interface. This only make sense, since the Command is invoking behavior on some class that represents the behavior of the View, and the class that represents a View’s behavior is that View’s ViewModel. Q.E.D. Once we’ve crossed that intellectual chasm, we’ll go ahead and implement the functionality inside the view model.

For that, we write this test:

   1: [Fact] 

   2: public void ApplicationControllerInvokedWhenViewModelExitApplicationCalled()

   3: {

   4:     var applicationController = new Mock<IApplicationController>();

   5:     TeamStatControlViewModel viewModel = new TeamStatControlViewModel(applicationController.Object);

   6:     applicationController.Setup(ac => ac.ExitApplication()).Verifiable();

   7:  

   8:     viewModel.ExitApplication();

   9:  

  10:     applicationController.Verify(ac => ac.ExitApplication());

  11: }

This test causes us to make a few design decisions. First, we’ve discovered an interface called IApplicationController that is going to be responsible for controlling application-wide behavior, which would certainly include things like exiting at the appropriate time. We’re also creating the view model class, TeamStatControlViewModel, since we have to add behavior directly to it now. And finally, we’ve discovered that the view model needs to have a reference to the IApplicationController interface, to allow it to invoke functionality through that interfacee. This leads us to creating a constructor for the view model through which we can inject the interface at creation.

Here is the resulting code. First, the simple IApplicationController interface:

   1: namespace ViewModels

   2: {

   3:     public interface IApplicationController

   4:     {

   5:         void ExitApplication();

   6:     }

   7: }

and now the TeamStatControlViewModel:

   1: namespace ViewModels

   2: {

   3:     public class TeamStatControlViewModel : IApplicationExitAdapter

   4:     {

   5:         private readonly IApplicationController applicationController;

   6:  

   7:         public TeamStatControlViewModel(IApplicationController applicationController)

   8:         {

   9:             this.applicationController = applicationController;

  10:         }

  11:  

  12:         public void ExitApplication()

  13:         {

  14:             applicationController.ExitApplication();

  15:         }

  16:     }

  17: }

That’s just enough code to make that test pass, so we’re momentarily happy. However, our system isn’t going to work yet, because we haven’t found anyone to implement the IApplicationController interface. That’s our next major decision.

ClassDiagramExceptForFinalClass

I’m going to choose to put this interface onto the App class, at least for now, since it seems to be the one place in our application that has knowledge of the entire application. It may turn out later that we need to move this responsibility somewhere else, but we’ll leave it here for now.

We’ll go ahead and make the easy changes to App.xaml.cs, which consist of making it implement IApplicationController and writing the ExitApplication method, which simply calls Current.Shutdown().

   1: public partial class App : Application, IApplicationController

   2: {

   3:     private readonly IUnityContainer container = new UnityContainer();

   4:  

   5:     private void Application_Startup(object sender, StartupEventArgs e) {...}

   6:  

   7:     public void ExitApplication()

   8:     {

   9:         Current.Shutdown();

  10:     }

  11: }

The important point to note is that the IApplicationController interface lives in the ViewModel assembly, even though it is being implemented by the App class in the main WPF assembly. This means that the main WPF application project has to have a reference to the ViewModel project, which is the direction we want the dependencies to flow. By moving the ViewModel classes and interfaces into an a project separate from the view classes, we’re enforcing our dependency management design as we described earlier.

This now leaves us with this for a design:

ClassDiagramFinal

So we’re in the home stretch now. We have all our code built – what is lacking now are the few scattered bits and pieces needed to wire this whole thing together. There are several of these pieces, and we’ll look at them one at a time.

Let’s start with the object creation changes needed in App.Application_Startup. Over these last few changes, we’ve created a new interface for the App class, so we need to tell Unity that when I ask for an instance of an IApplicationController, it should pass back a reference to the App class. You can see this code on line 3 below. We also created a TeamStatControlViewModel, which we tell Unity about on line 5.

   1: private void Application_Startup(object sender, StartupEventArgs e)

   2: {

   3:     container.RegisterInstance<IApplicationController>(this);

   4:  

   5:     container.RegisterType<TeamStatControlViewModel>(new ContainerControlledLifetimeManager());

   6:     container.RegisterType<TeamStatControl>(new ContainerControlledLifetimeManager());

   7:  

   8:     container.RegisterType<MainWindow>(new ContainerControlledLifetimeManager());

   9:     

  10:     Current.MainWindow = container.Resolve<MainWindow>();

  11:     Current.MainWindow.Content = container.Resolve<TeamStatControl>();

  12:     Current.MainWindow.Show();

  13: }

Next, we know that TeamStatControlViewModel is going to be the DataContext for the TeamStatViewModel, so let’s make that happen in code. The easiest way is to change the constructor for the TeamStatControl to take the view model and assign it to be its DataContext in its constructor. The really cool part of this is that we don’t have to make any changes in App.ApplicationStartup based on this constructor changing. Unity will just build all the dependent objects for us and call whatever constructors it can find, and it all just works.

   1: public TeamStatControl(TeamStatControlViewModel viewModel)

   2: {

   3:     DataContext = viewModel;

   4:     InitializeComponent();

   5: }

Now that we have the objects built and wired up, we need to do the data binding to put the commands into the controls on the interface. The first place to do this is in TeamStatControl, where we define the Quit button. We need to assign an instance of the ApplicationExitCommand to the Command attribute of the button. Here is the XAML code that will do this for the Quit button:

   1: <Button Command="{Binding ApplicationExit}" Grid.Column="1" Content="Quit" HorizontalAlignment="Left" Style="{StaticResource NormalButton}"/>

We do this by creating a binding to the ApplicationExit property of our data context, the TeamStatControlViewModel. The view is now expecting the view model to expose a property called ApplicationExit, of type ICommand, through which it can get the command. We don’t have that property right now, so lets write a test that makes us create it.

   1: [Fact]

   2: public void ViewModelExposesApplicationExitCommandAsICommand()

   3: {

   4:     TeamStatControlViewModel viewModel = new TeamStatControlViewModel(null);

   5:  

   6:     Assert.IsAssignableFrom<ApplicationExitCommand>(viewModel.ApplicationExit);

   7: }

This test says that we can get an ICommand from the view model and the ICommand we get is actually an ApplicationExitCommand, which is what we need. We just need to implement that through creating a simple auto-property in the view model. That satisfies what we need for the binding we defined in the XAML. Now, we construct the command in the constructor of the TeamStatControlViewModel class and pass an instance of the view model to the constructor of its command to wire that up, and we’re set!

   1: public TeamStatControlViewModel(IApplicationController applicationController)

   2: {

   3:     this.applicationController = applicationController;

   4:     ApplicationExit = new ApplicationExitCommand(this);

   5: }

   6:  

After all this, running the application and clicking the Quit button should cause the app to vanish silently, slipping into the night, never to be seen again. Whew!

A Bonus

Now that all this hard work is done, we can also  hook this same logic to the menu button. If we go into the XAML and find the line where we define the menu item, we just set its Command attribute to be a binding to ApplicationExit as well, and now it works, too.

Conclusion

As I said at the beginning, this blog entry, and the couple more that will follow this week, will form the basis for my St. Louis Day of Dot Net talk on this same subject. I’d appreciate any and all feedback on this article, especially including things that weren’t clear, design  leaps I made without a clear reason, and alternative ways to do the same things I did.

You can find the complete project for this on my website. You may need to install Unity to get the solution to compile.

Thanks for reading, and I hope it helps!

 

– bab

Posted in 111, 112 | Comments Off

Are you coming to St. Louis Day of DotNet?

Only a few seats left, apparently, for the conference on August 28th and 29th. Register here. Looks like lots of good sessions, lots of good topics, and filled with good speakers.

Personally,  I’m speaking on Using MVVM and TDD to test drive a WPF application.

 

bab

Posted in Uncategorized | 2 Comments