My talk at #notatpdc postponed

Hey guys,

I am really sorry for having to postpone my talk about Expression Blend 3 and SketchFlow. We had some huge difficulties with the NotAtPDC.com website, and unfortunately we were not able to locate the site administrator on time to solve the issue. Without a speaker login, I was able to talk to the attendees, but not share my desktop. Now I love to talk about Blend but I love even more to show Blend ;)

Ironically, as a Microsoft MVP I do have a LiveMeeting account, so I would be able to host the talk myself, but organizing a LiveMeeting take a little time, and I didn’t want to rush into that, cut my talk short or step on the next speaker’s feet (let’s hope that the issues get solved in time for him!)

We will definitely reschedule the talk, either within NotAtPDC (if we find a suitable time slot) or a bit later, so definitely stay tuned on this blog and my twitter feed for more info.

Silverlight 4 beta released at #PDC09

Well people, it was an amazing keynote. Silverlight 4 beta was just presented by Scott Guthrie at the Professional Developer Conference 2009 in Los Angeles. As soon as Silverlight 3 was released a few months ago, the Silverlight team started working on new features to create what will be a really exciting release.

As of now, the Silverlight 4 beta bits and all the necessary tools are available for download. Probably the best place to start is Tim Heuer (Silverlight evangelist for Microsoft) who has a guide to the new features on his blog. A great and very clear read!

Another fantastic resource is my friend Corrado Cavalli’s PDF document with all the new features (there is also an Italian version on Corrado’s blog).

Update: Just found out about the Silverlight 4 Training Course available on Channel 9, put together by Adam Kinney and John Papa, two Microsoft evangelists!

What happens with WPF?

Those of you who know me well know that I love WPF as much as Silverlight, and I am really super happy to work for IdentityMine, a firm that is very active in both environments.

Windows Presentation Foundation is not dead, not at all. With WPF4 (which is available in beta with Visual Studio 2010 beta 2), a load of new features is making it to the desktop as well. In the beginning of the year at MIX09, I had a talk about the .NET continuum, and we are exactly there, with Silverlight and WPF coming closer, but still having their respective features. WPF is more than ever Silverlight’s big sister, they are closer than they have ever been, which is a blessing for us developers because passing from one world to the other has never been easier.

With Silverlight running out of the browser with elevated permissions, and with the possibility to modify the appearance of the window hosting the out-of-browser application, Silverlight is coming very close to a desktop application. But it is not one yet. So the question is, will we see a “merge” between Silverlight and WPF in the coming few years? Well to be frank, I am a very vocal proponent of the convergence, and I am pretty sure that we will go that way sooner or later. The good news is that all that Microsoft learned over the years while creating WPF is invested in Silverlight. In some areas, it has been made even better, because they learned from some mistakes. In others, they capitalized on the fantastic functionalities available in WPF and made that available to us without a change in Silverlight. My point is that talking about the death of WPF is a cow’s opinion, it’s a moo point. WPF and Silverlight will continue to grow ever closer, and we will continue to enjoy the best of both worlds, the desktop and the web! Exciting years to be a client developer indeed!

These are YOUR features

One thing the Silverlight does really well is listen to the community. I read somewhere that 70% of the features requested by the community have made it into Silverlight 4 beta. This is pretty amazing. So continue that work, place your requests either directly to Microsoft evangelists if you have the chance to know one, or through Silverlight MVPs who have possibilities to get to talk to the Silverlight team often.

And the story is not over yet… Keep your eyes open, we have amazing years in front of us!

Happy coding!!

 

Talking at #notatpdc about Blend 3 and SketchFlow

notatpdc09sm[1]

NotAtPDC is an awesome initiative from within the .NET community that allows people who cannot for any reason attend one of the major conferences (such as PDC, MIX etc…) to share knowledge, have fun, interact and generally have all kind of good times without leaving their home or office.

This year, I cannot make it to the Professional Developer Conference because of multiple reasons (too much work, too many travels ;)) but I will talk to the NotAtPDC conference 2009!

My talk is titled Expression Blend 3: From Design to Realization and is scheduled at 11AM CST on 2009/11/19 (see below for the time at your location).

When designers envision beautiful applications, and pass the comps to developers for realization, the result is often not really up to their expectations. Expression Blend stands between the designer and the developer, and facilitates the workflow. It is not "just" a design tool, it is a visual development environment! In this session, we will show you new features in Expression Blend 3, such as the "interactive sketching tool" SketchFlow and more. This session will take a deep look at the new Blend 3 features such as SketchFlow, Photoshop import, Design-time data, etc…

I am really looking forward to giving this talk, which should be a lot of fun. Let’s face it, Blend 3 is awesome and taking a good in-depth look at the great features that are included in V3 should prove valuable to designers AND developers.

Thanks a lot to Steve Andrews, Rachel Appel and all those who take some of their precious free time to organize this event!

Logging in the session

You need LiveMeeting to log in the session. Make sure you download and test LiveMeeting in advance! The direct link to the session for attendees is:
https://www.livemeeting.com/cc/usergroups/attend?id=F98RD3&pw=Pa$$w0rd

Location Date/Time
Pacific Standard Time Thu, 11/19/2009, 9AM
Mountain Standard Time Thu, 11/19/2009, 10AM
Central Standard Time Thu, 11/19/2009, 11AM
Eastern Standard Time Thu, 11/19/2009, 12PM
London Thu, 19th Nov 2009, 17:00
Paris, Zurich, Milano… Thu, 19th Nov 2009, 18:00

Should your location not appear in this table, my apologies, make sure you check the World Clock Converter to avoid missing the start of the session :)

Bug correction in Messenger and new feature in EventToCommand (MVVM Light Toolkit V3 alpha)

Update (11/14/2009): The sample application is available as a zip file, and I also published the Silverlight version to be executed directly in your browser.

MVVM_Black

The advantage of pushing very early software to the advanced users is that bugs are detected before too many people suffer from them, and features requests can be placed and implemented without pain. This is exactly what happened with the MVVM Light Toolkit V3 alpha 2.

Bug correction

This applies to the new “send with token” feature of the Messenger. When a recipient registers for a type of message, it can provide a token (any object). Then, when a sender sends a message, it can also provide the same token. The Messenger will only send the messages to those recipients who provided the same token when registering. This enables creating separate optimized communication channels between objects. The token can be any object, for example a string, a GUID, etc…

A silly mistake I made in the Messenger preventer simple values (such as an Integer) to be used as a token when sending a message. Simple values can be very valuable for this scenario, since a common reference is not needed to the token: It is simply a kind of contract that the sender and the receiver agree upon in advance. This is as decoupled as it gets, and yet enables a private channel of communication between two objects. Anyway, this mistake is corrected, and available in changeset 34855 on Codeplex.

New feature

A user on Codeplex required an additional feature in the EventToCommand behavior: Adding a way to get the EventArgs from the fired event to the invoked command. I tried to find a good way to implement that, and decided to make this an opt-in feature. The scenario is:

  • if you set the new property PassEventArgsToCommand to true in the EventToCommand
  • and you do NOT set the CommandParameter, nor the CommandParameterValue
  • and you use a RelayCommand<EventArgs> as the data bound command
  • then the parameter passed to the RelayCommand will be the EventArgs.

I believe that passing the EventArgs straight to the ViewModel is a bit overstepping the separation of concerns between the View and the ViewModel. However I do also acknowledge that there are cases where this can be useful, and so now it is possible. This feature is also implemented in changeset 34855 on Codeplex.

I also updated the sample application which can be downloaded here, or from Codeplex (see below). The Silverlight version of the sample application can also be run here.

Sample applications on Codeplex

I took the occasion to upload some sample applications on Codeplex too.

  • EventToCommand: This application demoes the feature of the same name, and is detailed in this blog post.
  • CleanShutdown: This application shows a practical use for the Messenger, and a way to implement a clean shutdown that can easily be extended with additional components. More about this application here.
  • RaiseCanExecuteChanged: This app shows how to use RelayCommands and more info about this sample is found in this blog post.

Happy coding!!

 

MVVM Light Toolkit Logo by P. Schutz

I met Philippe Schutz at the TechDays in Geneva early this year, and have been following him on Facebook since then. He does amazing work with logos and icons, and it is only natural that I have thought of him when I decided to get a new logo and icons for the MVVM Light Toolkit.

A brand identity is quite important to me even in private projects. This is why I created the site GalaSoft (www.galasoft.ch) years ago, and started using this “brand” consistently as well as the cat logo (more about that on a post I wrote last year)

With the MVVM Light Toolkit starting to gain quite some popularity in the community, I have received a few suggestions to open a Facebook page for it, and to promote it on some other platforms. To do this, I needed a logo, something to display proudly and conveying the image, the message of MVVM Light.

So I present to you proudly the new MVVM Light Toolkit logos designed by Philippe Schutz:

MVVM_Black

 

MVVM_White

Yeah I know, they are beautiful.

The design is meant to remind from the Windows 7 aesthetics, and of the Silverlight / .NET logos. I think it is a total success. Of course, the feather suggests the idea of lightness, as opposed to more complex frameworks that are very powerful, but also quite hard to understand and start with.

I will work hard to include this new identity in the MVVM Light Toolkit and all the material related (websites, etc…). I am also preparing a Facebook page for “the fans” ;) So as usual, stay tuned!

 

Going to Berlin (TechEd Europe)

I will make a short appearance at Tech Ed Europe. Due to the amount of work we have right now, I cannot spend more than a couple of days in Berlin, but I still hope to meet many of you all.

I will arrive in Berlin on the Sunday, 8th of November, and leave on Tuesday, the 10th. During the day, I will mostly be helping at the Silverlight booth, together with other MVPs and Silverlight evangelist superstar Tim Heuer. I really hope that many will come and admire the booth, Silverlight 3, ask many questions and hopefully get good answers ;)

See you there!

Laurent

 

MVVM Light Toolkit V3 Alpha 2: EventToCommand behavior

Update (11/14/2009): I updated EventToCommand with a new feature: You can now pass the EventArgs of the fired event to the invoked command. See this post for more explanations.

Here is another early release of the MVVM Light Toolkit V3 (Alpha 2). I decided to release gradually and early as soon as a new part of this new version is ready, to allow advanced users to install, test and give feedback about the new features. If you haven’t seen it yet, the features available in V3 Alpha 1 are described in a previous article. There will be a few more alphas before I make a V3 release, which means more good things are a-coming ;)

Usual disclaimer: Alpha releases are not feature complete (meaning that APIs may change) and it is very possible that there are bugs in the code. Use with care and give feedback if something is not working, thanks!!

EventToCommand behavior

The new feature available in V3 Alpha2 is called EventToCommand and is a Blend behavior. These pieces of code are optimized for Expression Blend, but can also be added directly in XAML, as we will see in this article.

EventToCommand is used to bind an event to an ICommand directly in XAML.

Note: Even though Expression Blend facilitates the usage of EventToCommand, it is not a prerequisite. EventToCommand can be used even if Expression Blend is not installed on your system, or on your users’ system.

Credits, History

This behavior reuses much code from the Expression Blend sample behavior named InvokeDataCommand. I want to give props to the Expression team for creating and publishing these great samples. This would not have been possible without the work put into these samples. I want to especially thank Pete Blois and Jeff Kelly of the Expression team for their help.

I also want to thank Rishi, the creator of the nRoute toolkit, for the interesting discussions and a couple of ideas that I implemented in EventToCommand.

If you are already using InvokeDataCommand, the new EventToCommand behavior brings the following additional features:

  • WPF / Silverlight compatibility: The WPF version of the Expression Blend sample behavior InvokeDataCommand has a bug that prevents it to work (the Silverlight version runs fine though). The bug is corrected in EventToCommand, and both versions run well.
  • CommandParameter is bindable. You can bind this property, for example, to the value of a slider, the content of a TextBox, or any other property that is accessible to a data binding.
  • Disabling the attached control: If the IsEnabled property is available for the attached element, you can opt-in to automatically disable the element if the Command’s CanExecute method returns false. This is dynamic, i.e. if the value of CanExecute changes, the element will be disabled/enabled.
    • In Silverlight, this is valid for all Controls.
    • In WPF, this is valid for all FrameworkElements (Panels, Shapes, Controls, etc…).
    • Note: By default, the element will not be disabled/enabled automatically. Since one element can have multiple EventToCommand behaviors added to link multiple events to commands, you probably want only one or two of these to affect the IsEnabled property. This can be turned on by using the MustToggleIsEnabled property, which can be either set in XAML (see below) or databound to a boolean value (checkbox, etc…).

Source code, Binaries

The source code is available for download from my website. If you prefer, you can go to the Codeplex page where the source code has also been updated.

The binaries can be found here.

Features, Usage

EventToCommand is a behavior that can be added to any FrameworkElement. This can be a Rectangle, an Ellipse (in fact, any shape), an Image, any Control (Button, Slider, CheckBox, RadioButton, and many many others) etc. In short: If you can add an element to your UI, you can probably add EventToCommand to it.

For more information about ICommand (and their MVVM Light implementation, RelayCommand), read this article. You can bind any event to any command. Typically, you will use this to link an element’s event to a command defined in a ViewModel class. For more information about the ViewModel pattern in WPF and Silverlight, this page will help you.

In Expression Blend:

Adding an EventToCommand to any element in Expression Blend is super easy thanks to the visual support.

  • Right click on the References folder and select “Add Reference”.
  • Add a reference to the MVVM Light DLLs. You need two: GalaSoft.MvvmLight.dll and GalaSoft.MvvmLight.Extras.dll. In addition, you need the System.Windows.Interactivity.dll which contains the base code for all behaviors.
    You can download the DLLs needed here. 
  • Open your project in Expression Blend, and build it to make sure that everything is working fine.
  • Locate the element on which you want to add a command in the Objects and Timeline panel.
  • Open the Assets panel and find the Behaviors category.
    You can also find behaviors in the Asset library, which is the last button on the bottom of the toolbar.
FliCA4
  • Drag the EventToCommand behavior on the element you selected before in the Objects and Timeline panel.
  • With the EventToCommand selected, select the Properties panel.
  • Select the event you want to handle.
  • In the Miscellaneous section, bind the EventToCommand to the ICommand you want to execute when the event is fired.
    If you use the MVVM pattern, you probably want to use an ICommand (for example a RelayCommand) located in the ViewModel that is set as the DataContext for your window/page.
    In WPF, you can also enter a value, for example ApplicationCommands.Save. In that case, you must set a CommandBinding.

Fli249C

  • If you want to pass a parameter to the ICommand, you can set the CommandParameter property. You can data bind CommandParameter to something (for example the Text property of a TextBox, etc…). If you want to set a hard coded value ) for example “Hello world”, you need to set CommandParameterValue in the XAML editor (see the “Caveat” section below).

FliD557

  • Finally, if you want the attached element to be disabled depending on the ICommand.CanExecute method, set the MustToggleIsEnabledValue property to True. You can also use MustToggleIsEnabled to data bind this property to something else (for example a CheckBox’s IsChecked property) (see the “Caveat” section below).
    • In Silverlight, this will only work on Controls. Use the VisualStateManager to modify the appearance of the disabled control.
    • In WPF, any FrameworkElement can be disabled. Use the Triggers panel to modify the appearance of the FrameworkElement when it is disabled.

In XAML

Using the XAML editor, follow the steps to add an EventToCommand to an element.

  • Add a reference to the MVVM Light DLLs. You need two: GalaSoft.MvvmLight.dll and GalaSoft.MvvmLight.Extras.dll. In addition, you need the System.Windows.Interactivity.dll which contains the base code for all behaviors.
    You can download the DLLs needed here. 
  • Add an xmlns for the following namespaces:
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras"
  • Add the EventToCommand to the desired element (in this example, a Rectangle) with the following XAML code:
    This presupposes that the DataContext of your page/window is set to a ViewModel containing the TestCommand command, as is usual in the MVVM pattern.

<Rectangle Fill="White"
           Stroke="Black"
           Width="200"
           Height="100">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseEnter">
            <cmd:EventToCommand Command="{Binding TestCommand,
                                          Mode=OneWay}"
               CommandParameter="{Binding Text,
                                  ElementName=MyTextBox,
                                  Mode=OneWay}"
               MustToggleIsEnabledValue="True" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Rectangle>

Listening to events on other elements

Because EventToCommand derives from System.Windows.Interactivity.TriggerAction<T>, it has a property named SourceName. With this property, you can attach EventToCommand to an element, but listen to events on another element. I didn’t explicitly forbid this in the code, but I would recommend against it. I think that it creates confusing code that can easily be broken. The best is probably to always listen to events on the attached element itself, and leave SourceName empty.

Small caveat

Because of limitations in the Silverlight framework (specifically, the fact that data bindings can only be applied to a FrameworkElement), I had to resort to a small trick to make CommandParameter and MustToggleIsEnabled bindable. You will see in the code that there are four properties:

  • CommandParameter:
    • In Silverlight, used to data bind CommandParameter.
    • In WPF, used either for data binding or for hard coded values.
  • CommandParameterValue:
    • In Silverlight and in WPF, used for hard coded values only.
  • MustToggleIsEnabled:
    • In Silverlight, used to data bind MustToggleIsEnabled.
    • In WPF, used either for data binding or for hard coded values.
  • MustToggleIsEnabledValue:
    • In Silverlight and in WPF, used for hard coded values only.

In short, if you don’t care about Silverlight compatibility for your XAML code, you can always use CommandParameter or MustToggleIsEnabled in WPF, either for data binding or for hard coded values. If you want to share your XAML between a Silverlight and a WPF application, then you should respect the rules above, or else you will get exceptions in Silverlight when the XAML is being parsed.

Demo application

The demo application shows multiple usages of the EventToCommand behavior. The application runs in Silverlight and in WPF. Feel free to download the code and play with it to learn how to use EventToCommand! The Silverlight version of the sample application can also be executed directly in your web browser.

  • Binding a Button’s Click event and a Rectangle’s MouseEnter event to a simple RelayCommand.
  • Binding a Button’s Click event and a Rectangle’s MouseEnter event to a RelayCommand with a data bound parameter.
  • Binding a Button’s Click event and a Rectangle’s MouseEnter event to a RelayCommand with a hard coded parameter.
  • Binding a Button’s Click event and a Rectangle’s MouseEnter event to a RelayCommand and disabling them depending on the parameter’s value.
    Note: In Silverlight, Rectangles cannot be disabled.
  • Passing the EventArgs of a fired event to the invoked command.
    Note: This feature was added after V3 alpha 2 was released. See this post for more information.

License

MVVM Light Toolkit is distributed under the MIT License. This license grants you the right to do pretty much anything you want with the code, but don’t come crying if you break something (the exact wording is found here). Some parts of the GalaSoft.MvvmLight.Extras DLL are licensed under the MS-PL license.

 

Quick tip: Snooping WPF application with elevated permissions

Here is a quick tip: If you want to use Snoop on a WPF application running with elevated permissions, you need to run Snoop with elevated permissions too, or else your application will not appear in the application’s list displayed by Snoop.

Thankfully, it is really easy to run Snoop in elevated mode in Windows 7:

  • Press Ctrl-Shift on your keyboard.
  • Click on the Snoop icon in the Taskbar or in the Start menu.

Props for this quick tip go to my colleague Frank Preuss at IdentityMine :)

Note: If you do develop WPF applications, and don’t use Snoop yet, well you have to try it. It is like wanting to develop .NET without using Reflector. It’s possible, but it is painful.

Snoop is a great tool developed by Pete Blois (of the Expression team). It is a must have in every WPF developer’s toolbox.

2009110301

 

MVVM Light Toolkit V3 Alpha 1

This is a super early release of the next version of the MVVM Light Toolkit. Please enjoy with care, be aware that this version is not fully tested and not feature complete by a long shot.

The binaries are available for download, as well as the source code. In addition, the source code for V3 alpha1 is up to date in Codeplex, so you can also get the code from there.

What’s new in the Messenger?

So far the changes are:

  • Bug correction: A “collection was modified” error could occur if a recipient was registering for a message type in the same method it used to receive another message. A similar error had been fixed in V2, but unfortunately this one remained. A unit test was added to isolate this case, and a fix has been implemented.
  • New built-in message types: NotificationMessageAction and NotificationMessageAction<TCallbackParameter>. These types can be used to send a message through the Messenger, and get a callback. A next post will give more information about this scenario.
  • Renamed message types: To avoid some confusion, I renamed CommandMessage to NotificationMessage. These messages are used to convey a notification (of type string) from a sender to a recipient. The term “command” was too confusing because it is a loaded term in the MVVM pattern (ICommand, RoutedCommand, RelayCommand, etc…). The term NotificationMessage is clearer. The old types are still available but have been marked Obsolete and will be removed in a future version of the toolkit.

At this point it is good to remember that the Messenger class (from V2) can be used to send any kind of message, from simple values to complex objects. The built-in message types are merely a convenience for specific scenarios, but nothing forces you to use them!

  • To make testing and mocking easier, it is now possible to override the Messenger.Default property and provide another implementation. In addition, all the public methods of the Messenger class have now been marked virtual, which means that they can be overriden. A next post will give more information about this scenario.
  • In V2, you could send a message to a given type of recipients only by using the method overload Send<TMessage, TRecipient>. In V3, TRecipient can now be an interface. This enables the Messenger to send messages to all the objects implementing a given interface. Note that the Messenger can send to any type of recipient, and no special requirement is needed to receive a message. But if some of your objects happen to implement an interface (for example IViewModel), you can make sure that your messages reach only these recipients (of course, the recipients still need to register for a type of messages).
  • When a recipient registers for a type of message, it can provide a token (any object). Then, when a sender sends a message, it can also provide the same token. The Messenger will only send the messages to those recipients who provided the same token when registering. This enables creating separate optimized communication channels between objects. The token can be any object, for example a string, a GUID, etc…

What’s new in ViewModelBase?

In V3 alpha 1, a small change has been made to ViewModelBase: The constructor ViewModelBase(Messenger) has been replaced by ViewModelBase(IMessenger). This makes it easier to test and mock ViewModels that use their own implementation of the IMessenger interface.

More changes will be implemented in V3 final.

Installation

if you have MVVM Light Toolkit V2 installed, you can easily deploy the V3 alpha1 DLLs manually by following the steps:

  • In Windows, choose the Start menu then All Programs, MVVM Light Toolkit, Binaries (Assemblies). This starts the Windows Explorer in the Binaries folder.
  • (optional but recommended) Rename GalaSoft.MvvmLight.dll (and the Silverlight version too) to GalaSoft.MvvmLight.bak.
  • Download the V3 alpha1 binaries.
  • Extract this file to a local folder.
  • Copy the WPF version of the assembly in Binaries, and then copy the Silverlight version to Binaries\Silverlight.

After these few steps, you are all set to use the new features described here. Again, remember that this is a super early release, so use with care and revert to V2 if you are encountering issues. Also, please give me feedback and suggestions!

What else?

I will publish in the next few days a few blog posts about these new features, and also continue to work on new features. As soon as some features are ready, I will push an alpha2 and blog about it. Thanks a lot for the support!!

 

Microsoft #shape conference

image

The Shape conference is a new web technologies oriented conference organized by Microsoft Switzerland. It is held in Zurich Oerlikon, and has two tracks, one design-oriented and one development-oriented.

Best of Swiss Silverlight award

The Best of Swiss Silverlight awards are rewarding the best Silverlight applications developed in Switzerland this year. The winners are:

  • 3rd place: Siemens with an application to optimize energy efficiency in buildings. Very happy about that, because I have been a contributor to Siemens adopting WPF and starting to think more about new UI technologies, and it makes me very happy to see them adopt Silverlight now!
  • 2nd place: The hospital of Solothurn, Switzerland, for a medical application.
  • 2nd place too: The Swiss post, for an e-business web application

Interestingly, with these 3 applications,  the jury rerwarded some Line-of-business type applications, where Silverlight is used to enrich the content and the interaction.

  • 1st place goes to Sobees for their Silverlight-based Sobees Web. This client can be used in and out of the browser, to access Twitter and Facebook accounts (including posting status updates, search, etc…).

I am really happy for Sobees and want to congratulate them very warmly to this award. It is more than deserved. I know the Sobees team since 2007 and have followed their history, and was happy to help them with a couple of technical issues. The comparison in the challenges they faced while developing their richer application in WPF, and the lighter application in Silverlight is very interesting. Especially the problem of the deployment was interesting to face, as the “full .NET” 3.5 SP1 is not available on some of their target machines (XP, Vista) and needs to be installed, which is a relatively heavy download, even with the client profile. On the other hand, Silverlight is often already installed, and even if it is not, it is easy to download and fast to install.

Since Sobees Web can be installed out of the browser (a feature I have been begging Microsoft to implement already in 2008 ;) it can be used very much like a standalone application, with minor restrictions. I am really happy to see this innovative application rewarded, a very well deserved step for Sobees!

Design thinking

Ruedi Alexander Müller-Beyeler

Designers are still misunderstood by the clients.

  • Designers are responsible for colors.
  • Designers are artists but content and ideas comes from us, the client.

Design should be more than this.

  • English meaning of the word (Entwerfen).
  • Designers should be closer from developers, especially in software.

Talks about his experience in re-designing the news at the german TV channel ZDF, and the different experiences and challenges faced.

Compares design process to software development process: Iterative, we never know exactly when we will be done, we are anyway never completely done.

Funny note: HDTV is also influencing the way that news studios are designed: Presenters will not agree to be filmed as close as in normal definition, because HDTV will show all their flaws. This plays a role already now in the way that TV studios are designed.

Introduced some fake virtual 3D models in the studios (blue screen technology with 3D models, mostly pre-recorded) that the anchors can interact with. This was a wish from the anchors themselves, who would have wanted full 3D, but the technology is not quite ready yet.

The Internet changes the game, especially in the way that multimedia elements interact together. However the demographics for TV news is not always used to the internet (seniors), so this must be taken in account too.

Anchors and other technicians needed to be trained for this new design, early interaction with the people is needed to train them.

Conclusion: Design is more than just design :) Design should be “design thinking”, meaning that everyone involved, even non-designers, must learn to think more about design, and design should be more integrated in every steps of the process. On the other hand, designers must learn to “open their black box” and communicate more during the design process with the client and other persons involved.

And more…

I don’t have a report for the next sessions I followed, but they were pretty cool. The sessions were filmed so I am pretty sure they will be available online soon. Some of them are in English, most of them in German, so pick the ones that interest you and enjoy! In the morning I followed the designer track (with sessions about Expression Blend and SketchFlow). In the afternoon, I followed the sessions about RIA Services and Azure. All the sessions were very interesting and I can definitely recommend checking the videos if you are into this kind of things ;)

 

Clean shutdown in Silverlight and WPF applications

Update: There was a small error in the Silverlight version of the application. The code used to navigate to a different webpage was wrong (in ApplicationExtensions.cs). I wrote this article in the Austrian mountains and did not have the web to check the code, sorry about that ;) I updated the source code. If you downloaded the source code before the 19th of October, 8AM GMT, you want to load the correct version. Apologies!!

It is often difficult for large applications with multiple, loosely coupled components to cleanly shut down. Once a clean shutdown procedure is established, adding new components can disrupt the whole sequence, and things get ugly fast.

In this article, we will show a way to use a Messenger to create a loosely coupled shutdown sequence, making it easy to add new components if needed. For the sake of the demonstration, we will use the MVVM Light Toolkit Messenger, but of course this can also be realized with other messaging systems.

As a bonus, the sample application will also show how to use the same Messenger class to enable communication between two ViewModels that don’t know each other, making it very easy to refactor the application or to modify the client application (for example by adding new screens, etc…).

CleanShutdown demo from Laurent Bugnion on Vimeo.

What is a clean shutdown sequence?

Easy to request shutdown

To cleanly shut down a system, we need a central point from which the shutdown sequence can be started. This central point (we’ll call it the ShutdownService) should be reachable from any place in the application in an easy way. This way, if we add new components, they can request shut down without the ShutdownService needing any modification.

Possibility to interrupt shutdown

Some components might need a little more time to process important information, to display a “shutdown animation”, to log some information to a web service, etc. Some of these operations might be asynchronous, meaning that the shutdown sequence should be interrupted temporarily. This should be implemented in a way that allows adding new components without the ShutdownService or other components being changed.

Being notified upon shutdown

Some components might need to be notified when shutdown is happening, for example to save important information to the disk. Here too, we need to be able to add new components without changing anything else.

Requesting shutdown

This is quite easy: we simply provide a static method in the ShutdownService class. This method called RequestShutdown can be called by any object in the application. A more sophisticated implementation could include a reason for shutdown, letting the ShutdownService decide if the complete shutdown sequence must be executed, of if it should be ignored (for example, in case of a critical application error, a “catastrophic shutdown”, it could be dangerous or impossible to attempt a clean shutdown. Similarly, we could avoid to use a static method, and instead store an instance of the ShutdownService in an IoC container.

Giving everyone a possibility to interrupt shutdown

The ShutdownService provides a possibility for any object in the application to interrupt shutdown. We use the MVVM Light Toolkit’s Messenger class so that objects can register to be notified when a shutdown sequence starts, and to interrupt it if needed. We will use a NotificationMessageAction<bool>. This message type contains:

  • A string specifying which operation needs to be initiated. In the case of the shutdown sequence, we will send a string meaning ConfirmShutdown. The recipient of the message can take the opportunity to confirm that shutdown is OK, or to request shutdown to be stopped.
  • A callback method (of type Action<bool>) that the recipient can call to prevent shutdown from happening. If the recipient calls the callback with true, the shutdown sequence will be interrupted. If it calls the callback with false, (or if it doesn’t call it at all), the shutdown sequence will continue.

Note that the recipient that interrupts shutdown is responsible for requesting shutdown again, after the asynchronous operation has completed. A more elaborate implementation could use a timeout to force shutdown if the asynchronous operation still did not complete after a certain time.

Notifying of imminent shutdown

When shutdown is really happening, a last message will be sent to notify recipients that this time, it’s for real. this gives a unique opportunity to recipients to take last minute measures, such as saving their state to a file, etc. In the sample application, we use a CommandMessage with a string meaning NotifyShutdown. Recipients who subscribed to this message can do what needs to be done.

Let’s see some code

So time to see some code. The source code can be downloaded here. The application can be run in WPF or in Silverlight, and looks like this:

2009101701
  • The 3 sliders are used to change the color of the application’s background.
  • The big X is used to close the application.
  • On closing, the values of the 3 sliders are saved to a file.
  • When the application starts, the saved values are read from the file and set.
  • An animation is played when the application is closed (rotation, scale animation and fade out).

ShutdownService

This class exposes one static method used by other objects to request shutdown. The class is instantiated on startup by the Application object (in App.xaml.cs).

public static void RequestShutdown()
{
    var shouldAbortShutdown = false;

    Messenger.Default.Send(new NotificationMessageAction<bool>(
        Notifications.ConfirmShutdown,
        shouldAbort => shouldAbortShutdown |= shouldAbort));

    if (!shouldAbortShutdown)
    {
        // This time it is for real
        Messenger.Default.Send(new CommandMessage(Notifications.NotifyShutdown));

        Application.Current.Shutdown();
    }
}
  • We start by setting a local variable to false.
  • Then we send a message that interested objects can register for. This provides them with a callback that they can call to interrupt shutdown. The callback is implemented as a lambda expression. If at least one recipient replies true, the variable shouldAbortShutdown is set to true.
  • Finally, if shouldAbortShutdown is false (meaning that noone wants to interrupt), we send another message, this time announcing NotifyShutdown). If anyone registers for this message, they will know that the shutdown is imminent.
  • The last line shuts down the application.

Playing an animation on shutdown

In our sample application, we want to play an animation when the application is shut down. Animations are asynchronous, so we need to temporarily interrupt the shutdown sequence. To do this, we register for the message type NotificationMessageAction<bool>.

To make it easier to share this code between Silverlight and WPF, we place this code in a class called ShutdownAnimationService. This class is instantiated in the MainWindow (for WPF) or in the Page (for Silverlight).

Note: Some like to see MVVM applications without any code in the code-behind of a View. However, playing animations, showing popups and other functionalities are really the responsibility of the View. There is nothing wrong in placing code in the View, as long as it is View-specific!

Messenger.Default.Register<NotificationMessageAction<bool>>(this, message =>
{
    if (message.Command == Notifications.ConfirmShutdown)
    {
        if (!_shutdownAnimationHasRun)
        {
            var sbd = this.Resources["ShutdownStoryboard"] as Storyboard;
            if (sbd != null)
            {
                message.Execute(true); // true == abort shutdown

                sbd.Completed += ShutdownStoryboardCompleted;
                sbd.Begin();
            }
        }

        // If the animation ran already, no need to reply
        // to the message, allow shutdown.
    }
});
  • When a message of type NotificationMessageAction<bool> is sent (which is what the ShutdownService does), the lambda expression is executed.
  • First we check a global variable that tells us if the animation ran already.
  • If it didn’t run yet, we check if there is a Storyboard named ShutdownStoryboard in the resources. If we don’t find it, we let the shutdown happen (this is just a failsafe in case something went wrong with the Storyboard).
  • If we do find the storyboard, we execute the callback with true meaning that we interrupt the shutdown sequence.
  • Finally, we assign a “completed” event to the Storyboard and we start it.

Remember that it is now the responsibility of this object to restart the shutdown sequence! It is done in the completed event of the Storyboard:

void ShutdownStoryboardCompleted(object sender, System.EventArgs e)
{
    _shutdownAnimationHasRun = true;

    // Now that our pre-shutdown task is done
    // we can request shutdown again.
    ShutdownService.RequestShutdown();
}

Note: The animation is defined in the Page.xaml (for Silverlight) and in MainWindow.xaml (for WPF) and not in MainSkin.xaml. While storing the animation in the external resource dictionary would work in WPF, it fails in Silverlight.

Saving settings to a file

The class SettingsViewModel defines three properties (Red, Green and Blue) that are databound to the 3 sliders. In fact, the SettingsViewModel is the DataContext of the half-white panel on the left of the X button.

public SettingsViewModel()
{
    if (!IsInDesignMode)
    {
        Messenger.Default.Register<CommandMessage>(this, m =>
        {
            if (m.Command == Notifications.NotifyShutdown)
            {
                SaveSettings();
            }
        });
        
        _settingsFile = new SettingsFileHandler();

        var savedSettings = _settingsFile.LoadSettings();
        Messenger.Default.Send<Brush, MainViewModel>(
            savedSettings.ApplicationBackgroundBrush);

        _isLoading = true;

        var solidBrush
            = savedSettings.ApplicationBackgroundBrush as SolidColorBrush;
        if (solidBrush != null)
        {
            Red = solidBrush.Color.R;
            Green = solidBrush.Color.G;
            Blue = solidBrush.Color.B;
        }

        _isLoading = false;
    }
}
  • SettingsViewModel registers to receive messages of type CommandMessage. If the CommandMessage’s content is NotifyShutdown, it means the application is closing, and the object saves its state in a file.
  • The rest of the constructor is used to load existing settings, and send an initial message to the MainViewModel to set the saved brush as the application background (see the section below titled “Sending messages from a ViewModel to another” for more details).
  • Finally, we set the sliders to values corresponding to the saved ones.

The saving itself happens in SettingsFileHandler, which is also responsible for loading the settings when the application starts.

  • In WPF, saving the settings and reading them back is made with the XamlWriter, resp XamlReader. These two classes are very useful to save any CLR object to a XAML file, and to restore it. In this sample, we save to the Temp folder, but a normal implementation would save to the AppData folder.
  • In Silverlight, we don’t have XamlWriter, so we save to a plain text file in the IsolatedStorage instead, as explained in the section titled “Specific implementation details for Silverlight”.

Requesting shutdown when the button is pressed

The MainViewModel is set as the DataContext of the application’s window (in Silverlight, of the Page), with the exception of the half-white area with the 3 sliders (which is bound to the SettingsViewModel). Clicking the X button executes a RelayCommand defined in the MainViewModel. This command is very simple: It just calls the RequestShutdown method.

ShutdownCommand = new RelayCommand(ShutdownService.RequestShutdown);

Sending messages from a ViewModel to another

Another thing the MainViewModel does it define a bindable property called BackgroundBrush. This property, when updated, automatically sets the background of the application (through databinding). However, how do we know when the user changes the Brush?

In this simple application, we don’t really need two ViewModels. However, it makes sense to have them: If we decided to move the 3 sliders to a popup, for example, or to another window, it would be very easy to do, thanks to the separation of concerns: MainViewModel takes care of the MainWindow, SettingsViewModel takes care of the settings.

This poses a problem however: Since both ViewModels are separated, how can they communicate without being tightly coupled, which we really want to avoid. Well this is another usage for the Messenger: The MainViewModel registers for any message of type Brush:

public MainViewModel()
{
    if (IsInDesignMode)
    {
        BackgroundBrush = new SolidColorBrush(Colors.Orange);
    }
    else
    {
        Messenger.Default.Register<Brush>(
            this, 
            true, 
            m => BackgroundBrush = m);

        ShutdownCommand
            = new RelayCommand(ShutdownService.RequestShutdown);
    }
}
  • Whenever a message of type Brush is received, we just set the BackgroundBrush to it.
    The Messenger class can be used to send any message type, from simple values to complex objects!

  • Note that we use an overload of the Register application: The second parameter is set to true, indicating that we want to receive all messages of type Brush, and derived types too (SolidColorBrush, LinearGradientBrush, etc…).

  • If we are in design mode (running in Expression Blend for example), we set the brush to Orange, so that we have something to see (otherwise the window would be transparent).

Finally, we need someone to send updates! This is the SettingsViewModel’s task: When the user moves the sliders, we send a message of type SolidColorBrush, corresponding to the value of the 3 sliders. We do, however, send this message only to MainViewModel, thus avoiding too much unnecessary communication.

private void SendBrushUpdate()
{
    if (_isLoading)
    {
        return;
    }

    Messenger.Default.Send<Brush, MainViewModel>(
      GetCurrentBrush());
}

private Brush GetCurrentBrush()
{
    return new SolidColorBrush(
      Color.FromArgb(255, Red, Green, Blue));
}

Specific implementation details for Silverlight

  • Most objects in this application are shared between WPF and Silverlight.
    Reminder: To share objects, you can right click on a folder, select “Add, Existing Item” from the context menu. Browse to the item you want to share, then instead of clicking on the “Add” button, click on the small arrow within this button, and choose “Add as a Link” from the menu that opens.
  • Instead of saving the settings to the file system (which is not allowed in Silverlight), we save to the IsolatedStorage. The class SettingsFileHandler is not the same in Silverlight than in WPF, and takes care of this implementation detail.
  • Similarly, we do not have a XAML Writer in Silverlight, unfortunately. Instead of saving the settings to XAML (which is very easy and convenient), we use an extension of the partial class Settings (available only in the Silverlight version of the application) to serialize to a text format, and to deserialize from it.
  • Finally, we cannot shut down the application in Silverlight. We can, however, navigate to a different web page. Since the Shutdown() method doesn’t exist in the Application class in Silverlight, we provide an extension method (in the class ApplicationExtensions) with the same name.

These few techniques (partial class with specific Silverlight extensions, extension methods, adding items as link) help to “bridge the gap” between WPF and Silverlight and to write less code while providing similar functionality.

About NotificationMessageAction

This useful message type (allowing to send a notification and providing a callback to the recipient) is not yet part of the MVVM Light Toolkit V2, but will be included in future versions. An implementation is provided as part of the sample application, but is not final yet. Comments or feedback is welcomed!

Source code

The sample application’s source code can be downloaded from my site.

Conclusion

This sample application shows two usages of the Messenger class:

  • Enable communication between decoupled ViewModels.
  • Create a clean shutdown sequence that can easily be extended with new objects if necessary.

There are of course many other situations where a Messenger can be useful in an application. I hope to have awaken your interest for this very powerful yet simple to use component. For more information about the Messenger, RelayCommands or other parts of the MVVM Light Toolkit, please refer to the Get Started page.

 

MVVM Light Toolkit on Codeplex

Responding to a few requests from MVVM Light Toolkit users, I opened a project on Codeplex and published the installer as well as the source code there.

http://mvvmlight.codeplex.com/

Formally, nothing much changes, my site and my blog remain the main location to find information on the toolkit. Being on Codeplex gives the project more visibility, and provides a convenient place for discussions too.

Happy coding!

 

MVVM Light Toolkit V2: What’s new?

I am happy and proud to announce that the MVVM Light Toolkit V2 has been published!

Shortcut: Jump directly to the installation instructions.

Excerpt from the Get Started page:

The main purpose of the toolkit is to accelerate the creation and development of MVVM applications in WPF and Silverlight.

Like other MVVM implementations, the toolkit helps you to separate your View from your Model which creates applications that are cleaner and easier to maintain and extend. It also creates testable applications and allows you to have a much thinner user interface layer (which is more difficult to test automatically).

This toolkit puts a special emphasis on the "blendability" of the created application (i.e. the ability to open and edit the user interface into Expression Blend), including the creation of design-time data to enable the Blend users to "see something" when they work with data controls.

What’s new?

So what is new in V2? Here is a list that should help you adapt your existing applications to the new version.

New Messenger API

The major change in this release is the new and improved Messenger class. The API has been reworked and simplified to make sending and registering for messages a one-liner each. Any type of message can now be sent, from simple values (int, double, string etc…) to complex messages.

The old methods are still available, however they have been marked Obsolete, which will cause warnings to appear in the Output window of Visual Studio when you build an existing application. I encourage you to upgrade to the new API, which should be quite harmless and rewarding.

There is also an IMessenger interface that the Messenger implements, which makes mocking and testing easier.

The new methods are described in an existing blog post, and additional blog posts around this component will follow.

Expression Blend templates

The MVVM Light templates (project templates and item templates) are now installed for Expression Blend 3 too. You can create and run new MVVM Light applications in this fantastic tool. With the help of the Blend source code editor, you can even consider writing simple MVVM applications without using Visual Studio at all (though for more complex applications, this might prove difficult).

More information about creating new applications in Expression Blend can be found in a related article.

Never miss a new version!

I wanted to make a small application to help you check really fast if a new version of the MVVM Light Toolkit is available for download. Simply choose Start / MVVM Light Toolkit / Check Version On Server, et voila. It’s simple and fast (of course, an Internet connection is required ;)) More information about this application is available here. Oh, by the way, this is, of course, an MVVM Light application.

Easier to find in the Start menu

The shortcuts for V1.1 were installed in Start / All Programs / Laurent Bugnion (GalaSoft) / MVVM Light Toolkit. This was not very convenient, and made them more difficult to find than it should be. I changed this, and the shortcuts are now under Start / All Programs / MVVM Light Toolkit.

Note: The V2 installer attempts to delete the shortcut folder “Laurent Bugnion (GalaSoft)”, since it is not needed anymore. Depending on your system’s configuration, this step might be unsuccessful, and you might have to delete this shortcut folder manually.

Minor changes

A few minor changes have been made, that shouldn’t affect the way that the Toolkit works, but make things a bit cleaner:

  • The method RelayCommand.RaiseCanExecuteChanged(bool) has been marked Obsolete and replaced by RelayCommand.RaiseCanExecuteChanged(). The parameter was not really necessary and has been removed.
  • In the “Add new project” dialog in Visual Studio, the WPF project template has been moved from “MVVM” to “Windows / MVVM”. It makes more sense to put all the WPF content under the Windows category.
  • In the project template for WPF, I moved the resource dictionary "Skin.xaml” to a folder named “Skins” and I renamed the file “MainSkin.xaml”.
  • For consistency, in Silverlight, I also added a “Skins” folder in the project template, and moved all the resources from App.xaml to MainSkin.xaml. Note that this features will not work in Silverlight 2 applications (but hey it’s time to move on, right?).
  • Cosmetic changes: Quite a few small improvements (“polish”) have been made to make the experience (installing and using the toolkit) more consistent and clean.

Bugs corrections

There were a few issues with V1.1 that have been corrected in V2:

  • A scenario I had not envisioned was causing issues: When a recipient would receive a message, and in the method handling that message would register another recipient for the same message type, an Exception occurred. This bug has been corrected and unit tests added to verify this behavior.
    Thanks to Laurent Kempé for finding this one and helping me solve it, and to Innoveo for giving him some time to do this.
  • The property ViewModelBase.IsInDesignMode was returning false all the time when the assembly was compiled in Release mode. The value is now correct in Debug and Release modes.
  • (Silverlight only) When a RelayCommand was bound to a control, the control was not disabled properly if the command’s CanExecute method was returning false before it was bound.
    Props go to Corrado Cavalli for finding this bug.
  • The manual step that was required when creating a new Silverlight MVVM Light application is not required anymore. I modified the project template to take care of this.

Conclusion

With these changes, the MVVM Light Toolkit should be easier to use, which is my main goal and the motivation that drives me.

In next releases, new components will be added to make MVVM application development more fun and enjoyable. I am very careful when I add a new component to the toolkit to keep it “light”. The MVVM Light Toolkit is not a “solution to all the problems”, and never will be. It does, however, make it quite easy to start creating clean applications in Silverlight and Windows Presentation Foundation. Its stated goals (improving the blendability of applications, making them easier to test, separation of concerns, avoiding “component overload”) are, I hope, respected. I encourage you to give me feedback (many already did, and I am grateful for that) and new ideas.

 

MVVM Light Toolkit Messenger V2 beta

Update: MVVM Light Toolkit V2 has been released. Please use the new installer to upgrade your installation.

Ever since I released V1.1 of the MVVM Light Toolkit, I have received wonderful and constructive feedback from users. Most of it is flowing into V2, which is almost ready (I am still fighting a little with MSI installers and project/item templates for one feature I am particularly happy about, which is making project templates and item templates available in Expression Blend. That’s right, with V2 you can start Blend, and choose “File / New Project / MVVM Light”, then press F5 to have an application running.

IMHO the most interesting and innovative change in the toolkit is the new Messenger. In V1.1, quite a lot of plumbing as involved to register for messages, and to send messages. You had to implement IMessageRecipient to get messages, and all messages had to inherit the MessageBase class. Let’s face it, this was a bad idea. Thankfully, Glenn Block (of MEF and Prism fame) called me on that, and suggested a much, much cleaner implementation: Get rid of IMessageRecipient and use Actions instead to register for messages. Get rid of MessageBase and allow me to send anything through the Messenger.

The new API

This immediately appealed to me (and to some of my users whom I talked to) and I propose to you the Messenger V2. It implements the IMessenger interface, which should make mocking and testing easier. The interface looks like this:

/// <summary>
/// Registers a recipient for a type of message TMessage. The <see cref="action" />
/// parameter will be executed when a corresponding message is sent.
/// <para>Registering a recipient does not create a hard reference to it,
/// so if this recipient is deleted, no memory leak is caused.</para>
/// </summary>
/// <typeparam name="TMessage">The type of message that the recipient registers
/// for.</typeparam>
/// <param name="recipient">The recipient that will receive the messages.</param>
/// <param name="action">The action that will be executed when a message
/// of type TMessage is sent.</param>
void Register<TMessage>(object recipient, Action<TMessage> action);

/// <summary>
/// Registers a recipient for a type of message TMessage.
/// The <see cref="action" /> parameter will be executed when a corresponding 
/// message is sent. See the <see cref="receiveDerivedMessagesToo" /> parameter
/// for details on how messages deriving from TMessage (or, if TMessage is an interface,
/// messages implementing TMessage) can be received too.
/// <para>Registering a recipient does not create a hard reference to it,
/// so if this recipient is deleted, no memory leak is caused.</para>
/// </summary>
/// <typeparam name="TMessage">The type of message that the recipient registers
/// for.</typeparam>
/// <param name="recipient">The recipient that will receive the messages.</param>
/// <param name="receiveDerivedMessagesToo">If true, message types deriving from
/// TMessage will also be transmitted to the recipient. For example, if a SendOrderMessage
/// and an ExecuteOrderMessage derive from OrderMessage, registering for OrderMessage
/// and setting receiveDerivedMessagesToo to true will send SendOrderMessage
/// and ExecuteOrderMessage to the recipient that registered.
/// <para>Also, if TMessage is an interface, message types implementing TMessage will also be
/// transmitted to the recipient. For example, if a SendOrderMessage
/// and an ExecuteOrderMessage implement IOrderMessage, registering for IOrderMessage
/// and setting receiveDerivedMessagesToo to true will send SendOrderMessage
/// and ExecuteOrderMessage to the recipient that registered.</para>
/// </param>
/// <param name="action">The action that will be executed when a message
/// of type TMessage is sent.</param>
void Register<TMessage>(object recipient, bool receiveDerivedMessagesToo, Action<TMessage> action);

/// <summary>
/// Sends a message to registered recipients. The message will
/// reach all recipients that registered for this message type
/// using one of the Register methods.
/// </summary>
/// <typeparam name="TMessage">The type of message that will be sent.</typeparam>
/// <param name="message">The message to send to registered recipients.</param>
void Send<TMessage>(TMessage message);

/// <summary>
/// Sends a message to registered recipients. The message will
/// reach only recipients that registered for this message type
/// using one of the Register methods, and that are
/// of the targetType.
/// </summary>
/// <typeparam name="TMessage">The type of message that will be sent.</typeparam>
/// <typeparam name="TTarget">The type of recipients that will receive
/// the message. The message won't be sent to recipients of another type.</typeparam>
/// <param name="message">The message to send to registered recipients.</param>
void Send<TMessage, TTarget>(TMessage message);

/// <summary>
/// Unregisters a messager recipient completely. After this method
/// is executed, the recipient will not receive any messages anymore.
/// </summary>
/// <param name="recipient">The recipient that must be unregistered.</param>
void Unregister(object recipient);

/// <summary>
/// Unregisters a message recipient for a given type of messages only. 
/// After this method is executed, the recipient will not receive messages
/// of type TMessage anymore, but will still receive other message types (if it
/// registered for them previously).
/// </summary>
/// <typeparam name="TMessage">The type of messages that the recipient wants
/// to unregister from.</typeparam>
/// <param name="recipient">The recipient that must be unregistered.</param>
void Unregister<TMessage>(object recipient);

/// <summary>
/// Unregisters a message recipient for a given type of messages and for
/// a given action. Other message types will still be transmitted to the
/// recipient (if it registered for them previously). Other actions that have
/// been registered for the message type TMessage and for the given recipient (if
/// available) will also remain available.
/// </summary>
/// <typeparam name="TMessage">The type of messages that the recipient wants
/// to unregister from.</typeparam>
/// <param name="recipient">The recipient that must be unregistered.</param>
/// <param name="action">The action that must be unregistered for
/// the recipient and for the message type TMessage.</param>
void Unregister<TMessage>(object recipient, Action<TMessage> action);

No Memory Leaks

One neat thing with the Messenger (already in V1 and of course also in V2) is that the objects are referenced using WeakReferences. Even though I recommend to unregister explicitly when you want to delete the message recipient, if you omit to do so, you won’t cause a memory leak, because the Messenger does not keep a hard reference to the recipient.

Backwards compatibility

All V1 methods are still available, but marked as Obsolete. This allows a smooth evolution of existing projects to the new syntax. When you build existing projects with the new toolkit, you will get warnings with a suggestion to move to the new syntax.

The MessageBase class and the deriving message types (GenericMessage, CommandMessage, CommandMessageGeneric, DialogMessage, PropertyChangedMessage) are still available as suggestions for the payload (i.e. you can use them if you like, but you can also build your own messages, or send anything you want (objects, simple value types, etc…). It is perfectly legal to do:

// Somewhere
Messenger.Default.Register<string>(this, DoSomething);

// Further
private void DoSomething(string message)
{
    // ...
}

// Somewhere else
Messenger.Default.Send(“Hello world”);

Default Messenger, mocking, testing, IoC

Note that like in V1, you can either use the default Messenger (Messenger.Default) or create your own messengers, for example to create specialized channels of communication. Since the IMessenger interface is now available, you can easily mock, test, use IoC containers, etc…

The Messenger V2 as well as the rest of the toolkit will be available in a few days, and I will also prepare sample applications to demonstrate the use more in-depth.

 

Using RelayCommands in Silverlight and WPF

Like most of us have found out the hard way, Silverlight 3 and Windows Presentation Foundation 3.5 are two quite similar beasts, but not totally the same. Silverlight is often presented as a subset of WPF (in fact, some features are available in Silverlight but not yet in WPF; generally speaking, though, it is true that Silverlight has less features than its big sister WPF) (yeah WPF is a girl, don’t tell me you didn’t know ;))

No Commands in Silverlight

One of the missing parts is Commanding. Commands in WPF are used as a kind of “weak events”, i.e. they can be used to execute an action when a control is actuated (just like an event), but without the tight coupling that an event brings with it. You can specify a Command on an object, and bind this command to a control in a completely different part of your application. You can have one person write the Command (typically a developer), and a completely other person (typically a designer) use the Command in the user interface. More interestingly, the designer can change the look and feel, for example replacing a series of Buttons by a Menu and MenuItems, and the developer doesn’t need to change anything to the code.

In Silverlight, parts of the “plumbing” are available already (the ICommand interface) but most of it is missing. This led some very clever people to implement Commands in Silverlight, to replace the missing pieces by a custom implementation. In Prism, the command implementation is called DelegateCommand. In my MVVM Light Toolkit, I use a command that my good friend, colleague at IdentityMine and fellow WPF Disciple Josh Smith created, called the RelayCommand.

Now, the beautiful part is that RelayCommands (and DelegateCommands too) work wonders in Silverlight, but also in WPF. RelayCommands are making your life much easier in WPF too. No need to implement complicated code to bind the control to your method, just use a RelayCommand to do that. And since the implementation is (almost) the same in Silverlight too, you can share code between Silverlight and WPF.

The Execute Method

When the control to which a Command is bound is actuated by the user, the Execute method is called. This method is specified by the ICommand interface, and every ICommand implementation must offer it (and of course RelayCommand does).

The Execute method is passed to the RelayCommand’s constructor in form of an Action (or Action<T> if the command has a parameter, in which case you must use the RelayCommand<T> class).

Note: An Action is a method  (returning void) that can be passed to another object, for example as a parameter. It is something like a method pointer. If the method that the Action represents has a parameter, you must use Action<T> where T is the parameter’s type. There are also additional Action implementations with more than one parameters, but RelayCommand can only have 0 or 1 parameter.

The code to create a RelayCommand is:

public RelayCommand MyCommand
{
    get;
    private set;
}

public MainViewModel()
{
    MyCommand = new RelayCommand(
        () => DoSomething());
}

Note: The syntax () => DoSomething() is called a lambda expression, and is the shortest way to define and pass an Action to an object. In the sample here, the method DoSomething will be called without any parameter when the Command is executed.

CanExecute and CanExecuteChanged

Apart from the Execute method that the ICommand interface specifies, there is an additional method and an event that every ICommand (including, of course, RelayCommand) must offer.

  • CanExecute: This method should return true if the command can be executed. When the Command is used on a control, the control will be disabled automatically when CanExecute returns false.
  • CanExecuteChanged: This event should be raised when the CanExecute method must be “requeried” (when the value of CanExecute might have changed, and should be re-evaluated).

The CanExecute method can be passed to the RelayCommand constructor as a Func<bool> (or a Func<T, bool> if the command has a parameter).

Note: A Func is exactly like an Action, except that it has a return type. In the case of RelayCommands, the return type is bool: True if the command can be executed, false otherwise.

To create a command with an Execute and a CanExecute methods, you can do:

public RelayCommand MyCommand
{
    get;
    private set;
}

public MainViewModel()
{
    MyCommand = new RelayCommand(
        () => DoSomething(),
        () => return MyValue);
}

In the code above, if MyValue is true, the command can be executed; if it is false, the command cannot be executed (and controls using that command are disabled). This can depend on multiple parameters such as the state of the application, the time of the day, the weather outside, etc.

Note: When using lambda expressions, if the expression is just “return something”, the “return” keyword can be omitted. So the code becomes:

public RelayCommand MyCommand
{
    get;
    private set;
}

public MainViewModel()
{
    MyCommand = new RelayCommand(
        () => DoSomething(),
        () => MyValue);
}

The CommandManager

RelayCommands are available for WPF and Silverlight. However, one piece is missing in Silverlight: Windows Presentation Foundation has a class that is watching your UI, and that polls the commands’ state when something happens (for example when the user clicks a button, checks a checkbox, open a menu, etc…). This class is called the CommandManager and it doesn’t exist in Silverlight. Not at all. Nada.

So when a user actions the UI in WPF, this triggers the CommandManager to requery all the commands. In Silverlight you have to do the work yourself. This is why the RelayCommand class has a method called RaiseCanExecuteChanged. This method forces the control that uses the command to check again if the command may be executed or not. And if the command may not be executed, the control is disabled.

In WPF

Strictly speaking, in WPF, and if your command is bound to a control that is watched by the CommandManager, you shouldn’t have to raise the CanExecuteChanged event yourself. You can let the CommandManager handle the situation. That said, external events might also change the state of the UI. Let’s imagine that the UI should be enabled from 9AM to 5PM, and then disabled for the night. The user is not triggering the UI, so the code should request (politely) that the CommandManager requeries the state of the commands. This is done by calling the method InvalidateRequerySuggested on the CommandManager. And as you guessed, the method RaiseCanExecuteChanged of the RelayCommand class does just that.

And in Silverlight

However, since Silverlight doesn’t have the CommandManager, a little more manual work is involved. When the state of your object changes in a way that affects the UI, you must RaiseCanExecuteChanged on the corresponding commands. In Silverlight, this will raise the CanExecuteChanged event, thus forcing the bound controls to call CanExecute. In WPF,  like we just saw, this will call InvalidateRequerySuggested on the CommandManager.

Show me the code

I created a small demo to illustrate this in Silverlight and in WPF, using the MVVM Light Toolkit. Most of the code is shared between WPF and Silverlight. The source code for the application is available as usual (WPF 3.5 SP1 and Silverlight 3).

The demo exposes one command, created in the MainViewModel class:

public RelayCommand IncreaseCounterCommand
{
    get;
    private set;
}

public MainViewModel()
{
    IncreaseCounterCommand = new RelayCommand(
        () => Counter++,
        () => CanIncrement);
}

The Counter and CanIncrement properties are raising the PropertyChanged event when they are modified, thus data bindings that refer to these two properties will be updated whenever the properties are modified. What the code above means is: When the IncreaseCounterCommand is executed, check the CanIncrement property. If it is true, increment the Counter property.

2009092601

Figure 1: WPF demo application, Enabled and Disabled

Disabling the button

We have a manual way to enable/disable the “increment” button: If you click on the “Enabled” text, it will turn into “Disabled”. This text (it’s a ToggleButton) is bound to the CanIncrement property directly. So in fact, when the text is “Disabled”, the CanIncrement property is set to false.

Of course, we want the controls using this command to be automatically disabled/enabled when the CanIncrement property changed. In WPF, nothing needs to be done, because the CommandManager will automatically requery the state of the commands when the user clicks on the UI. In fact the state of the commands is requeried very, very often during the course of the application. Even just moving the mouse on the UI causes the CommandManager to requery the state of commands bound to visible UI element.

In Silverlight however, no CommandManager, so we need to raise the CanExecuteChanged event on the command manually. Note that raising the CanExecuteChanged event can be useful in WPF too if you change the CanIncrement property in the code, for example through a timer. So, in fact, we will just call IncreaseCounterCommand.RaiseCanExecuteChanged() in Silverlight and in WPF too when CanIncrement changes:

public bool CanIncrement
{
    get
    {
        return _canIncrement;
    }

    set
    {
        if (_canIncrement == value)
        {
            return;
        }

        _canIncrement = value;

        // Update bindings, no broadcast
        RaisePropertyChanged(CanIncrementPropertyName);

        IncreaseCounterCommand.RaiseCanExecuteChanged();
    }
}

Just a warning: In V1 of the MVVM Light Toolkit, the method RaiseCanExecuteChanged was taking a boolean parameter. This boolean was actually not very useful, and has been removed in V2. Calling the old method still works in V2, but the parameter has no effect, and the method has been marked Obsolete. It will be removed in a future version of the toolkit.

This sample uses V2 beta of the MVVM Light Toolkit.

Silverlight/WPF Compatibility

Much of the code is shared between Silverlight and WPF in this small demo.

  • The ViewModel code is completely shared. The source code files are physically into the WPF project, and added as links into the Silverlight project. Implement once, compile twice.
    To add a source code file as a link, choose “Add existing item” in Visual Studio. Then, select a file. Instead of clicking on Add, click on the arrow on the right of the Add button, and select “Add as a link”.
  • The resources defining the look&feel of the application are placed into the file Skins\MainSkin.xaml. The code n this file is 100% the same in WPF and in Silverlight. To reuse the Silverlight control templates in WPF too, I use the WPF Toolkit’s implementation of the Visual State Manager.
  • Finally, the XAML code in the main UI element (MainWindow.xaml in WPF, and Page.xaml in Silverlight) is almost the same, except for one little difference: Since Silverlight doesn’t support commands out of the box, we rely on an attached behaviour to bind the RelayCommand to the Button:
<Button cmd:ButtonBaseExtensions.Command="{Binding IncreaseCounterCommand}"
        Grid.Row="2"
        Style="{StaticResource IncrementButtonStyle}"
        Content="Increment" />

Conclusion

Commands in WPF are quite a complex topic, and I must admit that I didn’t completely understand them before I discovered the RelayCommand class. I totally fell in love with this fantastic helper. Josh Smith has been fantastic in allowing me to re-use his code in the MVVM Light Toolkit. I hope that this article will help you understand the power and convenience of RelayCommands. Happy coding!