Monthly Archives: November 2010

How to get testable WCF code in simplest way?

What is the problem?

We all know that creating an instance of service proxy inside of the view model makes writing tests for the view model very hard because during the unit test run we don’t have usually the web service on the other side or even if we do it slows down web tests.

You know how they say

“Unit test is the test which runs without any problem with network cable unplugged”

Still, there are two main problems with all the approaches I saw which belong to one of the next two groups:

They deal purely with async based scenarios.
If I have a service with a method GetForecast(DateTime date), I don’t want to maintain another interface just to get a way to make async call.

They are rocket science type of solutions
We are all geeks and like nice and shiny toys, but what about regular folks like me and a lot of the readers? Is there a really simple way to do this for “us others”?

Luckily, I think I found one which is definitely not the coolest one and 100% can be enhanced etc, but it is the one which proved to me in my day to day WPF/SL coding to be the easiest one “to grok and use”.

Conceptual solution

The solution follows next design goals:

doesn’t require any typing

it is using Visual Studio proxy generated with “Add service..” menu action

it is using the well documented MethodAsync() invoker, MethodCompleted event subscriber pattern

it is using T4 to auto generate code which enhances the VS generated service proxy

every service proxy file follows naming convention of ending with word “Proxy”

ServiceClient generated by proxy generator is marked as partial class.That allows me to create another partial class with same name and namespace outside of proxy which only purpose is to hook the IServiceClient interface I generated manually based on the ServiceClient itself.

In the original blog post I do it manually which ended as a PITA due to the fact that every change of service contract one has to keep updated the interface. As a result of noticing that I waste a lot of time on that, I spent 20 minutes and created a simple T4 class which does that automatically for me.

As you can guess, that’s complete code I was coding by hand and keep it updated manually with service contract changes. Having this in place it is quite easy to change ViewModel to accept the IServiceClient as a constructor parameter

Aftermath

My own version of this T4 template, beside the T4 template code used in this blog post is also auto filling IoC container with mappings to all of service clients and its interfaces generated by template. That auto generation combined with auto MVVM wire up I described in first post allow me to have this “TDD enabling of WCF service proxies” fully automated.

I decided not to put that additional template code so it won’t bloat the post with IoC containers etc, but it is VERY easy to modify and customize the T4 template – even if you never did it spend 20 minutes looking at .tt file I shared for this post and I guarantee you – you’ll get it.

The only downside of this approach is that you have to manually drop the T4 template file to every project with service proxies which in my case is not the problem at all – I add it once and after that it keeps things in sync on its own.

I am really not sure why Microsoft is not doing this in the default proxy generation process – it is not breaking anything or damaging backward compatibility and it enables easy testing. I was experimenting modifying the Visual Studio proxy generator myself, but I decided to abandon it (even it was working at the end) due to required registry modifications etc. In my opinion, dropping one file in project without any other requirements to make it testable is more transparent then other approaches and everyone could do this.

How to do MVVM in simplest possible way?

Yes, I am aware that there are at least 50 “How to do MVVM” blog posts and well known frameworks: prism, MVVM Light, Caliburn etc. Still, my friend Slobodan Pavkov convinced me to write a post and explain the approach I am personally using in my code, because (as he believes) it is so simple that it can be useful to someone – so here I am – writing it down.

Idea is so simple that I guess it is very possible someone already blogged about it and if so please let me know so I could link that blog post here. I presume you know what MVVM already is – if not go read some of the hundreds blog posts about that and once you get it come back. My sample is done in WPF (as that is my LOB platform of choice) but it works without any changes in Silverlight too.

As all MVVM framework I had to pick a name reflecting the spirit of my “framework” and I ended with “Naked MVVM” because it reflects design principles I respect:

And here is the view model containing all of the necessary requirements from my Naked MVVM framework

namespace NakedMVVM
{
public class MainWindowViewModel
{
}
}

As you can tell from the code above, there are ZERO requirements from view and view model.

Wiring up the view and the view model

s you already know, the whole MVVM pattern is based on the idea that view data binds to a view model which then talks to a model.

A lot of samples I’ve seen, define some form of view abstraction which should enable view model to communicate with view on framework level.

All of those samples ignore one simple but VERY IMPORTANT fact – there is such abstraction already baked in .NET – FrameworkElement. Every view (user control, window etc.) inherits from the FrameworkElement and can be casted to it. The reason why I picked it up is that the framework element has a DataContext member (to bad it is not defined in some interface so I could replace FrameworkElement with it). Setting a user control data context to some value results with all of the controls in that window/user control being bounded to the same value.

The problem here is how an IoC container (one of the requirements above is to use IoC) can resolve this generic FrameworkElement constructor parameter? That question is exactly the reason why we have all of the IView and IView<T> in the MVVM blog posts. To me that well documented approach is an overkill because we create entities just to hold our infrastructure. Much better approach could be to resolve a framework element from a IoC container using a well known key. There are many way how to do that but let here illustrate it in the simplest to digest form using the ServiceLocator.

As you can see here, view model becomes a data context of a view without any artificial code artifacts created to enable that. If I wouldn’t have to respect my design principle #1 “No base classes of any kind required” I could extract this class to base view model class and have it applicable on all view models.

Too bad I am not allowed to do that so I am again deleting all of the changes in this ViewModel and restore it back to be an empty class with no base class and no wire-up code in it. To see what I do in my code you would have to be patient for a little bit more because I need to explain first may way of …

Filling the IoC container

In most MVVM samples, there is a bootstrapper class where developer enlist all of the IoC mappings. In this example it could be something like this

The key I use to store it in IoC is the same as the name of user control/window

Every WPF/SL developer I know (including me) when doing MVVM follows the next naming convention:

every user control is suffixed with “View” and

every view model of a control is suffixed with “ViewModel”

In concrete case of the sample used in this blog post, user control is named MainWindowView and her view model class MainWindowViewModel

If we combine the 3 obvious facts given above with the naming convention we could easily come to the same idea as I did:

“Iterate all of the types in current assembly. Each one of them which name ends with “View” map as framework element using the full type name as a key. Each one of them which name ends with a “ViewModel” map as object with a full type name as a key.”

Translating that thought into a C# code class IoCBuilder in this sample was created containing this

Code is quite simple: pointer to a user control is being passed to a behavior. Following the naming convention explained above, I add the “Model”to the name of the view so I would get the specific view model key which I use to resolve view model from a container. Once resolved view model, I set to a DataContext of a user control being passed to a behavior. Same approach as the one in explicit sample, just encapsulated in the behavior.

Now when there is a framework level behavior, only thing a designer has to do to wire up a view and view model (I emphasize here again that both of them are following the #1-#3 principles and not having any base class, interface etc) is to fire up a blend and just drag&drop the AutoWireUp behavior to a control.

Off course, for us developers executing next R# snippet and resolving namespaces is maybe more suitable solution

Regardless of which way you would prefer, the end goal is achieved: view and view model are wired up on a unobtrusive way removing the need for infrastructure bloat used usually to enable that.

Putting it to work

If we run our sample, everything will work just fine (even with view and view model being completely empty) except we won’t see the current date on the screen so we can’t know for sure if it work or not, aren’t we?