Let me expand on the title, with this post we will build an iPhone-styled Sudoku Game application in Silverlight using nRoute Toolkit. In terms of the architecture we will make use of MVVM design techniques in having separate Model, ViewModel, View plus related Services - and we'll piece them together in a loosely-coupled manner. As a starting point, we'll make use of a Sudoku puzzle-generating engine from an existing Siverlight implementation by Lee Saunders, upon this we will build our MVVM friendly layers.

SudokuPreview the Sudoku Application here

Application Model

In Lee Saunders' Sudoku implementation the puzzle-generating engine asks for an expertise level, and in return it hands over two arrays of string type that represented the incomplete and completed puzzle. However for a proper MVVM design that is not adequate, and so we have to encapsulate the puzzle in a proper model that enables both binding and serialization of the puzzle. Post churning, the resulting Application Model, shown below, has two principle concepts - a "Game" which is the puzzle board as such, and the "Box" which is an individual playable square of the board. Each Box type is uniquely indentified using a row and column placement on the Board, and per the Sudoku concept each Box can either be a given or must be user specified - so accordingly we have the IsPredefined property and a SuggestedValue property that holds the user's input. The ExpectedValue property holds the required/correct value, and the possible Suggested and Expected values are constrained using the BoxValue enumeration. The GameLevel enumeration holds the user specified expertise level.

Application Model

 ViewModel (VM)

Given we have the Model part of MVVM, we proceed to the VM - the main thrust of the VM is two fold, one expose the Game data for UI consumption, and two expose the Game-related functionality as UI consumable ICommands. And we do both, as shown below, with our GameViewModel class. Note we are using nRoute Toolkit specific implementations of ICommands.

GameViewModel

In terms of the implementation, the first thing we do is earmark the GameViewModel class as being ViewModel of the GameView UserControl - see the MapViewModel attribute. Also note, the ViewModeBase is an optional helper class that just implements INotifyPropertyChanged and exposes a method to use the same. Next, we expose the Game model via the Game property in the VM - this provides us access to the Boxes that make up the board in the UI. Following that, we have a series of ICommands like NewGame, Reset, Hint, Confirm etc that basically mirror the functionality in the model. And we also enable saving and restoring of a game in the IsolatedStore via the SaveGame and RestoreGame commands. We also have one Reverse Command (which are basically ICommands that execute in the View and are triggered from the VM), the ViewBoardReverseCommand, that basically allows the VM to instruct the View to show the board visuals when required (a sample case is when we restore a Game from the IsolatedStore, the VM asks the View to show the board visuals immediately).

I'll also point out that the distinction between ActionCommand and ActionableCommand - the later allows us to specify a pre-condition to the execution of the ICommand. So for example, the SaveGame command is declared as follows:

   1: SaveGameCommand = new ActionableCommand(
   2:     () => IsolatedStore.SaveDataObject(Game, FILE_NAME), 
   3:     () => Game != null)
   4: .RequeryOnPropertyChanged(this, () => Game);

Line 2 is the execution handler of the ICommand, which in this cases saves the current Game in the IsolatedStore, and in Line 3 we specify a pre-condition to the execution which says that the Game should not be null - this as shown below has repercussion in the UI. And in Line 4 we use an extension method for ICommands to declare that whenever the Game property (of our INotifyPropertyChanged implementing) VM (i.e. this) changes, then re-evaluate the executable state of the command.

SaveGameView

View

For our View we have basically divided the functionality into two screens named Home Screen and Game Screen, these screens are implemented as Visual States of the User Control. Peppered on the screen are various functional elements that trigger various commands we have defined in our VM - for example the "Confirm" element corresponds to ConfirmCommand in the VM, similarly the "Easy" element triggers the NewGameCommand with an "GameLevel.Easy" enumerated parameter. Note, to keep things light and to my preference, all button like elements in UI are actually Border controls rather than Button controls, however you could change that if you like.

Two Screens

Now to automagically inject the appropriate VM we drop the BridgeViewModel behavior onto the UserControl (see below) and optionally, if we wanted, through the same behavior we could also specify some control-lifetime related commands against the VM (eg. command to trigger when the User Control is loaded).

States And BridgeViewModel Behavior

In the Game Screen, the 9x9 board is an ItemsControl bound to the Game.Board property from the VM, and the ItemsControl's ItemsPanelTemplate is a custom Grid control with 9 columns and 9 rows. Further, the ItemsControl's ItemTemplate shows either a Grey'ish Border (i.e. pre-defined value) or an interactive Blue'ish Border (i.e. user-defined value) control. We position each item in the grid using a custom "SetParentGridPos" behavior which binds the grid position to the Col and Row property of the Box Type from our Model. And to enable user specifying the Box value, we rig the Blue'ish Border control to trigger SetBoxValue command in our VM. However to enable the use of the command within the DataTemplate, we need to relay it from our VM - so we first we declare a static RelayCommand, and then bridge the relay from our VM, that is done using the BridgeCommandBehavior (again see the screenshot above).

ViewServices

You can think of ViewServices in nRoute as services that are implemented visually - and here we have two such ViewServices, one that shows messages and another one that get a user's input.

ViewServices

Above are the visual interpretations, but the VM actually uses something like this:

ViewServicesInterfaces

In our app, both these interfaces are implemented in the code-behind by the GameView type UserControl. Now there are many other ways to do this, but I am comfortable with what is essentially a visual implementation to be implemented within the View's code-behind. Also, because the VM doesn't take any hard-coded dependency on the View, you can change the visual implementation at any point as long as the defining contract remains the same.

   1: [MapViewService(typeof(IBoxValueViewService), 
   2:     Lifetime = ViewServiceLifetime.DiscoveredInstance)]
   3: [MapViewService(typeof(IMessageViewService), 
   4:     Lifetime = ViewServiceLifetime.DiscoveredInstance)]
   5: public partial class GameView 
   6:     : UserControl, IBoxValueViewService, IMessageViewService
   7: {
   8:     //  IBoxValueViewService and IMessageViewService implementations..
   9: }

Above we use the MapViewService attribute to earmark the GameView type as the concrete implementation of both ViewServices, also note we are setting the ViewService's Lifetime to be "DiscoveredInstance", which means nRoute will look for the implementation in the VisualTree at runtime. And in terms of using the ViewServices in the VM, we use the ViewServiceLocator static class as such:

   1: var _messageViewService = ViewServiceLocator.GetViewService<IMessageViewService>();
   2: _messageViewService.ShowMessage(message);

Bootstrapping

One last point, to use nRoute you need to bootstrap it by adding it to the application's ApplicationLifetimeObjects collection, so in App.xaml we need to something like this:

   1: <Application  ...
   2:     xmlns:nRoute="clr-namespace:nRoute.ApplicationServices;assembly=nRoute.Toolkit">
   3:     <Application.ApplicationLifetimeObjects>
   4:         <nRoute:nRouteApplicationService />    <!-- BOOTSTRAP nRoute -->
   5:     </Application.ApplicationLifetimeObjects>
   6: </Application>

Summary

So here what we've got is an end-to-end example of using nRoute to develop a MVVM type application, right from the ApplicationModel to the ViewServices. Further, by cleanly delineating the various application parts and using nRoute to bring them together we usefully get a loosely-coupled but cohesive application.

You can view the Sudoku Application here,
and download the source code from Codeplex

Update (24-1-2010):

I updated the application to show a waiting indicator (by Chris Anderson) when creating the puzzle, as it was taking an inordinate amount of time. I also moved the new game generation code into a separate service (see IGenerateGameService), which makes use of a background worker thread so the UI should be a bit more responsive.

nRoute Toolkit is basically a packaging of some components from the next drop of nRoute - I thought some of the components had merit beyond the nRoute framework, so I packaged them separately in a smallish 50K toolkit. The Silverlight only toolkit features Bindable Dependency Objects, Bindable Triggers, Actions and Behaviours for Blend, an IObservable-based Messaging Framework, a Resource Locator Framework, Module Components, Service Components, ViewModel Components, ViewService Components, Weak Eventing Handlers, Action ICommands and a number other bit and pieces useful for MVVM style development.

I hope to have this introductory post as a semi-documentation for the toolkit and its features, so please bear with me as it does get long. Secondly, the next drop of nRoute will essentially be a superset of what's in this toolkit - namespaces and all will remain the same, however the toolkit doesn't include any routing or navigation related features.

Bindable Dependency Objects

One of the biggest pain point with Silverlight, as of version 3, is that it only supports binding on FrameworkElement derived objects - which in effect limits binding to "visual components" - and therefore "inline" elements don't get the benefit of binding. Now, what I have here is not a perfect solution but a pretty workable one, and I refer to it as attached-bindings because it attaches the binding on any FrameworkElement derivatives (even non-hierarchically related).

The trick in play here is that you have to expose and consume the binding as a System.Windows.Data.Binding type. So for instance, say we have a Dependency Object derived class that has a ordinary "IsReady" dependency property; now, to make it bindable using attached bindings, we have to use what I call a dual-property pattern - wherein we expose the property "normally" but also have another property (post-fixed with the Binding word) of type Binding that is used to bind to the dependency property. Have a look below, note 'GetAttachedBinding' and 'SetAttachedBinding<T>' are extension methods:

   1: public bool IsReady
   2: {
   3:     get { return Convert.ToBoolean(this.GetValue(IsReadyProperty)); }
   4:     set { this.SetValue(IsReadyProperty, value); }
   5: }
   6:  
   7: public Binding IsReadyBinding
   8: {
   9:     get { return this.GetAttachedBinding(IsReadyProperty); }
  10:     set { this.SetAttachedBinding<bool>(_frameworkElement, IsReadyProperty, value); }
  11: }

Given the above, to bind we use the binding syntax against the 'IsReadyBinding' property, while to read the current value of we use 'IsReady' property. If you don't want to use bindings, the IsReady property works just as before and everything else remains the same. The critical part to enable attached bindings is to have a FrameworkElement derivative element to attach too, as represented above by the '_frameworkElement' variable - without this it wouldn't work. But once you have that you can have as many attached-bindings appended to it as you like, it doesn't matter. Secondly I understand having an additional property for each bindable property is not ideal, but it's a working solution and is kind of akin to the async post-fix we already use. Plus, with the extension methods shown above this is not that intrusive of a methodology, especially since you don't need do anything more than create an additional property declaration per dependency property.

Now there are a lot of uses for this, and using this infrastructure included in the toolkit are extensions to the Blend behaviours framework as we'll see right ahead - this also happens to be my favourite new feature in the toolkit.

Bindable Behaviors, Actions and Triggers 

In the first drop of nRoute I did a lot of work on behaviours, in fact I did create something very similar to what is available in Blend but didn't generalize it using triggers, rather per my preference of strong-typed stuff, I created many-many statically declared attached properties to expose/use behaviours. But part of the reason was also that inline dependency objects could not be bound in Silverlight, where as attached properties declared directly onto any FrameworkElement derivate could be. Now, with the binding infrastructure given above and fantastic tooling support in Blend, I choose to dump my behaviour's framework and extend the behaviours and triggers framework made available with the Blend SDK - essentially by making them bindable. This really makes for some fantastic possibilities, because we can now use and consume behaviours that are directly bound to our ViewModel or have them react to property changes through the richness of binding in Silverlight.

In the nRoute.Behaviors.Interactivity namespace you will find four classes that extend the behaviours, trigger actions and triggers in the Blend SDK, with bindable base classes.

BindableBehaviors

The binding-enhanced base classes (below the red-line) give you wrappers around the attached binding solution, and a very important capability to set bindings even when the "AssociatedObject" is not available (it stores and applies the binding to it when the object is attached). So for example, if we had the IsReady property sampled above exposed in any of the above behavior/trigger classes we would write the same as:

   1: public bool IsReady
   2: {
   3:     get { return Convert.ToBoolean(this.GetValue(IsReadyProperty)); }
   4:     set { this.SetValue(IsReadyProperty, value); }
   5: }
   6:  
   7: public Binding IsReadBinding
   8: {
   9:     get { return base.GetBinding(IsReadyProperty); }
  10:     set { base.SetBinding<bool>(IsReadyProperty, value); }
  11: }

As you can see in Line 9 and 10 we are using the base-class based GetBinding and SetBinding methods, they do the attach-binding business underneath. So quite simply, to make your behaviour/trigger/trigger-action property bindable you just need to additionally write something similar to lines 7 to 11 and that's it. Also, with this you can use all the UI facilities in Blend to set the bindings as usual, alternatively if you wanted to bind to static resources you would use the non-binding version (ie. IsReady and not IsReadyBinding). The binding-enhanced base classes are there for your own use, but I've also included some commonly needed behaviours, triggers, and trigger-actions some of which are detailed below.

Value Triggers

Value triggers are Blend-SDK based triggers that fire when a given property's value matches a given criteria - for example, you could use a ValueTrigger to show a special discount animation when when the total cart amount exceeds $1000 in your ViewModel. You can also use this with UI controls, like match some value in a text box and trigger a command in your ViewModel.

In many ways ValueTriggers are central to MVVM, because to my understanding in a MVVM architecture data changes are the primary ViewModel-based mechanism that effect changes in View, and for the other side of the equation data changes and ICommands are the two View-based mechanisms that effect changes in the ViewModel (see the diagram below). Events are not used, because they are a form of direct-coupling - and so there is a total reliance on the SL binding infrastructure for the loosely-coupled glue that makes it all possible. Further for me, this minimal scope of connections is both the beauty and the practical stick that keeps the ViewModel and View independent of each other despite the fact they are intimately interwoven.

ViewViewModelSignifiers

Given the concept above, the practical problem in SL today is consuming the data-changes to effect logical changes in your application, value changes in the controls such as text value is 100% supported but changing the logical state is not. And this is where the ValueTriggers come into play, by combining binding, triggers and trigger-action we can effect logical changes in the View such hiding something or moving something. Next, I'll go through the five value triggers available in the toolkit - just keep in mind you can pair this up with just about any trigger-action or behaviour.

ValueMatchTriggerValueMatchTrigger

Basically it allows you trigger an action when a given source's value equals to another specified value - in the example shown from Blend, the value must match the specified "nRoute" value and then only will it trigger the associated action. Also, the source binding is coming from a ViewModel and we're matching it against a static word but you could match it against anything bindable by using the ValueBinding property. Also note any changes in the Source Binding triggers a re-evaluation of the condition. Alternatively, if you require it not match the specified value then you can negate the result, by using the negate checkbox. The xaml for this example looks like:

   1: <nTriggers:ValueMatchTrigger SourceBinding="{Binding Key, Mode=OneWay}" Value="nRoute">
   2:     <nBehaviors:SetPropertyAction PropertyName="Foreground" Value="#FFFF0000"/>
   3: </nTriggers:ValueMatchTrigger>

Note, by default in Blend the Value property wouldn't be editable, in that case you might have to append it via xaml directly - I hope to create Blend designer extension soon to rectify this.

ValueNullTrigger

This is similar to the ValueMatchTrigger in that it exclusively looks to match the source value to a null. You can also negate this, so that it matches a non-null value. This is really useful when tracking asynchronously loaded data, for example when loaded items list in not null, we could visually effect the UI to indicate the availability of the data. Below is an example of this in xaml:

   1: <nTriggers:ValueNullTrigger SourceBinding="{Binding Key, Mode=OneWay}" Negate="True">
   2:     <nBehaviors:SetPropertyAction PropertyName="Foreground" Value="#FF23FF18"/>
   3: </nTriggers:ValueNullTrigger>

ValueCompareTriggerValueCompareTrigger

Most data comparisons boil down to equals to, greater than, less than or their negated comparisons - and so in addition to earlier mentioned triggers, the ValueCompare trigger allows you to value comparisons with >, >=, ==, !=, <, <= equality operations. For comparison purposes it relies on source value implementing the IComparable interface or you specifying an IComparer implementation.

In the screenshot from Blend show on the right, we compare some Source Value bound from a ViewModel being greater or equal to ten - which triggers the specified trigger action. In xaml the same thing would look like:

   1: <nTriggers:ValueCompareTrigger SourceBinding="{Binding Value, Mode=OneWay}"
   2:     Equality="GreaterThanOrEquals" Value="10">
   3:     <nBehaviors:SetPropertyAction PropertyName="Foreground" Value="#FFFF4321"/>
   4: </nTriggers:ValueCompareTrigger>

Note how dual properties pattern I mentioned earlier, makes everything bindable in Blend but in a bit more extraneous way than normal. Also note the possibility of negating the comparison result, with the negate option.

ValueChangedTrigger

As the name suggest this trigger executes every time its source value changes - which at times is all you need. The xaml example below triggers an animation whenever the value changes:

   1: <nTriggers:ValueChangedTrigger SourceBinding="{Binding Key, Mode=OneWay}">
   2:     <im:ControlStoryboardAction Storyboard="{StaticResource FlashTitleStoryboard}"/>
   3: </nTriggers:ValueChangedTrigger>

ValueSwitchTrigger

Just as in procedural code the switch-cases pairing allows you selectively trigger one or more actions if the Source value matches the Case value. Have a look at a xaml example, first:

   1: <nTriggers:ValueSwitchTrigger SourceBinding="{Binding Value, Mode=OneWay}">
   2:     <nBehaviors:SetPropertyAction nTriggers:ValueSwitchTrigger.CaseValue="1"
   3:         PropertyName="Foreground" Value="#FFFF4321"/>
   4:     <nBehaviors:SetPropertyAction  nTriggers:ValueSwitchTrigger.CaseValue="2"
   5:         PropertyName="Foreground" Value="#FF23FF18"/>
   6: </nTriggers:ValueSwitchTrigger>

In this example we are binding to some "Value" property from our ViewModel, and below are two actions each with a specified case value (using the ValueSwitchTrigger.CaseVale attached property). Now, if the value is one, the first trigger action will be activated, and if value is two the second trigger action will be used. I think it is really simple, yet very powerful and makes use of the all binding goodness in Silverlight.

KeyTrigger KeyTrigger

The KeyTigger is not part of the value-related triggers, all the same it a very useful trigger that responds to keyboard events. Now, I understand there is already an existing KeyTrigger in Blend, but before I found it I had already created this one and I've kept it because it helps with some advance scenarios.

More or less it is all self explanatory, except you can check for more than one modifiers - so a Control+Shift+V can be checked for. Also, you can negate the result to be everything except the keystrokes you have specified, and believe me this is useful. You can also throttle the key inputs by specifying a duration within which only a single key stroke will be processed - again this really useful and recently I had a situation where the UI couldn't keep up with keystrokes so I throttled the user's input and it worked like a charm. Lastly, you can also specify the max number of key strokes past which it will disable the triggering - useful for perhaps limiting baby smash torture.

MouseWheelTrigger.cs MouseWheelTrigger

The MouseWheelTrigger is not like a scrolling solution, it is a trigger which fires when the MouseWheel turns and you can then use it to invoke an action such as scrolling or index change. Also it passes through a delta value, which is factored by whatever you have specified in the DeltaFactor property (the default as shown is 120). And like the KeyTrigger you can throttle the mouse wheel events by defining a time-duration to allow-in a single wheel event.

Trigger Actions

SetPropertyAction I've only included four trigger-actions in this Toolkit, yet I've found them to remarkably useful particularly because they make of the of the binding.

The first of the four triggers is SetPropertyAction, which you've seen being used above - and as the name suggests, it is used to set a property value on the applied element with a specified value. Now, there is something similar already in Blend, but herein we get the possibility to set a binded value - which opens it up to your ViewModel's usage. In the blend screen grab on the right we are setting the text property to a value from our ViewModel, when the associate trigger invokes the action. Also if you just wanted to set the value statically use the non-binding Value property.

Quite similar to the SetPropertyAction is the TargetedSetPropertyAction, using which you set value on another element (ie. the target) as opposed to the declaring element itself. For example:

   1: <i:EventTrigger EventName="Click">
   2:     <nBehaviors:TargetedSetPropertyAction TargetName="BackgroundRectangle"
   3:          PropertyName="Fill">
   4:         <nBehaviors:TargetedSetPropertyAction.Value>
   5:             <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
   6:                 <GradientStop Color="#FFB8EBFF" Offset="0.762"/>
   7:                 <GradientStop Color="White"/>
   8:             </LinearGradientBrush>
   9:         </nBehaviors:TargetedSetPropertyAction.Value>
  10:     </nBehaviors:TargetedSetPropertyAction>                        
  11: </i:EventTrigger>

In the xaml above we are setting the "Fill" property on a Rectangle type element named "BackgroundRectangle" upon a click event. Again by using this with value triggers and binding you get a really powerful tool in your hand, and for the most part this is all Blendable. I will discuss the other two triggers action, in relation to other features because they are related.
 
Behaviours (or Behaviors if you prefer)

I've included four generalized behaviours, in addition to some feature specific ones, and they resolve around the idea of having an element viewable depending on the source being null or not null, or based on some true/false evaluation. This is really useful, in scenarios where you are loading data asynchronous and parts of UI are to be viewable per the availability of data.

So the first of these behaviours is called the BoolValueVisibilityBehavior, which make the targeted element visible if the given bool Value is true else the visibility is set to collapsed. You can negate this behaviour by using the negate option, like before. Similarly, the NullValueVisibilityBehavior sets the visibility to collapsed if the given value is null else it sets it to visible. This is again is negatable, and the value you evaluate against is bindable because it uses BindableBehavior<T> base class mentioned before.

For example, consider we have a search bar we don't want to show until some data is loaded into a ListBox, and so we could attach the following behaviour that tracks as to if the Items property from the ViewModel is null or not. And because we are using dependency properties we listen to data changes, so say if the data is re-loading then the toolbar will automatically hide and show-up when the data has been loaded again.

   1: <i:Interaction.Behaviors>
   2:     <nBehaviors:NullValueVisibilityBehavior ValueBinding="{Binding Items, Mode=OneWay}"/>
   3: </i:Interaction.Behaviors>

NullValueInteractivityBehavior I find the above very useful, but there is a very significant side-effect to setting the visibility to collapsed in that it "shutsdown" the element from processing visual changes. And so for example, if you were to put a NullValueVisibilityBehavior onto a ListBox and wanted to have it viewable once the ItemsSource is set - the items wouldn't show up because when collapsed it wouldn't have process any UI changes - and rightly so.

Now how do deal with that, well firstly we make an element non-viewable by setting its opacity to zero. However, the ListBox could still process mouse events, which is a problem especially if it unknowingly to the user triggers some changes and yet the element is not visible to the user. The second, step to rectify this is to set its IsHitTestVisible property to false - which makes the element non-interactive and yet the UI changes will be processed underneath.

Now, by combining the two solution above I've packaged them as interactivity altering behaviours called BoolValueInteractivityBehavior and NullValueInteractivityBehavior - which like their visibility counterpart, can used to make an element non-viewable though in this case they are capable of processing UI changes. However note this is not a perfect solution, because an element could still possibly handle keyboard triggered changes, if it had the focus. Nonetheless, in a lot of scenarios this works out just fine but be careful of the caveat. And just like before, you can inverse the workings of all these behaviours by using the negate option.

IObservable-based Messaging Framework

Recently, with the Silverlight Toolkit there was a hidden gem shipped by the name of Rx Framework, which you can read about extensively here. Basically, the idea behind it is that by using the observable pattern you can do "reactive programming", kind of like event handling. But the twist is that you can turn past, current and future "observed items" into a persuado data source, which opens it using LINQ to process, shape and consume the observed data. Think event stream processing, as opposed to a pipeline model - and the items are like an IEnumerable being pushed as opposed to being pulled. I am not gonna discuss the reactive framework here, but it is really cool and you should definitely check it out if you still haven't.

In relation to the Rx Framework, what I've done is used its interpretation of the observable pattern vis-e-vie their IObservable<T> and IObserver<T>interfaces (which I understand will be part of .NET 4 and hopefully SL4) and created so-called Observable Channels - which are basically singleton implementations of the IObservable<T> to which you can subscribe and publish. With the publish subscribe capabilities, it becomes a messaging framework kind of like Prism's EventBroker, but with a very easy to use API. 

MessagingFramework

As show above the Channel<T> class is the IObservable<T> implementation, to which any implementation of IObserver<T> can subscribe. Once subscribed, we return an IDisposable implementation based on the ChannelSubscriptionBase<T> class. In simpler terms you subscribe to a channel of Type T, whereby T can be any type you want to send and receive messages for, and on subscription you get a channel subscription token onto which you can call the Dispose method to get yourself unsubscribed.

Now, also provided is a generic IObserver<T> implementation predicatively called ChannelObserver<T>, and it makes it really easy to consume any channel's incoming data, as well Subscribe and Unsubscribe as required. Below is an example, for that:

   1: // declared
   2: ChannelObserver<ApplicationStateInfo> _observer;
   3:  
   4: // subscribe
   5: _observer = new ChannelObserver<ApplicationStateInfo>((s) => DoSomething(s.CurrentState));
   6: _observer.Subscribe(ThreadOption.UIThread);
   7:  
   8: // unsubscribe
   9: _observer.Unsubscribe();

Here we are tunning into the "ApplicationStateInfo" channel, which is one of the build in channel used by the Resource Locator Framework. It basically, publishes application lifetime state changes - which include starting, started, exiting, and exited states (this is based on IApplicationLifetimeAware callings). Note to subscribe one has to explicitly call for it, as shown in line 6, and the option we are excising there is to receive the subscription on the UI thread. Similarly to unsubscribe you need to call the Unsubscribe method and you can also check if you are currently subscribed via the IsSubscribed property. Further, once you have unsubscribed you can subscribe again, which makes it really easy to play/pause a subscription using the ChannelObserver.

By default, subscriptions are weakly referenced - which means that even if a subscriber that goes out-of-scope, were not to unsubscribe, it would still be available for GC (though you should always unsubscribe). On the flip side, if you wanted to ensure a non-weak referenced connection, for performance reasons or otherwise you could choose an option during subscription to keep the subscriber strongly-referenced.  Just as in Prism's Event Broker (whose API I've mimicked), you can subscribe to on the UI Thread, on the Publisher's Thread, or in a Background Thread. Also you have the option to publish asynchronously, however in this case you need to ensure the subscribers don't run into cross-threading exceptions. And keep in mind that, by design, a Channel always throw back any exception raised by a subscriber whilst receiving a payload.

Publishing to a channel is very straightforward, just use either the Channel or Channel<T> class to publish, there are also non-generic overloads available for publishing. Below is a straightforward example, of publishing a SearchQuery:

   1: // to publish a search query
   2: Channel.Publish<SearchQueryInfo>(new SearchQueryInfo("Silverlight"));
   3:  
   4: // to publish async search query
   5: Channel.PublishAsync<SearchQueryInfo>(new SearchQueryInfo("Silverlight"));

ChannelPublishActionAlso included is a trigger action which allows publishing to a channel directly from the UI. Because the ChannelPublishAction can bind the payload from the ViewModel, you could rig say a button 'click' to trigger the publishing. Also it can determine the channel by the type of payload set, however in cases it is expected to be null or based on derived types, you must set the ChannelType explicitly.

Coming back to the Rx Framework, because the channels are basically an IObservable implementation they are open to party on the IObservable-related LINQ operators available in the Rx Framework. And this is big deal, because you do a lot of intelligent processing on the client side (and I will try and show this separately with a post). However note, the current build doesn't take a dependency on the Rx Framework, but a separately compiled version is available if you require.

Resource Locator Framework

IResourceLocator The Resource Locator (RL) is basically a thread-safe register of resource locators, and a resource locator is an implementation of the IResourceLocator interface, which identifies any given resource by a unique name and can return an instance of that resource (see the interface on the right).

This really is not far off from IoC components, but the idea here is that any type of resource can register its own locator. And the locator's resource materialization strategy is its own business, and so when the RL is asked for a resource, it delegates to the locator. The core of this is really very simple, but around the resource registry are a number of utilities that really make it's consumption seamless and almost transparent from direct use. 

The RL is actually a generalization of what was there in the first drop of nRoute; in fact I had two separate implementations one for navigation and one for actions that did the same thing but in a more specific manner. If you have used nRoute you will know things like the MapNavigationContent, MapActionHandler attributes that when used with MapAssemblyRoutes or MapLoadedAssembliesActions static methods located all resources and fed them into the routing engine as routes. Here with the RL, we generalized that to not just produce routes (which themselves are actually locators in a way) but return IResourceLocator which is independent of any particular use.

Now the question is how do we feed locators into the RL registry, we could do it manually one by one, through a configuration file, or we could do using my preferred way by the means of an Assembly Mapper. The mapper basically looks for all MapResourceAttribute derivates in any given assembly, and yields an IResourceLocator implementation, which is then registered automatically.

Well, we have five feature implementations in the toolkit that make use of the RL, lets have a look at them individually.

Modules

The modules concept is straight out of Prism, but herein we use the RL with attribute-based mappings to locate and instantiate a module. For example:

   1: [MapModule("ContactsModule")]
   2: public class ContactsModule : IModule
   3: {
   4:     // .. implementation 
   5: }
 
Well, line 1 is all you need to have this module located and instantiated - we have also given the module a name by which you can locate it within the registry. The MapModule attribute takes two more parameters if you like, one an InitializationMode enumeration by which you can choose to have this instantiated when the application starts or alternatively as required. The other parameter is an optional array of strings declaring dependencies on other modules (by their names) - and the assembly mapper ensures that the module is not instantiated or registered until all the dependencies are resolved. 

Modules

Thanks to the RL, there is nothing much to the Modules concept, and the only important class is the IResourceLocator implementation which is registered into the RL by the MapModule attribute. And the ModuleLocator static class is just a candy wrapper around the ResourceLocator static class, but specifically geared for Modules-related info. Also by overriding the DefaultModulesLocator and MapModuleAttribute implementations you can add more features or change the internal workings to your requirements.

Services 

Again akin to Prism, services are essentially an implementation of some service contract (defined as an interface) which can then be located and realized.

   1: [MapService(typeof(IDateService))]
   2: public class DateService : IDateService
   3: {
   4:     // implementation of IDateService
   5: }

Here in Line 1, we are registering a Service of type IDateService which here is implemented by the DateService class - note the mapped class must implement that identified service contract. Now there are two more optional parameters to that attribute, which let you specify a name for the service, another one lets your list an array of other service types that the is dependent on. Also, you have three more named parameters, using which you can specify the lifetime of the service (see the InstanceLifetime Enum), initialization mode (see the InitializationMode Enum), and a boolean value specifying as to if it is the "default" service. Services

Like with the ModulesLocator static class, we also have a wrapper class for Services which helps with getting/checking for services. Also with services, actually with all types of resources, there is a concept of having a default resource - which is either a specifically designated resource (see the SetDefaultService<T> method above) or by default the first registered resource is considered the default service. So in the case of a default service, it can be retrieved without having to specify a name. So for example:

   1: // get the default service
   2: _dateTimeService1 = ServiceLocator.GetService<IDateTimeService>();
   3: // get a named service
   4: _dateTimeService2 = ServiceLocator.GetService<IDateTimeService>("GMT");

If you said this is just about like using any IoC component out there, well, I would agree with your - and feature-wise this implementation is not even that sophisticated. However the services as a concept has a lot of semantic value, which in this context is a non-visual building block for your application. Nonetheless if you wanted more smarts, you could "smartern" the locators up by creating a custom IResourceLocator implementation that uses an IoC component under the hood.

View Models

In the earlier release of nRoute we had this unfortunately named MapViewModelViewNavigation attribute, using which you could specify the View type, the ViewModel type and a Url to go with that - and what it did was when the Url was requested it instantiated the View in a Navigation Container, then create the ViewModel, which it injected into the View as its DataContext. Here with the toolkit, we don't have the composition capabilities of the nRoute Navigation component, but we have resource locators that can inject the ViewModel into a View using behaviours. Lets look at an example:

   1: [MapViewModel(typeof(Page4))]
   2: public class Page4ViewModel : ViewModelBase
   3: {
   4:     //..
   5: }
   6:  
   7: // OR - choose either way
   8:  
   9: [MapView(typeof(Page4ViewModel))]
  10: public class Page4 : UserControl
  11: {
  12:     //..
  13: }

BridgeViewModelBehaviorAbove we are defining the association between a View and a ViewModel, you could choose either of the two mapping mechanisms - either map the View and specify the ViewModel type or map the ViewModel and specify the View type. Once we have that all you need to do is drop the "BridgeViewModelBehavior" on the View's (at the root level).

This behaviour uses the RL to locate and instantiate a ViewModel instance and then injects it into the View's DataContext. Further, as you can see on the right, we can even bind some commands to the View's lifetime events - specifically for initialization, loading and unloading. Each command can pass in a parameter, and that too is bindable. Unfortunately, the unloading command was not firing so I've disabled it for now - it seems that the OnDetaching method on the behaviour is not being called.

We also a have specialized ViewModelLocator, if you like to use it procedurally.  ViewModelLocator

Also in the nRoute.ViewModels namespace you will also find a ViewModelBase class, which just implements the INotifyPropertyChanged interface and provides an helper to notify property changes. Note, its use is not required.

View Services

The idea of the ViewServices is that the ViewModel shouldn't have to take dependency on visually implemented controls or on platform specific contraptions - think notification balloons, save file dialog, etc. In practical terms, these are exposed just like services, where we have an interface defining the contact and an implementation that is transparent from its consumption. Now, build into the toolkit are four such services for opening files, saving files, showing messages and showing exceptions.
 ViewServicesContracts

To call upon any ViewService you can make use of the ViewServiceLocator static class, which just like the ServiceLocator requires the type of ViewService and optionally a name.

   1: IShowMessageViewService _messageBoxService;
   2:        
   3: // setup 
   4: _messageBoxService = ViewServiceLocator.GetViewService<IShowMessageViewService>();
   5: _messageBoxService.ButtonSetup = MessageBoxButton.OKCancel;
   6: _messageBoxService.Text = "Please confirm?";
   7:  
   8: // use 
   9: var _result = _messageBoxService.ShowMessage();

And similarly, declaring a ViewService is very much like everything else.

   1: [MapViewService(typeof(IShowMessageViewService), IsDefault=true)]
   2: public class NewShowMessageViewService
   3:    : IShowMessageViewService
   4: {
   5:     // IShowMessageViewService Implementation
   6: }

The MapViewService attribute requires that you specify the type of ViewService you implementing and optionally it can take in a name, you can also configure the lifetime and the initialization mode - very much like Services. Also you get a ViewSerivceLocator static class that helps you consume ViewServices.

ViewServices

Now, ViewServices are different from plain-jo services in two ways, one, it is semantically designated for View related functionality whereas ordinary Services, like with Prism, are more back-end providers. The second difference is a more practical one, you could define a ViewService directly within a UIElement or UserControl implementation - and this can then be the located by scanning the VisualTree. If you look at the ViewServiceLifetime enumeration, we have a DiscoveredInstance option which works by looking for the first instance of the ViewService in the VisualTree. Another, similar option is the SelfRegisteredInstance, wherein a UIElement or UserControl declares that it's a ViewService but will will self-register it's instance through the ViewServiceLocator when it is realized in the VisualTree.

In some ways if you look at Child Windows or MessageBox or File Dialogs they are like non-integrated visuals - they are not in the VisualTree per se, whereas if you have a status bar within the main UI  that can be called an integrated-visual. So the Discovered and Self-Registering instances option is to support these kind of integrated visuals, whose life-time you do not control directly, but yet they need to be addressable directly from some Service or ViewModel.

Consider, if we have a background-running "Stocks Watch Service" which finds-some abnormalities with your preferred stock, and it want to notify you - what does it do? Well, you could give it a ViewService contract, by which it can notify the user. This idea can be used further to componentized your visuals and avail them for without creating UI dependencies, so for example you could create a Bookmarks Panel ViewService, or Logged In/Logged Out controlling ViewService.

 Intergrated-Visual

I am not sure if this is very clear, but I will provide some samples showing how this can help to expose and consume visual components in a non-visual manner.

Channel Observers

Earlier I had shown an in-built IObserver<T> implementation, which really makes it easy to listen to any channel without having to implement the IObserver<T> interface; however in some cases you might want a dedicated listener - for example, a logging observer. In these cases you can implement the IObserver<T> interface onto a class and we can register and avail it though the RL. For that, we could do something like:

   1: [MapChannelObserver(typeof(ApplicationStateInfo), 
   2:     InitializationMode=InitializationMode.WhenAvaliable,
   3:     Lifetime=InstanceLifetime.Singleton)]
   4: public class ApplicationStateObserver : IObserver<ApplicationStateInfo>
   5: {
   6:     // IObserver<ApplicationStateInfo> Implementation
   7: }

Here we are mapping the ApplicationStateObserver class as an observer for the AppicationStateInfo Channel, we have set it to be realized as a singleton instance as soon as it is registered into the RL. Also when mapping you have the option to have it listen on a particular thread, see the ThredOption enumeration. Further, you can rely on the RL to instantiate the observer very early in the application lifetime, even before the RootVisual is created.  ChannelObservers.cs

And like before, we also have a static ChannelObserverLocator, using which you can locate your registered observers - though I am not sure how useful it is. Also, the IObserver<T> interface has three methods, the OnNext method is used to receive the channel payload, however the OnComplete is never called because a channel remains open for the lifetime of the application and I see no point executing the OnCompleted when the application is about existing. Lastly, the OnError method of the interface is also effectively not called because a Channel which implements the IObservable doesn't have the context of the publisher to generate an error - though I am mulling over the idea that any publisher can also publish an error. However, for now, just keep in mind that the workings of the channel-based messaging might change as my think evolves - and if you have any input on this, do share.

Locating Resources

One of the things with Resource Locator and it's preferred mechanism of using attributes to map resources, is that an assembly is the working currency - and indeed you could load an assembly and feed it to the AssemblyMapper static class to have any and all resources mapped. To aid this scenario, there is a RemoteResourceLoader class which helps you point to any url and load either a single dll or a xap file - in the later case it reads the xap's manifest and maps all included dlls. Here's how you can use it:

   1: // to load a dll
   2: var _loader1 = new RemoteResourceLoader();
   3: _loader1.AssemblyLoadComplete += Loader1_AssemblyLoadComplete;
   4: _loader1.LoadAssembly(new Uri("DynamicallyLoaded.dll", UriKind.Relative));
   5:  
   6: // to load a xap
   7: var _loader2 = new RemoteResourceLoader();
   8: _loader2.PackageLoadComplete += Loader2_PackageLoadComplete;
   9: _loader2.LoadPackage(new Uri("DynamicallyLoaded.xap", UriKind.Relative));

It really is very simple, and in the Assembly/Package LoadCompleted event you don't need to do anything to map the assemblies that is done for you once they are loaded, but if it was an error you will need to respond to it appropriately. Also the RemoteResourceLoader class has two static methods to check if any Uri is or has been used to load either a xap or dll.

In the attribute based mapping examples you have seen above, you have to tack the attribute on the mapped target - for example the MapModule attribute has to be tacked onto the IModule implementing type - however, this might not be possible sometimes or it may not gel with your preferences. So with toolkit there is another solution to this, a rather clean one, which allows you to "define", as oppose to "map", your resources. Have a look:

 AssemblyLevelDefines 

Here I created an empty cs fil, and added these assembly-level attributes - for all functional purposes, these attributes are the equivalent of the MapXX attributes described earlier. It works just as before, however when using the define version you need to specify the mapping target - for example with the DefineModule attribute you you have to specify the implementing type in addition to the name of the Module. Beyond the mater of personal tastes, the main benefit here is that rather than having mappings sprinkled all over the project, they located are in this one single location whilst still being strongly-typed. Also I hope the "Define" prefix as opposed to "Map" makes the intent clear here.

Quite obviously, the Resource Locator doesn't start by itself - you have to make it start and the recommended way to do that is to instantiate an nRouteApplicationService class into the Application's ApplicationLifetimeObjects collection.This can be simply done in your app.xaml file like this:

   1: <!-- declare the xml namespace -->
   2: xmlns:nRoute="clr-namespace:nRoute.ApplicationServices;assembly=nRoute.Toolkit"
   3:     
   4: <!-- and add it your application's LifetimeObjects collection -->
   5: <Application.ApplicationLifetimeObjects>
   6:     <nRoute:nRouteApplicationService />
   7: </Application.ApplicationLifetimeObjects>
 
This also happens to be the recommended way of creating "extension services" in Silverlight 3, plus it also helps to plug-into IApplicationService and IApplicationLifetimeAware related functionality. I've found this is easy to forget, but it is critical, so when there is a problem make sure your not tripping this.
 
Lastly, just as I have used the Resource Locator to created specific sets of locators you can do the same for custom locators - and it really is quite easy, just answer like six questions and you are in. I'm going to defer how to do to custom locators to a separate post, for which I have an example that shows how to dynamically collate "Search Providers" in a Silverlight app.
 
Break;
 
Because this post is already way-long, I'll have a part 2 which describes some of the other new features and what else is in store in the full-edition of nRoute. Also, please consider this as a pre-beta release, and I'll have a more polished release coming along with the full nRoute drop in a couple of weeks.
 
Download the toolkit from Codeplex.
 
Update: Part II is available here