.NET and me Coding dreams since 1998!

25Nov/105

Naked MVVM – simplest way to do WCF code

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”

Like the previous post about simplest possible way to do MVVM, the solution for this problem was covered in so many blog posts that even I am personally aware of a couple of cool and ‘frameworkish’ ways to solve it: use WCF behaviors, create your own ChannelFactory<T> with either sync call in separate thread or IAsyncResult based approach and (my personal favorite) hack the Visual Studio proxy generator. I’m sure there are at least 24 more solutions to do this Smeško

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

  1. 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.
  2. 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

imageThe 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”

A year ago, I have blogged in great detail about the unfortunate fact of ServiceClient generated in service proxy not implementing an IServiceClient interface. In case you want to understand what my solution do under the hood go read that blog post now and then continue reading this one. In case “you don’t care how it works as long it is working” here’s a very short summary for you:

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.

You can download the source code of end solution here.

Before

Project structure is very trivial. It is vanilla Silverlight project which has a TimerService WCF service doing just this

using System;
using System.ServiceModel;
using System.ServiceModel.Activation;

namespace NakedMVVM.Web
{
    [ServiceContract]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class TimerService
    {
        [OperationContract]
        public string GetTime()
        {
            return "Yes it works on " + DateTime.Now;
        }
    }
}

Once we add a service proxy to NMVVM_WCF project (NOTE that proxy name ends with Proxy)

image

We can happily write now our demoware code “…

namespace NMVVM_WCF
{
    using System.ComponentModel;
    using System.Runtime.Serialization;

    using NMVVM_WCF.TimerServiceProxy;

    public class MainPageViewModel : INotifyPropertyChanged
    {
        public MainPageViewModel()
        {

            TimerServiceClient client = new TimerServiceClient();
            client.GetTimeCompleted += OnGetTimeCompleted;
            client.GetTimeAsync();
        }

        private void OnGetTimeCompleted(object sender, GetTimeCompletedEventArgs e)
        {
            Message = e.Result;
        }

        [DataMember]
        private string message;

        public string Message
        {
            get
            {
                return this.message;
            }
            set
            {
                if (this.message == value)
                {
                    return;
                }
                this.message = value;
                this.OnPropertyChanged("Message");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

Nothing wrong with this code per se, just it makes unit testing of the view model much harder task then it should be…

After

To fix this problem, let’s do next 2 steps:

  • download the T4 template file (no need to look in what it contains at all) from here .
  • add the file to the root folder of NMVVM_WCF project using VS IDE “Add existing item”

As a result of this activities t4 template was executed and a file with ClientEnhancer was auto-generated with next content

	namespace NMVVM_WCF.TimerServiceProxy
	{
		public partial interface ITimerServiceClient
		{
			#region Events
			event System.EventHandler GetTimeCompleted;
			event System.EventHandler OpenCompleted;
			event System.EventHandler CloseCompleted;
			#endregion Events

			#region Methods
			 void GetTimeAsync();
			 void GetTimeAsync(object userState);
			 void OpenAsync();
			 void OpenAsync(object userState);
			 void CloseAsync();
			 void CloseAsync(object userState);
			#endregion Methods
		}

		public partial class TimerServiceClient  : ITimerServiceClient
		{
		}
	}

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

        public MainPageViewModel(ITimerServiceClient client)
        {
            client.GetTimeCompleted += OnGetTimeCompleted;
            client.GetTimeAsync();
        }

        private void OnGetTimeCompleted(object sender, GetTimeCompletedEventArgs e)
        {
            Message = e.Result;
        }

The only thing left is to update the MainPage.xaml.cs file

namespace NMVVM_WCF
{
    using NMVVM_WCF.TimerServiceProxy;

    public partial class MainPage
    {
        public MainPage()
        {
            InitializeComponent();
            DataContext = new MainPageViewModel(new TimerServiceClient());
        }
    }
}

And that’s it – application works like it was and we have a highly testable view model using only service client interface which is easy to stub/mock.

Having a hard time figuring out path from “before” to “after”? Here’s a short video showing step by step things just described

You can download the source code of end solution here.

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.

What do you think about it? Is it simple enough?

Comments (5) Trackbacks (0)
  1. Simple enough if you ask me :)

    What i would add or remove from it would be the *Completed events and simplify it so that user can call service in more streamlined way maybe something like:

    proxy.GetTime(successAction, failureAction)

    (anybody said JQuery ?)

    but thats just matter of preference, its an excellent post, straight to the point as usual.

    keep up the good work!

  2. Interesting approach. I also tried modifying the VS proxy generator and stopped at about the same point you did.

    My solution is slightly different. Instead of writing new proxies, I wrote an interface and implementation imbued with the proxy workflow. It lets you express each async method call, including the various callbacks,  as a single statement, while allowing for full testability.

    You can find a write-up here:

    http://www.executableintent.com/refining-wcf-service-proxies-in-silverlight

  3. Bryan,

    as I said above my approach is uncool compared to other approaches but it is also not requiring any framework and code other then the usual "vanila web service" coding any developer can do.

    I can imagine the trouble for some of ‘us regular folks’ to get the

    _siteInfoProxy.ExecuteAsync<GetVisitorCountCompletedEventArgs>(

         (client, handler) => client.GetVisitorCountCompleted += handler,

         client => client.GetVisitorCountAsync(),

         args => Console.WriteLine(“Visitor count: {0}”, args.Result),

         exception => Console.WriteLine(“Error: {0}”, exception),

         () => Console.WriteLine(“Cancelled”));

    All this been said, it’s a very cool implementation and I’m sure a lot of folks not affraid of a little bit lambda coding would embrace it for sure :)

  4. Bryan,

    as I said above my approach is uncool compared to other approaches but it is also not requiring any framework and code other then the usual "vanila web service" coding any developer can do.

    I can imagine the trouble for some of ‘us regular folks’ to get the

    _siteInfoProxy.ExecuteAsync<GetVisitorCountCompletedEventArgs>(

         (client, handler) => client.GetVisitorCountCompleted += handler,

         client => client.GetVisitorCountAsync(),

         args => Console.WriteLine(“Visitor count: {0}”, args.Result),

         exception => Console.WriteLine(“Error: {0}”, exception),

         () => Console.WriteLine(“Cancelled”));

    All this been said, it’s a very cool implementation and I’m sure a lot of folks not affraid of a little bit lambda coding would embrace it for sure :)

  5. Understood. It condenses the same code you are writing, so I can see how it would be imposing. To be fair, I am handling the exception and cancellation cases, which your example does not :-)

    Lambda expressions aren't magic. They are just inline methods. You would write the exact same signatures elsewhere in the class. If that is the root of the intellectual divide you seem to perceive, you might not be giving yourself enough credit.

    Thanks for the feedback.


Leave a comment

No trackbacks yet.