Archive

Archive for March, 2010

Simplified MVVM Commanding with DelegateCommand

March 30, 2010 13 comments

The MVVM (Model-Miew-ViewModel) pattern for WPF works really well, but for me has one big disadvantage – the sheer verbosity of it.  There’s just so much code to type!  Especially when you’re going for the ‘pure’ approach of no code in your code-behind.

One of the worst offenders for this is the Command model, whereby in your ViewModel you define a class which implements ICommand.  This is made available to the View via a property, and when called, calls some method in your ViewModel.

(Note:  This only applies to WPF.  Silverlight doesn’t currently support commands in the same way.)

Here’s an example, from inside my ViewModel (MeasurementViewModel):

(This is set up in the XAML as follows:)

You can see the custom ICommand (AddDefinitionCommand), a local variable to hold it, and a property getter for the view to find it.  Now considering that this doesn’t even have the code which performs the action (which is viewModel.AddMeasurementDefinition), that’s lot of overhead.  And you have to do that for every single command!  That’s button clicks, selection changes, and so on.

One of the problems is that the Command model provides a lot of flexibility by defining the CanExecute() method and CanExecuteChanged event, but I don’t need those in my simple scenario.

So, how to write a bit less code?  Of course, you could make some good use of Code Snippets, but there are better solutions.  The best one I’ve found is the DelegateCommand approach used in Microsoft’s Composite Application Library (a.k.a Prism), also discussed in Josh Smith’s MVVM article (where he calls it a RelayCommand).  This involves defining an ICommand which uses delegates, and means you have less boilerplate code to write.

As I’m not interested in using the full features of the ICommand, my simple DelegateCommand goes like this:

DelegateCommand class definition

DelegateCommand.cs

And to call it, you simply need the following:

You can see the local member for the DelegateCommand, the ViewModel constructor where we define the method to call, and the property to make it available to the View.  Much simpler, I’m sure you’ll agree!

Of course, if you want to include the rest of the Command functionality, you can just extend the DelegateCommand.  So there you have it, all of your MVVM problems solved!  Well, nearly..

The Code

(As I don’t seem to be able to upload DelegateCommand.cs for you to download, here’s the text for you to copy & paste.  I’ll work WordPress out one of these days…)

using System;
using System.Windows.Input;
namespace CommandUtils
{
public class DelegateCommand: ICommand
{
private Action _executeMethod;
public DelegateCommand(Action executeMethod)
{
_executeMethod = executeMethod;
}
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_executeMethod.Invoke();
}
}
}
Edit: To see this in action, check out my MVVM Example App
Advertisements
Categories: WPF Tags: , ,

WCF Overview

I did an introductory WCF workshop the other week so I thought I’d post the basics here.  This diagram shows the usage of WCF (excuse the crappy PowerPoint art) – brief explanations below:

WCF Usage Diagram

WCF Usage Diagram

Service

This is your actual service, which is just made up of standard .Net code, usually an interface and the implementation.  The interface has a couple of attributes on it to make itself known to WCF as a service, e.g.:

In VS2008, you can create this by adding a new ‘WCF Service Library’ project, which includes some example code.

Host

The host is whatever runs the service, making it available on a particular address.  In most cases this will be IIS, but it could be a Windows Service or even just a console/winforms app.

Either way, you’ll need some config to specify the Address, Binding and Contracts (known as the ABC), which in it’s most basic form will look something like this:

These are collectively known as an ‘endpoint’.  If you created a WCF Service Library for your service, Visual Studio will actually have created this for you in an App.config file, which you can just copy into your host application.

Then to run the service, just stick this in your main():

Client

Here’s where you actually call your service, again just a standard application of your choosing.  The point at which it turns into a WCF client is when you select ‘Add Service Reference’ in Visual Studio, and give it the address of your running service.  This does a load of magic, and the important things you and up with are:

  • A config file with the relevant WCF endpoint in it
  • A service proxy

The proxy is basically a local version of the service that you created.  If you look at all the files in the service reference, you will see ‘reference.cs’, which contains your service methods.  When we want to call the service from the client, we just make a call to this proxy, which goes away and handles all of the tricky networking stuff in the background so you don’t have to worry about it.

How simple is it?  Here’s the code:

Conclusion

So, WCF’s pretty easy to use.  The main issue you’ll face are probably with config, and firewalls (addresses not matching, remote machines not responding, and so on).  Once you get into it, WCF’s a massive technology, but at a basic level it’s pretty straightforward.

Apologies if this was a little short, but I thought it was about time to feed the blog!  Feel free to get in touch for more details.

Categories: WCF Tags:

Podcast Rundown

One of my favourite ways of keeping up with development is listening to podcasts, which I usually do in my car – a stereo with a USB port comes in very handy here.  (Note:  Only do this while alone!  The dulcet tones of Scot Hanseman might increase your knowledge, but they’re unlikely to impress the chicks..)

Anyway, audio tips and sexism aside, here are all of the podcasts I’ve been listening to and what I think of them, in order of greatness:

Herding Code

Rating: 10/10

Technology: Mainly .Net

Sound Quality: Average

Hosted by four smart and fairly amusing guys, the beauty of this podcast is that you always get to hear all sides of the argument on any given topic.  And unlike some of the other podcasts, the topics are nearly always interesting – I rarely skip an episode.  They get some top guests too.

.Net Rocks!

Rating: 9/10

Technology: .Net

Sound Quality: Excellent

Probably the best-known and longest-running podcast out there, .Net Rocks is perhaps the most professionally produced show out there – you could easily mistake it for a radio show.  The presenters are funny and knowledgeable, get good guests and always ask pertinent questions (although you don’t get the same level of  discussion as with Herding Code).

ElegantCode Cast

Rating: 8/10

Technology: Mainly .Net

Sound Quality: Poor – Average

Run by some of the ElegantCode bloggers, this podcast is similar to Herding Code in it’s style, usually with multiple presenters leading to interesting discussions.  It seems to have died since David Starr left for the PluralCast (see below), but I’m hoping it might get resurrected.

Alt.Net Podcast

Rating: 7/10

Technology: Mainly .Net

Sound Quality: Average

Although this only lasted a short while, the few podcasts it created covered some really useful subjects, in good detail.  And being Alt.Net (if you’re aware of that movement), there are also some interesting debates and disagreements in there.  Well worth a listen.

Pluralcast

Rating: 7/10

Technology: .Net

Sound Quality: Good

Having recently taking over from the Elegant Code Cast, the Pluralcast has made a good start, covering some interesting subjects.  Although run by a commercial company (PluralSight Training), the shows don’t feel like they’re trying to sell you anything.  The interviews are sometimes a little one-sided, and the shows don’t always flow as well as they might, but definitely one to try out.

HanselMinutes

Rating: 6/10

Technology: .Net

Sound Quality: Excellent

Alongside .Net Rocks, HanselMinutes is the other well-produced, long running podcast.  Scott is currently a Senior Program Manager at Microsoft, which means he gets some great guests and inside scoops, but sometimes the interviews are again a little one-sided.  Scott’s a really smart guy and knowledgeable developer, and I feel bad for only giving a 6, but the subject is often web development (which I’m not really into), and I often skip shows because I’m not that interested in the guest/subject.

Software Engineering Radio

Rating: 6/10

Technology: All

Sound Quality: Good

I’ve really only just started listening to this so it’s a little early to give my opinion – but when did that ever stop a reviewer?!  So, as you might imagine from the title, it covers general software engineering in all languages, often with clever academic people being interviewed by other clever academic people.  Ok, perhaps I undersell it there, it’s not all academic – and it is good to break out of .Net every now and again.

The Thirsty Developer

Rating: 5/10

Technology: .Net

Sound Quality: Average

A show run my a couple of Microsoft evangelists, this has some good content, but the shows are fairly infrequent and I often skip them.  The subjects and interviews can be a little Microsoft-heavy.

The Pragmatic Bookshelf

Rating: 5/10

Technology: All

Sound Quality: Good

Run (although not hosted) by The Pragmatic Programmers, this podcast consists of interviews with the authors of various books on the Prag Pub label.  It’s kind of commercial in that respect, but interesting nonetheless.

Polymorphic Podcast

Rating: 4/10

Technology: .Net

Sound Quality: Good

Again I feel bad about giving this such a low rating, as it’s not a bad podcast, I just don’t like it personally.  I only listened to the first few, but the topics are usually web-based, and were often covered fairly simplistically, and I didn’t really like the presenter.  I think I’ll give it another try soon, as everyone else seems to rate it.

So there you go, plenty to keep you occupied on your lonely commute there!  Obviously those ratings are just my opinion, so don’t take my advice – go and try them for yourself!

Categories: Development Tags: ,