Advanced MVVM now available on Kindle Store in the UK

August 9, 2010

I just got some good news from Amazon.  Folks in the UK can now get my book, Advanced MVVM, from the Kindle store.   If you buy my book from Amazon’s Kindle store, you can read it on a variety of devices: the Kindle e-book reader, iPhone, iPad, your PC, and others.

Here’s the link: http://www.amazon.co.uk/Advanced-MVVM/dp/B0038KX9FW

Also, I have some other exciting news to share.  Team Mole has been very hard at work, creating Mole for Visual Studio 2010, the second generation of our popular debugger visualizer.  We’re getting close to the finish line.  We expect to have our product online, and ready to be purchased, within the next few weeks.  Mole 2010 has been in the works since February.  It’s turning out to be an amazing tool…we’re all very, very proud of it.  We can’t wait to release it! :D


The MVVM Twilight Zone

May 23, 2010

This morning I went to one of Seattle’s numerous coffeehouses to get breakfast.  While waiting in line, the two guys in front of me (looked like coworkers) were talking, and I overheard them use the term “ViewModel.”  When their conversation came to a lull, I politely asked if they’re talking about MVVM.  The following conversation ensued, between one of the guys and myself:

Guy: “Yes, we are actually.”
Me: “Oh cool, that’s a great pattern.  Always an interesting topic.”
Guy: “We use it all the time.”
Me: “What do you like about it?”
Guy: “I like that it’s based on dependency injection.  That makes it really easy to test ViewModels.”
Me: “What do you mean that it’s based on DI?”
Guy: “I mean, it’s based on DI.  Have you ever actually used the pattern?”   [Guy2 now smirks pretentiously]
Me: “Yes, I’ve used it.  But, to me, it’s based on Models, Views, and ViewModels.  That’s it, no DI.”
Guy: “Well it sounds like you don’t really get it then.  It’s complicated, so you need to read a lot about it.”
Me: “Oh, that’s good to know.  What do you suggest I read to learn about  it?”
Guy: “Start with Josh Smith’s MVVM article in MSDN Magazine.”

I kid you not.  That is literally what the guy told me.  I burst out laughing so loud that I felt embarrassed and had to leave.  The guy must have thought I was psychotic!

It’s worth noting that my MVVM article on MSDN never once mentions dependency injection, inversion of control, or any other dependency inversion technique.  That’s because dependency inversion has nothing to do with MVVM.

Happy coding…


Using DynamicObject to intercept and marshal property changes

May 22, 2010

One of the most interesting (and potentially dangerous) new features in C# 4.0 is support for the dynamic type.  It allows certain pieces of your code to bypass the normal compile-time type checking features that we have grown to know and love.  You can use a dynamic object however you want to, and the C# compiler will ignore the members you use on it.  At runtime, if the methods/properties/etc. your code tries to use are not actually present on the object, an exception is thrown.  If they do exist, they will be linked to and invoked dynamically.   This technique is called dynamic dispatch.  What you lose in safety, you gain in flexibility.

In addition to the dynamic keyword there is also support in the .NET Framework 4.0 for creating types that support dynamic dispatch. The System.Dynamic.DynamicObject class allows you to specify how an object performs dynamic dispatch.  You can subclass DynamicObject and override some of its methods, such as TrySetMember and TryGetMember, to perform whatever logic you need to link a dynamic property set or get to a backing store.

Sound pretty cool, right?  That’s what I thought when I first heard about this functionality.  Then I thought, “Why would I ever need to use this?”  I didn’t have an answer to that question, until tonight.  It dawned on me, while trying to read something not related to programming (damn OCD!), that this could be leveraged to implement a simple, reusable means of marshaling property changes to the UI thread.

As you probably know, you cannot get or set a visual element’s properties from any thread except the thread on which it was created.  When the UI thread creates an element, that element thereafter has an affinity to the UI thread’s Dispatcher object.  The only property on an element that you can access from another thread is its Dispatcher property.  Once you have a reference to an element’s Dispatcher, you can use it to dispatch method calls that manipulate the element on the UI thread.

If you work on a lot of UI-level components and controls, like I do, you probably find yourself writing a lot of code that works with Dispatchers just to do something simple like get or set an element’s property.  What a pain!  It turns out that this pain can be somewhat eliminated by making use of DynamicObject and the dynamic keyword.  Here’s a contrived example that shows how…

The code snippet above shows how to use my DynamicElement class.  It acts as a proxy to an element, which intercepts all access to an element’s properties.  This interception allows the DynamicElement to make use of the visual element’s Dispatcher, if necessary.  Here is how the interception works for setting a property:

The TryGetMember implementation is similar to the code seen above.

You can download the source code here.  NOTE: Rename the file extension from .DOC to .ZIP and then decompress it.


Fireside chat about MVVM

May 17, 2010

Craig Shoemaker recently interviewed me for an episode of his Polymorphic Podcast. We touched on a quite few interesting topics, ranging from the merit of the code-behind file, to implementing Undo functionality, to the role of MVVM frameworks. You can check it out here:

http://weblogs.asp.net/craigshoemaker/archive/2010/05/17/advanced-mvvm-with-josh-smith.aspx


Assembly-level initialization at design time

April 7, 2010

One sorely missing feature from the Blend 4 Beta is the ability to have a method in which you can perform initialization work specific to design-time.  Such a method is useful for tasks like loading design-time data services into a container, configuring MEF with design-time specific dependencies, and basically anything else that you might otherwise do at startup when the application runs.  Since your App class won’t be started up when in design mode, it would be great if there was a way for Blend to call a method designated for that purpose at design-time.

I have been thinking about this a lot recently.  Initially I thought that Blend could provide an attribute that I could apply to a static method, and it would then invoke that decorated method before loading any Views.  That seemed like the best solution (and still does, in my opinion).  However, since Blend has no such attribute, I figured it was a moot point…until I realized that I could create my own attribute for the same purpose!

If you decorate an assembly with an attribute, that attribute must be instantiated when the assembly is inspected via reflection (which Blend most certainly does).  So, I simply created a custom attribute and applied it to my assembly.  In that attribute’s constructor, I check to see if it was loaded into design-time.  If it was, I then perform my initialization logic.  How simple!

Here’s the code I added to AssemblyInfo.cs in a project loaded by Blend 4 Beta:

I assume people might want to genericize this class a bit, but the basic idea is quite simple.  Perhaps adding a Type parameter for a class to instantiate would be better, so that the instantiated class could handle initialization.  That would leave the attribute very simple and reusable.  I’ll leave that up to you, if you care…

Here’s the code, for copy-and-paste purposes:

// In AssemblyInfo.cs
//
// Apply this attribute to the assembly so
// that it will be created when the assembly
// is loaded into memory.
[assembly: DesignTimeBootstrapper]

[AttributeUsage(AttributeTargets.Assembly)]
class DesignTimeBootstrapperAttribute
: Attribute
{
public DesignTimeBootstrapperAttribute()
{
var dep = new DependencyObject();
if (DesignerProperties.GetIsInDesignMode(dep))
{
// TODO: Design-time initialization…
}
}
}

Happy coding!


Design-time data is still data

April 4, 2010

It’s strange how common application architecture concerns are often ignored when it comes to supporting design-time data.  By “design-time data” I am referring to pre-canned/fake data that is shown in Views while they are being displayed and edited in Expression Blend, or the Visual Studio visual design surface (a.k.a. Cider).  There are two commonly seen approaches to supporting design-time data, each of which has severe drawbacks.

The most commonly seen approach is to use the d:DataContext and d:DesignInstance settings, which assign a designer-only data context for a View.  The d:DataContext setting is ignored at run-time.  This approach might seem great because it appears to keep design-time concerns consolidated in the View layer, which is the application layer in which “design-time” applies most directly.  Nothing could be further from the truth.  While having support for design-time data settings in the View layer might be great for early UI prototyping, it quickly becomes problematic as the rest of the application layers fall into place.  The main problem with d:DataContext is that you now have to maintain two separate data contexts: the real one and the design one.  Often people create entirely separate classes (or the designer tools generate dynamic classes) that mimic the real data objects and ViewModel objects that are used at run-time.  This introduces a grotesque amount of duplication in the code base, just for the sake of showing some fake data in Blend.  Having duplicated classes and extra settings in XAML just for the sake of design-time data strikes me as patently absurd.  Have fun maintaining that application over the years…

Another common approach to creating design-time data is to keep the Views unaware of being in design-time, and to have their ViewModel objects handle it for them.  This can easily lead to ViewModel classes that are littered with conditional logic that does one thing at design-time and something different at run-time.  For example, a ViewModel that exposes a collection of Foo objects might issue a network call to get Foos at runtime, but just new up a bunch of Foos at design-time.  Complicating ViewModels with repetitive conditional logic has a distinctly rotten code smell.  If a ViewModel is a Model of a View, and a View should not be smart enough to know about “design-time” then, by extension, neither should its Model (i.e. the ViewModel).  There has to be a better way!

Let’s take a step back and return to basics.  In a layered application architecture, you separate the responsibilities and concerns into various layers.  The View layer is responsible for showing things.  In MVVM, the ViewModel layer is responsible for maintaining the logical state of Views, and processing user interactions.  So far, we have not mentioned anything about data access.  That’s the job of a layer below the ViewModel, perhaps called the Model layer or the DataAccess layer.  If the application needs data, it goes to the DataAccess layer to get it.  Design-time data is still data.  It, too, should come from the DataAccess layer.  Everything above the DataAccess layer, such as ViewModels and Views, should not be responsible for making decisions about how data is accessed: including design-time data.

In an application that I’m working on these days, I created an interface that the ViewModel objects use to access data and save data.   It’s a modest sized application, so only one interface was needed so far.  In a larger system you could have as many interfaces as you need to meet your data access requirements.  The data access interface is implemented by three classes: one for run-time data access, one for design-time data access, and another for unit test-time data access.  I use dependency inversion (specifically, the Service Locator pattern) to supply an implementation of the data access interface to the ViewModels.  When the Views and ViewModels are created and start living their life, they are blissfully unaware of the run-time context in which they exist.  When running my unit tests, I provide the data access implementation with whatever data I want it to return to the ViewModel that invokes it.  The design-time implementation loads up some fake data from disk and passes it back into the ViewModels, which then bubbles it up to the Views on the design surface.   Of course, at run-time the “real” data access implementation is used to retrieve the actual data processed by the application.

To me, the primary benefit of this approach is that almost the entire system has no concept of “run-time” vs. “design-time” vs. “test-time.”  The only place in the code base that is aware of the run-time context is the tiny bit of code that determines which implementation of the data access interface to make available to the ViewModels.


Article about Service Locator, MVVM, and MessageBoxes

April 1, 2010

I just published an article titled ‘Using a Service Locator to Work with MessageBoxes in an MVVM Application‘ on CodeProject.  It’s one solution to the now canonical question of how to work with message boxes in an MVVM app, either WPF or Silverlight.  The article gives an introduction to the Service Locator pattern, in case you are not yet familiar with that concept, and then dives into an example of how to leverage it.  The end result is a simple, testable, extensible way to work with message boxes from ViewModel objects.

http://www.codeproject.com/KB/WPF/MessageBoxInMVVM.aspx

By the way, I found out today that I got the Microsoft MVP award again.  Four years in a row!  Woohoo!! :D


Response to Ward Bell’s Review of Advanced MVVM

March 20, 2010
Ward Bell recently published a very thought provoking review/critique of my book Advanced MVVM.  In his review he dished out a compliment sandwich, with a meaty middle of constructive criticism.  I appreciate his positive feedback, and even more so the critical feedback. However, there are a few things in his post that I would like to speak to, since I disagree with some of what he said.
While planning the book, I had to make some decisions and compromises.  My overarching goal was to elucidate the complex interactions that can occur between Views and ViewModels.  I wanted the book to be brief, packed with solutions to recurring problems I’ve seen people asking about on the Web, introduce some interesting new material, and to have minimal overlap with my article about MVVM in MSDN Magazine.  I consider that MSDN article to be “part one” and the book to be “part two” of some unofficial series that I write about MVVM over time.
Another goal was to keep the BubbleBurst demo application understandable to a wide audience.  I made a point of not applying design patterns to everything that could be formalized, because that would just distract the reader from what I wanted to teach them.  Now that you have some of the back story, let’s continue.
Ward’s four main points of criticism are that my book does not cover testing, the data model, dependency injection (DI), or event aggregation.  Since my MVVM article showed how to write tests for the ViewModel layer, I did not cover it in the book.  I know that the examples in that article are not the end-all-be-all final solution to testing ViewModels.  There are certainly a million other important topics that could be discussed to no end about it.  But writing a book about unit testing was not what I set out to do.  I wanted to focus on complex interactions between Views and ViewModels, period.
I’ve had quite a few people ask why the book does not talk about using Model objects.  Aside from the fact that I covered it in the MSDN article, there are two reasons.  First, I wanted Advanced MVVM to focus on the complexities that can arise between the View and ViewModel layers.  That’s why I wrote the book.  Second, working with Model objects is not all that difficult, in my opinion.  When working on an MVVM app, I never find myself solving difficult problems related to the Model, once those classes exist.  That’s the easy part.  Why bother writing about the easy stuff in a book labeled “advanced?”  The hard part about Model objects is designing them, and my book certainly was not intended to be about domain modeling.  Also, the fact that the BubbleBurst application, which is the demo app discussed in the book, has no Model objects, made it even easier to elide the topic…
Moving on to Ward’s other points of critique, let’s talk about dependency injection.  Or, let’s not.  I chose the latter option in my book.  Why?  Dependency injection is a very important and popular topic, so it would certainly be justifiable to discuss it in a book about advanced MVVM.  On the other hand, DI is not in any way, shape, or form part of MVVM.  The two can be used together very effectively, but they are orthogonal practices.  If I wrote a book about DI, would people expect me to include a chapter about MVVM?  I highly doubt it. Like I keep saying, I wanted Advanced MVVM to focus on complex interactions between Views and ViewModels.  The point of the book was not to show how to use every cool, popular, useful technique and pattern.  Advanced MVVM is focused like a sniper on the head of some evil dictator, just waiting to fire a shot.  One shot, one kill.  One focus, one book.
Ward’s other main point of contention is that I didn’t write anything about event aggregation.  He’s correct, I did not.  I certainly could have, but that topic is irrelevant to the focus of my book.
In conclusion, everyone has their own opinion on what a book about “advanced” MVVM should/must contain.  I appreciate guys like Ward, who respectfully disagree with my opinion and voice their own interesting thoughts on the matter.  Perhaps all of this feedback will inspire me to write another book about MVVM!

Control input focus from ViewModel objects

March 16, 2010

One of the pain points in MVVM development is controlling input focus from ViewModel objects.  A common scenario is when a validation error occurs, and focus needs to move to the control that is bound to the property in error.  This makes it easier for the user to immediately fix the validation problem.

A while ago, Dr. WPF shared a solution to the WPF Disciples that involves hijacking the VM’s IDataErrorInfo implementation and doing some hacky magic that results in focus being sent to the correct control.  While a brilliant solution, I preferred finding a more formal, less hacky solution.  This blog post presents the implementation that I’ve thrown together, with help from the WPF Disciples over the past few days.

In a ViewModel object, you must implement my IFocusMover interface.

public event EventHandler MoveFocus;

void RaiseMoveFocus(string focusedProperty)
{
var handler = this.MoveFocus;
if (handler != null)
{
var args = new MoveFocusEventArgs(focusedProperty);
handler(this, args);
}
}

The MoveFocus event should be raised when the VM object determines that input focus needs to be sent to the control bound to the ‘focused property.’  For example, if the FirstName property of an object is deemed invalid, you would call the RaiseMoveFocus method, passing “FirstName” as the focused property argument.  In the demo application, this results in the TextBox whose Text is bound to the FirstName property to get input focus.

Now let’s shift our attention to the View to see how a control is configured to be able to receive focus.  The only thing you must do is use a custom Binding object that I made, called FocusBinding.  That class relies on Philipp Sumi’s BindingDecoratorBase class, which allows you to create a custom Binding that can override the all-important ProvideValue method (inherited from MarkupExtension).

public override object ProvideValue(IServiceProvider provider)
{
DependencyObject elem;
DependencyProperty prop;
if (base.TryGetTargetItems(provider, out elem, out prop))
{ FocusController.SetFocusableProperty(elem, prop); }

return base.ProvideValue(provider);
}

You use the FocusBinding in XAML like this:

<TextBox

Text=”{jas:FocusBinding Path=FirstName, ValidatesOnDataErrors=True}”

/>

The ValidatesOnDataErrors property setting is not required, but is used in the demo app to enable support for validation via the VM’s IDataErrorInfo implementation.  All controls bound to VM properties that can be “focusable” use the FocusBinding, instead of a normal Binding.  When the VM raises its MoveFocus event, the control whose FocusBinding’s Path references the ‘focused property’ will be given input focus.

You can download the source code here.  NOTE: Rename the file extension from .DOC to .ZIP and then decompress it.  Feedback is welcome!


Handel Keyboard Suite #2 – Allegro

March 13, 2010

Every once in a while I post a recording of myself playing a piano piece that I’ve been practicing.  This time I’m performing the Allegro from Handel‘s second keyboard suite.  The recording quality is not ideal, since I never invested in real recording equipment and software.  For those of you who like Baroque keyboard music, I hope you enjoy it!

Handel Keyboard Suite 2 – Allegro