Thursday, December 23, 2010

December Update of the Coding Guidelines for C# 3.0 and C# 4.0

I finally found some time to update the coding guidelines with some feedback I received since it’s original release in June this year. I’ve removed the following guidelines because I found that they were either very exotic or not general enough for most developers:

  • Avoid side-effects when throwing recoverable exceptions (AV1044)
  • Don’t make assumptions on the object’s state after raising an event (AV1050)
  • Adhere to the LINQ Design Guidelines for custom IQueryable implementations (AV1075)
  • Explicitly define the scope of a type or member (AV1551) because it is a duplicate of AV1501.

I also noticed that the Design Guidelines section is getting bigger with each new version, so I split up that section into three smaller sections. And because of that, I had to renumber the guidelines in the AV1025-1100 range as well. So what about the new guidelines?

Well, these are new ones:

  • Use an interface to support multiple implementations, not a base class (AV1004)
  • Use an interface to decouple classes from each other (AV1005)
  • Avoid bidirectional dependencies (AV1020)
  • Classes should have state and behavior (AV1025)
  • Avoid mutual exclusive properties (AV1110)
  • Don’t expose stateful objects through static members (AV1125)
  • Use exceptions instead of return codes for reporting failures (AV1200)
  • Don’t use nested loops in a method (AV1532)
  • Consider abstracting an external dependency or 3rd party component (AV1580)

As usual, you can download the latest version, its A4 cheat sheet, and Visual Studio 2010 rule sets at

Saturday, December 11, 2010

A night of Silverlight, WPF, unit testing and Caliburn Micro

Last Thursday, me and my employer Aviva Solutions hosted the December edition of the DotNED user group in Leiden. And yesterday a shared my Silverlight reference architecture on this year’s last SDN Event. I gave two talks that evening and one last night and wanted to share my slides and example code from here.

Best Practices for Writing First Class Unit Tests
Slides, Example Code

Building Testable Silverlight and WPF applications using Caliburn Micro
Slides, Example Code

A Silverlight 4 Reference Architecture for LOB Applications
Slides, Example Code

Notice that you need Visual Studio 2010, the Silverlight 4 Tools and probably the Silverlight 4 Toolkit (but I’m not entirely sure about the latter).

If you have any questions, let me know.

Monday, November 29, 2010

ReSharper versus CodeRush through the eyes of a keyboard addict

I've been a very long-time and very happy user of ReSharper, and I’ve become very dependent of it. I wouldn't know what to do with a plain Visual Studio 2010 installation. However, I also heard many great things about the combination of DevExpress's CodeRush and their Refactor! Pro products. Apparently my many tweets about the greatness of R# have attracted some attention, so DevExpress offered me a one-year license to try their products out. To be fair, I did pass this blog post to DevExpress to make sure I was not overlooking something and they've provided me with some great feedback. Nevertheless, this is my personal opinion, even though I've really tried to be as unbiased as possible.

For the comparison I used ReSharper 5.1.1 and CodeRush/Refactor Pro 10.1.7. The development box I tested on was a Sony Viao notebook with 8 GB of memory, a Core i7 CPU (1.73 GHz) and an Intel X2 160GB SSD.

R# versus CodeRush / Refactor Pro!


Syntax coloring. Not everybody likes it, but I really think it improves the readability of your code.


File Structure window. I use it continuously to make sure all my classes can be read from top to bottom (a la Clean Code).


The menus are self-explanatory and include the currently configured shortcut key.


Single keystroke for virtually all fixes, improvements and refactoring opportunities.


Code Cleanup, will fix naming issues, reformat the layout, and other improvements. Can be applied to the entire solution.


Project/Solution-level refactoring features such as fixing up namespaces globally and moving every type into its own source file.


Surrounding a statement requires a few more keyboard hits


Requires a lot of memory and still has a major performance impact on Visual Studio


Doesn't always understand where a custom extension method comes from.


R# relies more on dialog boxes to provide the details of some refactoring option, whereas CodeRush relies more on inline editing. Unfortunately, the dialog boxes don't always get focus properly, requiring the mouse to activate it. This also happens when the change causes a file to get checked out. At that point, the TFS dialog box and R#'s are in conflict.


CodeRush  / Refactor Pro versus R#


Way more refactoring options


Way more code generation options requiring only one or two keystrokes


It's configuration system is extremely flexible


Nice context sensitive help tool window, especially for the single-character code generation templates.


Feels a bit snappier than ReSharper


Embedding a block of code is nice. Just select a block of code and press one of the keys such c for a try...catch. ReSharper can do this as well but requires more key strokes. In fact, I really love being able to add ( and ) to an expression by selecting het expression and '(' and get it surrounded. Oh Jetbrains, please add that one as well.


I like the marker concept which allows you to sprinkle bread crumbs and simply step back to the last edition position or the last marker. Takes a bit of getting used to, especially after using ReSharper since it uses ESC to cancel a refactoring action.


If you're into code metrics, you'll love the little icons listing the number of lines and code metric indicators next to it, but I have not really found the need for it.


When you just use a particular feature for the first time, it shows you a small non-intrusive dialog explaining what just happens, and giving you the choice to change that behavior.


It has a built-in spell checker that highlights words and provides a context menu with alternatives.


It can refactor an ordinary statement with one that uses the Parallels library


Amount of visual feedback is a bit too much sometimes, but it drops off after a while


Overwhelms a bit too much in the beginning


Not as well designed for keyboards users as R#


No member selection (a la R# CTRL-\)


Quick Navigation (CTRL-SHIFT-Q) does not show namespaces, so duplicate items are difficult to differentiate). You can use the CTRL key to get a preview of the highlighted code block, but it's a bit slow sometimes.


No Smart Completion such as referring to something that is not part of the namespace or in an unreferenced assembly, both in code, in ASPX and in XAML files. You have to fall back to the CTRL-. VS keyboard option, but that only works when the class is in the same project or part of the references.


No refactor option for renaming a namespace based on its location in the source code hierarchy


Duplicate Line feature (SHIFT-ENTER) does not duplicate an entire block of code


No option to add the opening parentheses when calling a method


In general I want a tool like R# or CodeRush to replace and extend the default features of Visual Studio without the need to learn too many new tricks. But most importantly, its keyboard support must be excellent. I want as less keystrokes as possible to get as much work done as possible within the context of the code you're editing. Based on my short experience, it seems that DevExpress has focused on shortening the amount of keystrokes to generate new code and to introduce as many refactoring options as possible. R# on the other hand, excels in keyboard support and improving the overall experience of programming in Visual Studio 2010 without too much interference. As far as I can see, R# biggest problem is their ridiculous memory and performance footprint, whereas DevExpress's primary concern has been to introduce as much features as possible, without looking back at the consistency aspects.

I've really tried to give DevExpress's tools a fair change, but at the end, the inconsistent experience, both on the visual level as well as the lack of proper keyboard support, have forced me to stay with R#. These are more important for me than the many extra refactoring options.

Tuesday, November 16, 2010

The subtleties of Silverlight’s cross-browser compatibility

Last week we put our first full-blown Silverlight 4 line-of-business application into production, and just yesterday, we’ve run into our first production issue. Consider the width specifications of the DataGrid columns in this XAML fragment:


This XAML file was generated by Expression Blend and has not caused any problems throughout the development phase and during user acceptance tests. However, on one particular Windows XP/IE7 system it caused a crash, even though all systems were using Silverlight 4.0.50917.0. After a bit of investigation we learned that by design a star-sized specification should include an integer and not a double. The big mystery is why this is not detected by the compiler and why it works on all other systems…

Saturday, November 06, 2010

More quotes from QCon

Well, QCon 2010 is over, so it is time to travel back to the Netherlands and finally see my wife and daughter again. However, after the previous post, the quotes have been coming in on Twitter space. So, to complete one of the most intense conferences ever, here are some more funny, inspiring and brain hurting quotes.

About architecture, technology and tools

  • "All problems can be solved by another level of indirection, except for the problem of too many layers of indirection"
  • "Nothing scales like a stateless service"
  • "Erik (Meijer) just mathematically proved thatNoSQL is really coSQL"
  • "Given enough time and perseverity, you can create any query model on top of any storage model" (Michael Nygard)
  • "How do you tell the difference between a startup and an enterprise? In a startup, everybody knows the administrator password"
  • "If you do it more than twice, script it." (Randy Shoup about automation being key in the cloud)
  • "Technology without purpose is squat" (Rod Barlow)
  • "XML is like violence. If it's not working, use it more." (Martin Fowler)
  • "Continuous integration and feature branching are incompatible. Powerful merging tools don't handle semantics. " (Martin Fowler)

About software development

  • "Hope is not a strategy. Don't build a system based on it."
  • "Understanding the domain is a whole team activity" (Dan North)
  • "Share your fear about a thing with friends that do the same thing helps you all to act together..."
  • "Meetings == beatings" (Michael Feathers after misunderstanding a question)
  • "Test too hard and you are fixing problems that will never occur. Test too light and bad things happen."
  • "Oh?….oh!....crap!" (Dan North, about deliberate discovery)

About the conference, the speakers and other attendees

  • "Where did Erik Meijer get that shirt?"
  • "Dutch are cheap" (Erik Meijer)
  • "I think of myself as an intellectual dumpster diver" (Martin Fowler)
  • "Ok, we get it. Your company is very interesting, now get to the nerd stuff."
  • "Seems wrong for the concurrency track not to be delivered in parallel"
  • "Once again, QCon is showing me how little I truly know!"

Friday, November 05, 2010

Deliberate Discovery, No SQL and CQRS at QCon

The 2nd day of QCon was not one where I chose wisely. My focus for this conference was everything Agile and anything from the well-known speakers. So I ignored most sessions that had words like REST, SQL or Java in it. How wrong I was…. But I did not discover that until I heard and read about all the great feedback those got while the only ones that could keep my attention where hosted by Dan North and Erik Meijer.

So, let's discuss Dan North's talk on Deliberate Discovery. It kept my brain hurting for the remainder of the day, even after speaking with Dan and reading his associated post. And I still don't know whether I'll be able to reproduce his message. His point is that many failures in our projects are caused by ignorance. Ignorance on technology, ignorance on organizational aspects, or even ignorance on your own ignorance. Essentially stuff you don't know yet on any level (axes as he calls it) that will reduce or hamper your throughput. And it doesn't necessarily has to apply to you or your team. Ignorance of your stakeholders can be just as catastrophic. Some of the ignorance will become apparent during poker planning sessions or your user story workshops, but that's only going to be the tip of the iceberg.

So what can you do about that? Well, that's the part which I haven't really figured out yet. Fortunately, Dan is still working on that as well, but some concrete things he mentions includes having a brainstorm before you start breaking down stories. In this brainstorm you focus not on the things you already know, but on the relevant things you don't and which may impact the project. I suppose such a brainstorm should include the team, the stakeholders and anybody else how might have something relevant to contribute. I think that explicitly focusing on the ignorance is the differentiating aspect here.

Another example he gave is what he calls Test Driven Testing. If you practice pure TDD, you won't write a single line of production code without having written the test for it (or specification if you will). But sometimes it might be wiser to start with a Spike to do some exploratory developing to see if some idea works out or not. If it doesn't, throw it away. But if it does, start adding first-class unit tests as if you would have done when doing TDD from the beginning. That should force you to refactor or redesign that code to make it testable. If you ask me, Test Driven Refactoring may be a better name.

Anyway, another talk I went to was Erik Meijer's mathematical analysis of SQL versus NoSQL. I must admit that it was very funny to watch. But to be honest, I had no clue of what he was talking about other than being able to vent his opinion that SQL databases and NoSQL databases should be seen as complimentary rather than as competition. Taking into account that he is working for Microsoft, that may have been the real message. Nonetheless, the audience was thrilled so it must have been good…

After taking a quick bite at the Google-sponsored reception, I went to the CQRS OpenSpace discussion I proposed earlier that day. I was quite surprised to finally find the entire .NET minority group present at QCon. It was great to be able to hear the opinions and challenges of all those smart people. The discussion continued for more than 1.5 hour, so that's prove it is something worth discussing. If you’re interested, I’m currently maintaining a demonstration project on CodePlex that uses Silverlight, the Ncqrs framework and some other .NET technologies to demonstrate Event Sourcing and CQRS.

Thursday, November 04, 2010

Pretotyping, Best Patterns and History Lessons

The compression ratio of the content versus the timing available is quite high here at QCon. Already at the first official day, I attended 7 (!) talks. That's quite a lot of information to process. Unfortunately, the difference in quality is really noticeable. Some talks were absolutely awesome and inspiring, while some other speakers were simply reading out loud what was on the slides or reading them in silence (while keeping us wondering whether he forgot what he was talking about). As an occasional speaker, I'm surprised that so many of them made that many rookie mistakes.

The ones worth looking at included the keynote by Google's Director of Engineering Patrick Copeland. Regardless of him making fun of Microsoft, he gave a great talk about the value of prototyping software products using physical mock-ups. At first it sounded a bit strange or rather unlikely, but he showed some pretty convincing stories from Google's own product development efforts. The name he gave to that concept is pretotyping, and there's even a website about that.


Well, it's starting to get predictive, but Dan North's session titled Keeping Agile Agile was a blast and made me smile throughout his entire talk. Apart from the recurring Dreyfus model (which is in fact quite handy if you're an consultant like me that tries to improve other people's skills), he discussed the dangers of applying best practices without thinking. The problem, as he explained it, is that most people treat best practices as something you should do, regardless of the context in which you want to use it, and without considering the pros and cons. In fact, most advocates of best practices don't even mention all those side effects. That's why he suggested to refer to these practices as patterns instead of best practices. And that resonates nicely with the way the Gang of Four have been explaining their design patterns as well. However, if you ask me, any good consultant should be looking at the particular culture, history, problem domain and people involved before introducing any practices, patterns or other proverbial silver bullets.

Leonardo Mattiazi's talk on Agile adoption within a Brazillian company was completing the formal part of the day. Although he didn't really introduce any new concepts or innovations, he showed us the challenges he went through to successfully transform a company of passionate people into an agile adopting organization. His use of visual media and Twitter was very good and helped keep the audience awake after such a long day. During his talk, I challenged him a few times because it all felt so unnaturally positive. But I happened to enjoy some beers with him at the conference party and confirmed that he has been very lucky with such a great group of people.

However, the day was not over. Just before the conference party started we had another keynote by somebody I didn't know before. But Dan Ingalls appeared to be an icon in our profession and the founder of Smalltalk, the most widely referenced computer language whenever we talk about the history of object orientation. He took us through 40 years of computer engineering and appeared to have wisdom that could match Yoda's. If you have been monitoring the chatter on the #qconsf Twitter hash tag, you know what I mean...

Quotes from QCon

One of the funny things of this QCon is the many tweets that the attendees have been throwing into the world wide web. That's great for a speaker because now they get immediate feedback on their performance, both good and bad. These are some of the quotes I found funny, inspiring or refreshing:

On testing

  • Just because you have automated tests doesn't mean you shouldn't be doing manual testing (Martin Fowler)
  • Test is not a phase… (Martin Fowler)

On tools & deployment

  • Beware!... a fool with a tool is still a fool (Martin Fowler)
  • If it hurts,do it more often,and bring the pain forward (Martin Fowler)
  • How long would it take your org to deploy a 1 single line of code change (Mary & Tom Poppendieck)
  • If you're able to adapt, test and deploy a change very quickly, you don't have to worry too much about risk (Dan North)
  • Adam Messinger from oracle didn't show up to talk about the future of java. What's the message there?

About architecture

  • The structure of your architecture will reflect the structure of your organization (Dan North)
  • If you don't mind being called in the middle of the night, then it's an error. Otherwise it's a warning (Dan North)
  • WADL (web application description language) is people coming from the SOAP world putting their sofas on the porch, reducing property value for everyone else (attendee)

About Agile and product management

  • Agile is a methodology to get mediocre developers to screw up less (Dan North)
  • Lots of concern about blindly following agile in Agile Track at #qconsf. one gotta understand the underlying ideas (Cecilia Fernandes, attendee)
  • You get what you measure (Dan North)
  • If you're not embarrassed by your first product, you shipped too late (Patrick Copeland)
  • Build the right product instead of building the product right (Patrick Copeland)
  • Even if organizational constraints seem to be hard, be skeptical and discuss it (Dan North)
  • Not screwing other teams is a requirement of your software (Attendee)
  • When you solve problem #1, problem #2 gets a promotion (Attendee)
  • Most fear is irrational, so we can learn how to get rid of that (Dan North)
  • Teaching is creating an environment in which people can learn (if they want) (Dan North)

About other attendees

  • Okay, if your whole purpose at #qconsf is to argue with the presenter, sign up to present next year and tell everyone your view", about an Italian guy going against the speaker on both tutorial days
  • Oh good, loud clicking external keyboard guy is here again this year

About the conference

  • Haha @martinfowler screaming at vendors in #continuousdelivery presentation at #qconsf was pretty funny.
  • Ideas are worthless (Patrick Copeland)
  • I'm almost a top model, so I can date anyone I want" (Guilherme)
  • Its your decision, live with the company culture or leave…
  • Amazing how quickly the #qconsf crowd tore though the ice cream bars
  • Coffee: A mild stimulant popular as a late-afternoon refreshment at software development conferences.

Wednesday, November 03, 2010

Agile Architecture according to Dan North

Updated on March 3rd 2012 with a PDF of Dan North’s mind map

On the first day of the QCon conference in San Francisco, I attended a full-day tutorial titled "Secrets of Agile Architecture" hosted by Dan North. I didn't really know what to expect, but I was hoping for some refreshingly new insights on the way I do my job currently.

Well, his talk was actually less innovative than I thought. But that's okay, because he gave one of the best and most refreshing talks on architecture I've seen in a while. He covered an enormous amount of material in that one day, so I won't even try to cover that in a blog post. But what I particularly liked is that a large part of that content was dealing with the organizational and human aspects of building an architecture.

One of the takeaways worth noting, and which is something I recognize quite well, is the fact that it's difficult to go into an organization and build enough trust to start breaking down the organization. Often you’ll find tens and tens of things to improve, accept the fact that you probably can only change three of them, and focus on that.

So what's the agile aspect? Well, just like Fowler explained in his Continuous Delivery tutorial, it is important to accept the fact that risks happen, so deal with it. If you can setup your architecture and development process in such a way that you can quickly (read: automated) build, test and deploy small changes, you don't have to worry too much about the likelihood of those risks. Moreover, deploying quickly gives you valuable feedback that you can use to further tune and tweak your architecture. As a bonus, it allows you to defer decisions to the last responsible moment instead of doing it upfront and running the risk you made a bad choice.

Dan didn't use any slides, but based his entire talk on a huge mind map that he unfolded gradually. He's going to share that mind map soon, and I'm sure going to put that on my office wall. It's a great reminder of all the aspects you should consider when designing an architecture for a specific company or problem domain. You can find a PDF of that mind map here.

Monday, November 01, 2010

A weekend in San Francisco

This week I'll be attending QCON, an international conference on architecture and Agile held in San Francisco. Because a flight on Sunday was 400 euros more expensive than a flight on Saturday, I decided to rent a nice convertible and use the day off to take a nice road trip through the area to the south of San Francisco. My ride for this weekend? A Ford Mustang Premium Convertible with a 305HP V6 engine, 500 watt USB sound system and a GPS. Not bad huh?


What’s great is that I could only make reservations for the Chrysler Sebring Convertible. I knew from last year that the Chrysler is a crappy car to drive, so imagine the smile when they told me about the Mustang. And to my surprise and unlike the many complaints of European car magazines about the driving experience of American cars, this one was absolutely awesome.   

This is more a less the trip I did. First to Vicaville to do some shopping in its Outlet Factory, then a bit of backtracking, and on to Napa to take the Silverado Trail all the way up to Calistogo. Napa is known for its wine-tasting, but since I don’t care much for wine (and I was driving), I just enjoyed the scenery. The vineyards over there look exactly like the south of France, but the difference is that in California the roads, the buildings and the gardens are better maintained. And did I mention already that the folks over there are much friendlier than the French?


Obviously Napa has a Starbucks as well, so that’s were I took a light lunch and a cold Frappuccino. After completing the Silverado Trail I moved on to the coast where I enjoyed the view at Bodega Bay. What’s funny is that during a road trip like these, you pass through small villages and towns that look exactly like those you see in movies and TV series.

San Francisco 086

From there I took Highway One all the way back to San Francisco. What I don’t get is why they call that back road a highway. It’s nothing more than a asphalted back road that flows through meadows, along farms, and through the hills. If you ever drove along the Gorges du Verdon in France you might know what I mean. I requires quite some driving skills to stay on the road with all those tight turns and narrow parts. Fortunately the Mustang was the right car at the right spot, especially with all that power. I lost count of the many Priusses and other small cars that decided to stop somewhere so that I could pass them. Nevertheless, I found plenty of spots to enjoy the view.

San Francisco 095

Somewhere halfway along Highway One you pass through a little town called Point Reyes Station. That’s where I took a burger for dinner before continuing the last part of my trip. By the time I crossed the Golden Gate Bridge it was almost dark, so unfortunately I could not take of good picture of it. Suffice to say that crossing this bridge is an impressive experience. The view on the open sea made me feel very small.

As you can see from the pictures, the weather was quite okay. On Saturday it was still very cloudy and about 14 degrees Celcius, but during my 550-km trip the weather allowed me to drive with the hood down all the way back to the Hertz drop-off point.

So, the next time you are in San Francisco, make sure you rent a convertible. It’s really worth the time (and the money).

Tuesday, October 26, 2010

Silverlight Cookbook: ViewModels, Coroutines and Binding Conventions

This post is part of a series of blog posts detailing various aspects of the Silverlight Cookbook, an initiative to demonstrate proper design choices for building enterprise-class line-of-business applications with Silverlight (and WPF if you will). It currently consists out of the following parts.

After having covered querying, commanding and the domain model, it is time for discussing some of the Silverlight application details. But before I do that, let's list the components I currently use:

Consider the client part of my reference architecture



The first essential part of every application is the Shell. It's a placeholder for all UI behavior related to menu bars, error messages, last-chance exception handling and the Master-page equivalent for Silverlight. Originally, I was planning to use the Regions and Views concept such as provided the Composite Application Guidance (CAG) block of Prism. But once I started working with the combination of Caliburn Micro (CM) and the Silverlight Business Navigation project template and added one of the awesome free themes, I never needed something like that anymore. As a nice bonus, the Business Navigation template already handles deep linking and back/forward support for you. And if you're building a Line-of-Business application, check out the new Jetpack theme. It's excellent for exactly that purpose.

If you don't want to use the Business Navigation template, CM offers a complete solution consisting of a Screen class representing the ViewModel of a XAML page or a user control, and a Conductor class that represents the Shell and allows activating and deactivating individual screens. The out-of-the-box conductor only allows having one active screen (aka SDI), but it is quite trivial to support an MDI-style application because the CM design is very extensible. For instance, the Screen class implements a whole bunch of interfaces that allows your ViewModel to hook in its life-cycle. Examples of those interfaces include IActivate, IDeactivate, IGuardClose and IChild. Notice that this approach is based on the ViewModel-first concept. In other words, you are always activating ViewModels where CM will use conventions to figure out which XAML page, XAML fragment or User Control to display.

In the case of the Business Navigation template, the conductor functionality is handled by a Silverlight Frame control. CM provides a FrameAdapter class that makes sure that the above mentioned life-cycle notifications are also applied to ViewModels that are associated with the XAML pages that the Frame control loads. As such CM supports both a ViewModel-first approach as well as View-first.


Obviously, no serious developer will build a Silverlight application without applying the Model-View-ViewModel pattern. Let's start with the code that is involved when loading a view. It's from The CQRS Kitchen demo and represent the ViewModel for a view that is used to search for recipes.

    public class SearchViewModel : Screen



        public IApplicationController ApplicationController { get; set; }



        public IQueryAgent QueryAgent { get; set; }


        protected override void OnInitialize()


            MinimumRating = 0;

            PartialDescription = "";

            PartialName = "";


The first thing to notice is the base-class this ViewModel is deriving from. It extends CM's Screen class, which offers a way for raising the INotifyPropertyChange using type-safe expressions instead of using literal strings, and implements all the plumbing needed for hooking into the life-cycle interfaces CM offers. You don't necessarily need to derive your ViewModels from Screen and can implement those interfaces directly, but using the Screen class prevents your ViewModel from becoming too obscure.

The OnInitialize method is one of those life-cycle methods I mentioned before but is not doing anything useful in this particular case other than setting the defaults for the search fields. Notice the use of the NotifyOfPropertyChange method in the property setters below. That's the PropertyChangedBase class in action where Screen is deriving from. It will raise the corresponding NotifyPropertyChanged event, and make sure it is raised from the UI thread, regardless of the thread you called NotifyOfPropertyChange from.

        public string PartialName


            get { return partialName; }



                partialName = value;

                NotifyOfPropertyChange(() => PartialName);




        public string PartialDescription


            get { return partialDescription; }



                partialDescription = value;

                NotifyOfPropertyChange(() => PartialDescription);




        public double MinimumRating


            get { return minimumRating; }



                minimumRating = value;

                NotifyOfPropertyChange(() => MinimumRating);



The code also shows some dependencies this particular ViewModel has on other application-specific services. In the reference architecture, the ApplicationController is responsible for navigating to other views or dialog windows and knows the URLs of their XAML files. This way I can verify the navigation behavior of the ViewModel without the need to know anything about the actual URL or the required query parameters.

In this demo application I use Unity to handle dependency injection, but CM can be extended to use any IoC framework by overriding the appropriate methods in the class that inherits from the Bootstrapper class:

    public class ClientBootstrapper : Bootstrapper<ShellViewModel>


        private readonly IUnityContainer container = new UnityContainer();


        protected override void Configure()


// Setting up the Unity container left out for brevity...



        protected override object GetInstance(Type service, string key)


            if (service == null)


                service = GetViewModelTypeNameFromKey(key);

                key = "";



            return container.Resolve(service, key);



        private static Type GetViewModelTypeNameFromKey(string key)


            var viewModelType = from type in typeof(ShellViewModel).Assembly.GetTypes()

                                where type.Name.Equals(key, StringComparison.InvariantCultureIgnoreCase)

                                select type;


            return viewModelType.SingleOrDefault();



        protected override IEnumerable<object> GetAllInstances(Type service)


            return container.ResolveAll(service);



        protected override void BuildUp(object instance)


            container.BuildUp(instance.GetType(), instance);




So let's look at the code that searches for existing recipes.

        public IEnumerable<IResult> FindRecipes()


            var coroutine = new FindRecipesCoroutine


                PartialName = partialName,

                PartialDescription = partialDescription,

                MinimumRating = (int)(minimumRating * MaxRating)



            yield return coroutine;


            Recipes = coroutine.Recipes;


It should look rather unconventional, especially the usage of the yield keyword and the reference to the IResult interface in the return type declaration. This interface is part of CM and defined as:

    public interface IResult


        void Execute(ActionExecutionContext context);


        event EventHandler<ResultCompletionEventArgs> Completed;


You can easily deduce from this definition that a class implementing this interface is supposed to do something upon calling Execute and should notify the caller when that is finished. In essence, this is an asynchronous version of the Command Pattern, but most people refer to it as a Coroutine. CM will assume that all ViewModel methods that return an IEnumerable of IResult are doing asynchronous work and will ensure that the Execute method of a coroutine is not executed until the previous one has completed. The compiler will do the rest. Why?

Well, this is probably the first time I've actually found good use of the yield keyword. Because what happens here is that the compiler will generate a hidden class for the FindRecipes method. This class implements IEnumerable and breaks the method body into two steps that are executing sequentially as part of each IEnumerable.Next call. As such, the first step will construct the FindRecipesCoroutine class and return it. CM will then invoke its Execute method and wait until its Completed event has completed. Only then, it will continue enumerating and cause the code following the yield to execute. By returning multiple coroutines you can create a kind of mini-workflow because the compiler and CM will ensure everything is executed in the right order. That is awesome, isn't it!?

The coroutine itself is not that complex.

    public class FindRecipesCoroutine : SimpleCoroutine



        public IQueryAgent QueryAgent { get; set; }


        public string PartialName { get; set; }


        public string PartialDescription { get; set; }


        public int MinimumRating { get; set; }


        public IEnumerable<Recipe> Recipes { get; internal set; }


        protected override void OnExecute()


            QueryAgent.FindRecipes(MinimumRating, PartialName, PartialDescription,

                recipes =>


                    Recipes = recipes.ToArray();





It's just a thin wrapper that calls a facade hiding the complexities (ugliness) of using WCF Data Services. And since we can rely on CM to inject any dependencies using the configure IoC container, even this class is easily testable. Notice the SimpleCoroutine template class. It's something I created myself to get rid of the repeating code required for declaring and raising the Completed event. The CQRS Kitchen demo also includes a ComplexCoroutine that allows using multiple yield return statements in the OnExecute method to wrap mini-workflows into a coroutine.

In this case, the Recipes property simply exposes the Recipe objects that were generated by the Add Service Reference context menu option of Visual Studio. Because those classes implement INotifyPropertyChanged, In most cases that is sufficient for all kinds of tracking purposes. However, sometimes you have to add some derived properties that are specific to the ViewModel. In usually extend the generated class and add whatever I need for my particular situation and postfix that class with Model. That signifies the fact that I see those classes a part of my ViewModel.

Binding Conventions

You may have noticed the lack of any logic that handles or returns instances of ICommand as you'll find in many other MVVM examples. In fact, I never explained how the XAML view gets attached to the ViewModel, and where this ViewModel instance is created in the first place. This is all part of CM's convention-based binding.

In short, regardless of whether you go for View-first or ViewModel-first, CM will ensure that the ViewModel instance is set as the DataContext of the view, that its dependencies are injected, and that the implemented lifecycle interfaces are called. Additionally, CM will automatically bind UI controls to the ViewModel properties based on the control's name. The specific control property and UI event part of that binding is defined by CM's ConventionManager class, and can be easily changed. Just check out the ClientBootstrapper on CodePlex.

The same applies to invoking methods on the ViewModel. By default, CM will relate buttons with a particular name to the corresponding equally named method (which may or may not use coroutines). It even supports passing the values of other UI elements as the parameters of that method, again by matching their names. And if your ViewModel has a boolean property or method with the same name, but prefixed with Can, then CM will use that to dynamically disable and enable the corresponding button. Morever, using event triggers, you can hook up methods to virtually any UI control event available.

Rob Eisenberg, the author of CM, has written some pretty elaborate articles demonstrating the power of his convention-based binding. Read the introduction first and then continue with the stuff about the actions.

Miscellaneous goodies

For a long while I have been wishing Patterns & Practices would develop a version of the Policy Injection Application Block suitable for Silverlight. But recently, a community member came up with a CM extension that looks similar to the Action Filters concept in ASP.NET MVC. With that you can apply attributes to your ViewModel properties and methods like [Async], [Rescue], [SetBusy], [Dependencies] or anything else you can come up with yourself. The CQRS Kitchen is not using this yet, but that’s one of things I plan to the next weeks.

Another little gem for which I'm quite happy CM provided a solution, is its IObservableCollection<T> interface and the corresponding BindableCollection<T>. Now it's finally possible to expose a collection that implements INotifyCollectionChanged, without exposing the actual collection class itself. I'm one of those guys that tries to restrict any collection properties to Ienumerable<T>, so having IObservableCollection is a great life saver. But it gets better. The BindableCollection will automatically raise its events from the UI thread, even if you add or remove items from a background thread.

Well, this post has ended up being a bit longer than I expected, and I’m not done yet, so keep checking back once in a while. Topics I have in mind include at least UI validation, the service agent and event aggregation.