nRoute: Now, More Wholesome

Posted by Rishi on 13-Apr-10 1:36 PM - Comments (9)

I'm really excited to introduce the latest version of nRoute - this has been brewing with me for a long-time and I'm really happy about the feature-matrix that this release brings to bear. This release is a major one, for a couple of reasons - first, this release propels nRoute to three platforms, two, it takes big strides in making the underlying infrastructure asynchronous, three, it significantly updates the navigation infrastructure, and four, it brings extensible Dependency Injection (DI) into play which allows top-down composition to cascade through the application.

nRoute Overview

ApplicationFeatures

Now my intention with this post is to cover what's new and what's changed, but before that I want to just give an overview of nRoute. Basically, nRoute is a composite application framework that allows you to break and compose your application using various application-level constructs, as show in the diagram above. It is highly prescriptive in terms of its use of Navigation, IoC, DI, and other MVVM design patterns. It comes in two flavors, the full framework (nRoute.Framework.dll), and the toolkit version (nRoute.Toolkit.dll) which lacks the Routing Engine and the sub-features associated with it (shown in green above).

The Routing-Engine basically provides Url addressable content and actions - this helps you break your applications into smaller-chunks that can be brought together in a very loosely-coupled fashion - just like on the Web. The Messaging-Framework allows for loosely-coupled communication between one or more parties, without either having direct knowledge or keeping direct references between each other. Lastly, the Resource Locator Framework (RLF), which is an IoC component (and now a DI component too) allows for extensible and open-ended composition at runtime - build upon it are various features such as Modules, Services, View-Services, View-ViewModel support etc.

For more information on all of the above, check out some of my older posts, though do note that quite a bit has changed since:
Introducing nRoute: an application-flow framework for Silverlight and WPF
Introducing nRoute.Toolkit for Silverlight (Part I)
Introducing nRoute.Toolkit for Silverlight (Part II)

I'm looking into put together a single document that highlights nRoute's depth and breath, but for now these blogs posts will have to serve as scattered documentation.

Multi-Platform Support

SimpleMVVMWith this release we now have out-of-the-box support for Silverlight, Windows Phone 7 and WPF. This is a big branch-out from nRoute's Silverlight-only roots, but between the growing convergence of WPF and Silverlight and three independent WPF implementations of nRoute out in the wild, we've managed to bridge the gap. All the same, it is important to note that for the foreseeable future the center of gravity of nRoute, in terms of features and scope, will remain aligned with Silverlight despite the wider canvas afforded by WPF.

Asynchronous Routing and Navigation

First a little background, in nRoute we have two core interfaces that handle routing and navigation - the IRouteHandler interface essentially "sources" the response for an Url request (i.e. gets the content), and INavigationHandler handles the routing response (i.e. displays the content). These are like the two main cogs that make content sourcing and its visualization work, and with this release we tweaked both of them to make them work asynchronously. With respect to IRouteHandler, rather than just returning a response, we changed it to return an IObservable of the response - a seemingly small change, but it makes a fundamental difference:

IRouteHandler

Secondly, as it was, INavigationHandler separately processed the request and the response - which allowed us to be asynchronous in-between the two calls. But now with this release we've also tweaked INavigationHandler to respond to any navigation request asynchronously, by returning a yah/nah through a callback. It is also a little change, but has a profound effect:

INavigationHandler
With the new definition, we can now respond by consulting with the active View/ViewModel as to if we can proceed - and this is important as most of the can/should navigate reasons are contextual to the task at hand. In terms of the normal designer-developer workflow you don't need to deal-with the INavigationHandler or IRouteHandler directly - rather, as we'll see next, you deal with some predefined interfaces/contracts that optionally provide you control over how things like closing the current-view, navigating to a new view etc work. One common scenario where this really helps is when you want to navigate-away from a page, but before that you want to contextually consult the user about cancelling, saving changes, or continuing with the navigation - this gives your the entry point for that.

Formalizing Container-View/ViewModel Communication

One of the common problems with MVVM tuned applications is how do we communicate with the ViewModels from the outside/shell - well, the answer is simply, define a contract and use that as the basis for communicating. And with the new release we've put in place some mechanisms to make this extremely easy and extensible - I'll need to defer showcasing this to another post, as I want to explain it with an example. Making use of this technique, we've got three build in contracts that are used by various navigation controls to communicate with your View/ViewModel (which ever implements it). These contracts are refinements over what was available before, but they are much more well-strung now:

ISupport_thumb[2]ISupportNavigationState allows you to optionally participate in a container-maintained state management functionality (just as before, but the interface has changed). ISupportNavigationLifecycle (also changed, but like before) helps with lifecycle integration, by passing-in the parsed Url-based tokens along with the request's parameters, and as mentioned above it also allows you to participate in the closing of the active-view. A very simple way to exercise both the ISupportNavigationState and ISupportNavigationLifecycle interfaces is to use the new NavigationViewModel, which in addition to the two interfaces also implements INotifyPropertyChanged interface. Lastly, the ISupportNavigationFailure is used to visualize navigation error information, as we'll see ahead.

Globally Named Navigation Containers

Often you'll find that you want to trigger navigation in some container that is not directly accessible within the operating name-scope or even via the VisualTree - for such cases, we've introduced a simple mechanism to globally register a container with a string-based identifier, and then target the container for navigation using the same string identifier.

NavigationHandlerBehaviour 
To register any container globally use the NavigationHandlerBehavior and simply provide a name - as shown in the figure above. Now, internally we keep a weak-reference, and if another container registers with the same name then the last-one-in wins. Secondly, to target the globally-registered container specify the HandlerName (as shown above) on the any of the various navigation inducing behaviors (described ahead).

Application-Wide Default Container

In earlier versions to specify an application-wide default container, we had to hijack the Application class - well, no more - we specify the application's default container by just using the above mentioned NavigationHandlerBehavior and checking the IsDefaultHandler option. Also, in case of multiple opt-ins the last-one in wins, and to access the default container programmatically use the NavigationService static class. Note, when you want to use the application-wide default container you don't need to specify the navigation handler name.

Browser-Shell Integration

Browser-shell integration was earlier quite messy, now all you need to do is to drop the NavigationShellIntegrationBehaviour and you are done - clean and simple, and there are no options to fiddle around too.

NavigationShellBehaviour
This behavior makes use of the Silverlight's built-in Browser-History Manager, however it has the limitation of only being forward-only, which means you can't use it with navigation containers that allow directional navigation (like BrowsingNavigationContainer). For use with direction-aware containers I'll release an out-of-bound behavior, which will use of a different Browser-History Manager. Also, note this behavior is not available for WP7 or WPF, and when in Out Of Browser (OOB) mode it disarms itself.

Added StatefulBrowsingNavigationContainer

Unlike WPF/SL we have a flexible approach to containers (aka Frames) that display navigation results; in nRoute our approach is to offer different containers for different navigation use semantics - so some offer browser like state-management, some offer browsing history, while others just offer onwards-only navigation. Now, with this release we're adding a new navigation-container called "StatefulBrowsingNavigationContainer", it allows browser like back-forward navigation whilst allowing each page-type to share the same common state. Think about how in a Web-Browser each individual page in your navigation history keeps its own navigation state - well, with this container each page-type will have one common state whether they be in the forward or back stack or even if you just directly navigate to the page. So when you back up or go forward, the same single state will be returned - and I personally find this quite useful for desktop class application. This is actually an hybrid of StatefulNavigationContainer and BrowsingNavigationContainer.

Also as a related point, with this release we've update all the build-in container templates, they now match the Silverlight's standard way of templating content controls. Another changes is that the template now shows an overlay with an animated indicator whilst navigating (it uses a spinning indicator by Felix Corke).

Navigation Adapters

NavigationHandlers  
Implementing navigation containers in nRoute is really quite simple, all you really need is an INavigationHandler implementation - and there are two approaches to this, one is to make custom controls from the ground up, which we have (as shown in the hierarchy above) and the other approach is to tack this interface onto existing controls, which is relative easy. However, inheriting and extending controls is not exactly pleasant, and indeed in some cases it's not even viable - so as an alternative, with this release we've standardized a way to create so-called "navigation-adapters". These are essentially behaviors that implement INavigationHandler and can be drag-dropped onto any targeted control. And by the virtue of having the behavior all of nRoute's navigation infrastructure will seamlessly work around your targeted control. So for example, you want to handle navigation in a Tabs-Control, write a little behavior for it, drag-drop it, and you're done - no need for extending any control.

Now, because a lot of the functionality for adapters is common we've build in an adapter base class, obviously called NavigationAdapterBehaviorBase<T>. It only requires you to handle the displaying of content when navigated upon - and it's basically like visualizing the navigational content. Consider you could make a custom navigation adapter for a 3D panel, and each navigation adds to the 3D content. Additionally, we've also create an ItemsControl navigation adapter (numbingly called ItemsControlNavigationAdapterBehavior) that basically can append to an ItemsControl any navigated upon content. And because it's an ItemsControl, you can use this will all sorts of panels. This is a very powerful and flexible model and I'll have to showcase it separately, but the idea behind it was to allow you to create custom use-models, not just the linear navigation apps we are all used to. You can even create MDI type of application, and combine it with all benefits of a navigation-style app.

Abstracting Container Behaviors

One other new thing we've done is to abstract the common navigation-related functions such as refreshing, navigating back/forward, purging journals etc into well-understood interfaces; some of these are:

ISupportContainerThis helps, because now we can consistently target functionally-similar containers, and indeed we've build into nRoute the following behavior-actions to that take advantage of the abstracted commonalities:

NavigationBehaviours

NavigateActionSo like if you want to refresh a container, drag-drop the RefreshNavigationAction, point to the handler and you're done. Now, the most useful of these behaviors has to be the NavigateAction - which as it self-suggests induces navigation, and its use is shown in screenshot to the right. The Handler property is useful when you want to directly bind to an INavigationHandler object, but mostly you'll either just specify the HandlerName or actually not specify any handler (as we'll see ahead, why). Note, the Handler Name can either be an element name within the control name-scope, or it can be a globally-registered handler name (as we described earlier). The parameters collection allows you to pass-in a name-value collection with any navigation request, think of it as a Form/Request Collection in Web-Forms. We'll get to the SiteArea in a bit, and the Url is obviously the Url one wants to navigate too.

Now, I just wanted to point out the workflow of how we resolve the navigation-handler (this is slightly changed from before), we have a five-step approach, described below:

  1. If we have a navigation-handler directly specified/bound (Handler Property), then we use that
  2. If we have a handler-name specified, we check for an element with that name in our control name-scope; if found we use that
  3. If we have a handler-name specified, we check against the list of globally-registered handlers; if found we use that else throw an exception stating that the handler name was not found
  4. We look up in the visual-tree for an INavigationHandler, it can either be an control implementation or it can be via an attached adapter - we check for either; and if found we use that
  5. Lastly, we check if we have an application-wide container specified, if so, we use that - if not then, we return null and the handling logic would normally throw an exception stating handler not found

The interesting part is part 4, which basically says look upwards in the Visual-Tree and if you find any INavigationHandler use that - this basically allows you to default to the most immediate handler, just like in web-pages/IFrames, and it gives you the browser like use-semantic. And note, you can easily have containers-within-containers or use containers side-by-side, like in a master-detail scenarios.

Support for Error Pages

ErrorPage
One of the expectations with navigation-style apps is that when you can't get to any resource, you get a nice little exception page - well, in earlier releases that was not the out-of-the box behavior with nRoute. But with this release, we've not only added a default error page (shown above), but also allowed you to put in your custom page. Custom error pages are easy to create, all you need to do is to implement the aforementioned ISupportNavigationFailure interface - and you can set them by setting the ErrorUrl property on all built-in containers.

Also, the default error page can be reached via the Url "About:Error", and the WP7 counterpart looks a bit different as it's specifically tailored for the mobile experience - it even makes use of the active phone theme. And in cases where you don't want to show error pages at all, you can override the ShowFailedNavigationState method to handle a navigation failure in whichever manner suitable to your needs.

Introducing Controllers

One of the concepts in earlier version of nRoute was Url-addressable "Actions" - but now its got the axe, as it required that each action have a corresponding class, plus it wasn't represented in a strongly-typed manner. A replacement is in hand, have a look:

   1: [MapController("Shell/Tasks/{Action}"]
   2: public class ShellController : Controller
   3: {
   4:     public ActionResult Settings()
   5:     {
   6:         return new NavigateResult("Pages/Shell/Settings/");
   7:     }
   8:  
   9:     public void Exit()
  10:     {
  11:         Application.Current.Shutdown();
  12:     }
  13: }

If the above looks familiar, well then say hello to MVC in Silverlight - basically, we've got the full MVC style controller-action thing in nRoute. The idea is to have Url-executable actions, and Controllers provide us the necessary encapsulation required for something that is rooted in the UI. Additionally, we have the full range of extensibility points available in MVC, for example custom ActionResults, custom ActionNames, even custom ActionInvokers if you so require. And because this is build-upon the desktop-class routing engine you can even get the full MVC routing semantics, including setting custom route handlers with default values etc; or to keep your sanity just use the MapController attribute as shown above. Further, you can pass in action parameters to methods either through Url-tokens or using the parameters collection associated with the controller-action request.

Controller Behaviors

ControllerBehaviours
To execute Controller based actions we basically have the ExecuteControllerAction behavior, which can be attached to any sort of trigger. The use-semantics of executing an Controller is exactly the same as the NavigationAction (which was described earlier), and indeed they inherit from the same base-class. And the reason controller-actions optionally associate with navigation handlers, is because in some cases, they allow you to execute an action against an navigation handler.

Introducing SiteMaps

   1: <nRoute:Application.ApplicationLifetimeObjects>
   2:         <nRoute:nRouteApplicationService>
   3:             <nRoute:nRouteApplicationService.SiteMapProvider>
   4:                 <sm:XamlSiteMapProvider>
   5:  
   6:                     <sm:SiteMap>
   7:  
   8:                         <!-- AREAS -->
   9:                         <sm:SiteMap.Areas>
  10:                             <sm:SiteArea Key="ModuleA"
  11:                                  RemoteUrl="nRoute.ModuleA.xap"
  12:                                  InitializeOnLoad="false"/>
  13:                             <sm:SiteArea Key="ModuleB"
  14:                                  RemoteUrl="nRoute.ModuleB.dll">
  15:                                 <sm:SiteAreaInfo Key="ModuleA" />
  16:                             </sm:SiteArea>
  17:                         </sm:SiteMap.Areas>
  18:  
  19:                         <!- ROOT NODE -->
  20:                         <sm:SiteMap.RootNode>
  21:                             <sm:NavigationNode Title="Home Page"
  22:                                 Url="Pages/Content/HomePage/"
  23:                                 SiteArea="ModuleB">
  24:                                 <sm:NavigationNode Title="About Us"
  25:                                     Url="Pages/Content/AboutUs/" />
  26:                                 <sm:NavigationNode Title="Contact Us"
  27:                                     Url="Pages/Content/ContactUs/" />
  28:                                 <sm:ControllerActionNode Title="Exit"
  29:                                     Url="Shell/Tasks/Exit/" />
  30:                             </sm:NavigationNode>
  31:                         </sm:SiteMap.RootNode>
  32:  
  33:                     </sm:SiteMap>
  34:  
  35:                 </sm:XamlSiteMapProvider>
  36:             </nRoute:nRouteApplicationService.SiteMapProvider>
  37:         </nRoute:nRouteApplicationService>
  38:     </nRoute:Application.ApplicationLifetimeObjects>

Well, here's another nod to concepts from web-world, we've basically borrowed the concept of SiteMaps right from ASP.NET and indeed you get the same type of semantics of specifying hierarchical set of nodes. However, unlike ASP.NET, we have two specific built-in node types that directly relate to navigation and controller-actions (see NavigationNode and ControllerActionNode above). Also, this is an extensible architecture, so for example you can have ICommand based nodes or indeed custom ones based on your application executable-functionality.

SiteMapNodes

Above is a screenshot from a sample application (you can actually download it from Codeplex) that shows how you can use the SiteMap definition to integrate within your application. Alternatively, you could have menus or toolbars based on your SiteMap definition. Plus, to make life that much easier, build into nRoute are a couple of behaviors (see the diagram below) that allow you to execute any SiteMap Node. Also you can give each SiteMap Node a unique key, and use that to Navigate (see NavigateNodeAction) or execute the associated Controller-Action (see ExecuteControllerNodeAction) - this way you can abstract the Urls out.SiteMapBehaviours

SiteMaps are sourced using a "SiteMapProvider", which is basically tasked to yield a SiteMap. You specify the application's lone SiteMapProvider in nRoute's ApplicationService declaration (which is defined in App.xaml) - and so, when the app starts, nRoute tries to load the SiteMap using the specified provider. Built-into nRoute are two providers, one, a XamlSiteMapProvider which, as shown in the xaml above, allows you define the SiteMap in xaml itself. The other included provider is the XmlSiteMapProvider, it allows you to load the SiteMap definition from an external xml file. And to ensure maximum flexibility, the SiteMap infrastructure is designed to load asynchronous, so it can tolerate loading of SiteMaps dynamically/lazily. Furthermore, you can create your own custom SiteMap providers, like one perhaps using a database to dynamically assemble your application's parts at runtime.

Introducing SiteAreas

SiteAreaBehaviour Again I've borrowed the Areas terminology from  MVC, but in this case you can think of them as external resources (like xap/dll files), each SiteArea is uniquely identifiable using a key. The idea is to define all external resources in one well-understood place, so that both your code and the entire nRoute infrastructure can avail them at runtime. So for example, if you want to navigate to "Pages/Content/ContactUs" and it is in "ModuleB.dll", then by defining it as a Site Area and indicating the same in your navigation request (see right) the infrastructure will automagically load it when asked to navigate, and then navigate to your destination once the SiteArea is loaded. This way we get both easy-to-use semantics and very loosely-coupled bridges over external resources.

Now, in terms of the technical workings, when a SiteMap based external resource is requested, the navigation-engine will first check if the SiteArea (in our case) named "ModuleB" is loaded or not, if not it will download it, initialize any resources within it, and then continue with the navigation. All this takes place seamlessly, in fact if ModuleB had any dependencies (like "ModuleA" in the case above) they will be topographically resolved to the nth level. Also, the SiteMap infrastructure can also check for circular dependencies, just like Visual Studio does references.

Honestly, I don't think I could have made this any simpler, it is tightly integrated with the asynchronous nature of the routing engine and therefore works with anything build upon it, obviously like built-in navigation and controller facilities. However for other or custom uses you also have programmatic control over loading both SiteAreas and the SiteMap; and you can also specifically indicate which SiteAreas to load when the SiteMap initializes. Keep in mind, use of both SiteMaps and SiteAreas is totally optional, however, use of SiteAreas is not at all possible with WP7 because you can't load external resources by design. Lastly, note that SiteArea internally makes of RemoteResourceLoader component, which with this release has been totally revamped, and now makes use of IObservables to asynchronously load and map external resources.

Introducing Dependency Injection (DI)

nRoute already has an MEF like IoC component that is both extensible and open-ended, now, with this release it meets its significant other - an extensible DI system. The new DI systems' use can be summed-up by two attributes ResolveResource[Attribute] and ResolveConstructor[Attribute]. You put ResolveResource attributes on properties, fields and parameters; it optionally allows you to specify which named resource to use, and it also allows you to indicate as to if some resource is "nullable" in which case if not found it won't throw an exception. Further, in Silverlight you can only use it with public fields/properties, as use with non-public members is not allowed. And you use the ResolveConstructor attribute to indicate which constructor to use at runtime - its use is required unless you have a default public constructor, and in Silverlight you are obviously limited to a public constructor.

Now, like the resource "mapping" infrastructure in nRoute, the dependency "resolving" infrastructure is also totally customizable - if you want to provide your own custom resolving methodology, then inherit from the ResolveResourceBase attribute and provide your own custom implementation. Included in nRoute are two such custom resolving attributes, ResolveChannel attribute and ResolveViewModel attribute. The ResolveChannel resolves an Observable Channel, and the benefit of using it is that it bypasses the resource mapping layer and goes directly to the Channels infrastructure - plus, it allows you to specify additional contextual options. Similarly, the ResolveViewModel attribute can resolve an instance of the ViewModel for a View; note below how we appended that to the parameter of the constructor:

   1: public partial class PageA : UserControl
   2: {
   3:     [ResolveConstructor]
   4:     public PageA([ResolveViewModel(typeof(PageA)]Object viewModel)
   5:     {
   6:         InitializeComponent();         
   7:         this.DataContext = viewModel;
   8:     }
   9: }

This kind of extensibility moves beyond the traditional A is to B type of DI, as it is semantically-rich and can mesh your domain-logic seamless with the DI process - all the while keeping infrastructure concerns separate from the content. Further, note all resources created by the nRoute infrastructure like Services, Views, ViewModels, Modules etc can make use this DI system - so when defining your ViewModel you can ask it resolve services you require:

   1: [MapViewModel(typeof(PageA))]
   2: public class PageAViewModel : ViewModelBase
   3: {
   4:     private readonly IRepositoryService<Customer> repository;
   5:     private readonly Lazy<IMessageViewService> _messageViewService;
   6:  
   7:     [ResolveConstructor]
   8:     public PageAViewModel(IRepositoryService<Customer> repository, 
   9:         Lazy<IMessageViewService> messageViewService)
  10:     {
  11:         _repository = repository;
  12:         _messageViewService = messageViewService;
  13:     }
  14:     ...
  15: }

Locator Adapters for Higher-Order Dependencies

Another point of extensibility are so-called Locator Adapters, this is inspired by Common Context Adapters concepts which is all about abstracting out the IoC container specifics by using higher-order dependencies. For example, consider if you want to lazy-load a resource, normally you'll defer it's use till required, once require you check if it's null, if so then ask the IoC to load it etc - now this both quite messy and leaky, so instead why not have the DI resolve a Lazy<T> which would internally abstract away all the container and loading specifics - and you're level of involvement is limited to asking for Lazy<T> rather than a type T. Based on this simple but powerful concept, nRoute's DI can resolve the following higher-order dependencies, for any resource of type T.

  • T[]
  • Func<T>
  • Lazy<T>
  • Lazy<T, Metadata>
  • Future<T>
  • List<T>
  • ICollection<T>
  • IQueryable<T>
  • IEnumerable<T>
  • IEnumerable<Func<T>>
  • IEnumerable<Lazy<T>>
  • IEnumerable<Lazy<T, TMetadata>>
  • IChannel<T>

And if that's not enough, you can create your own custom adapters and register them with nRoute's Resource Locator Framework (RLF). Again, like the MapChannel attribute we saw earlier, you can extend the DI to your custom domain specifics, just as we do with IChannel<T> above. Another interesting adapter is the Future<T>, which when used says that we might not have this resource-type available as of now, but in some point in the future it might be - so just resolve a Future<T> resource and we will check against it if the resource is available or not (via its IsValueAvaliable property) prior to using it - using this you've abstracted away the IoC/DI system specifics.

Another problem with DI in an open-ended IoC framework like MEF and RLF is we have no idea what is a resource and what is not; MEF deals with this by rejecting the composition, nRoute deals with this by throwing an exception - simply because without a resource-type registration we don't know if type XYZ is a bonafied resource or not, and we simply can't accept anything is a resource policy, as that's an endless loop. Now to solve this conundrum, keeping in mind the open-ended nature of nRoute, we have a special MapAsKnownResource attribute (with a parallel DefineAsKnownResource attribute) which tells the RLF that this type is a known resource type, and so accept any request for it. This way we can reject any erroneous-requests, but still accept the unknowns.

   1: [MapAsKnownResource]
   2: public interface IExecuteService
   3: {
   4:     void Execute();
   5: }

So for example, with the code above even if we don't have any registered implementations of IExecuteService, we still accept it as a bonafied resource type because it is specifically earmarked as such. Note, normally you don't need to put this on every resource because you'll have an implementation available at the same time - in case you don't, use this.

Dependency Recomposition Support

Dependency recomposition is a fantastic facility, however it is something that can without due-consideration lead to all sorts of memory leaks, because in most likelihood you are tying a variable to a static "source-of-resources", whose lifetime will mostly likely exceed that of your variable. So for recomposition with RLF, I've made available three specific adapters that "by default" will not lead to memory leaks as it makes use of "smart handlers" infrastructure in nRoute. The three supported adapters for a resource of type T, are:

  • ReadOnlyObservableCollection<T>
  • ReadOnlyObservableCollection<Lazy<T>>
  • ReadOnlyObservableCollection<Lazy<T, Metadata>>

Now this is not a be-all list, as  you can extend it with your custom adapters as you require - but I think for most common uses these should suffice. Its usage is similar to any resource, and doesn't require any additional opt-ins:

   1: public class ServicesViewModel : ViewModelBase
   2: {
   3:     [ResolveResource]
   4:     public ReadOnlyObservableCollection<IExecuteService> Services { get; set; }
   5: }

As you would know, ReadOnlyObservableCollection implements INotifyCollectionChanged, which therefore can be used to notify when recomposition happens and to stop the recomposition one just needs just nullify the variable/property (note, nullify all instances of it, and also remember to remove any event-handlers attached to the collection to stop recomposition).

Observable Channels

We've made sweeping changes to the Observable Channels in nRoute -  for the better - the performance is up 4 fold, we've aligned it much more with the Observable pattern, and now we also have compatibility with Rx-framework.

IChannel
Each channel is now defined as an IChannel<T> (as can be seen above) and in Rx-speak an IChannel is a Subject which means it both an observer and observable. And being both an observer and observable means that through an IChannel you can both publish and subscribe - which is the same as before, but now you can direct do using the IObservable<T> and IObserver<T> interfaces. A new thing with this release is that you can also publish exceptions (using OnError) and this is appropriate because, as I explained before, a call to any operation in .NET has two possible outcomes an explicit result or an implicit exception, and the same two possibilities are reflected here. One important thing to note is that you CANNOT call OnCompleted on an IChannel because an observable channel is usable through-out an application's lifetime, doing so will only raise an exception.

A new thing with this release is that we have the concept of a public and private channels - each type of channel has one default public IChannel<T> associated with it, and additionally you can any number of private channels each identifiable with an unique string-based key (non-case specific). The API is very simple, below we are subscribing and publishing on a public channel and a private channel (identified with the key "Test"), have a look:

   1: // Subscribe
   2: Channel<string>.Public.Subscribe((m) => MessageBox.Show(m));
   3: Channel<string>.Private["Test"].Subscribe((m) => MessageBox.Show(m));
   4:  
   5: // Publish
   6: Channel<string>.Public.OnNext("Hello Public World!");
   7: Channel<string>.Private["Test"].OnNext("Hello Private World!");

Now above the "Subscribe" is an extension method, and you have couple of them with lots more options. Further, the OnNext method (and OnError method too) has an overload that takes in a Boolean suggesting as to if you want to publish it asynchronously. If this is not not enough you can always call in the cavalry, in form of Rx-framework, so for example:

   1: Channel<string>.Public.
   2:     Delay(TimeSpan.FromSeconds(10)).
   3:     TimeInterval(TimeSpan.FromSeconds(5)).
   4:     Select((t, m) => m.Substring(10)).
   5:     ObserveOn(DispatcherSynchronizationContext.Current).
   6:     Subscribe((m) => MessageBox.Show(m));

So above, we are delaying the listening by ten seconds, and at every five second interval we are selecting a substring of the first ten characters, and observing it on the dispatcher thread, to show the resulting string via a message-box - nonsense use, but the point is you get the full power of the Rx-framework for use with your channels. Though note Rx-framework is not required by default, but you have the option to exercise it if required (aka nRoute doesn't have a dependency on Rx, but we have binary compatibility).

Old Channel Ways Survive

Despite the new API I've show above, you can still use the old-style API to publish/subscribe against observable channels (like before) - and it has full parity to the new API. And as an extended use-case it even allows non-generic usage of channels, which can be really handy sometimes.

ChannelObserver
The Channel static class follows the "publish/subscribe" metaphor, and its usage is also quite simple:

   1: // Publishing through the Channel class
   2: Channel.Publish<string>("Hello Public World!");
   3: Channel.Publish<string>("Test", "Hello Private World!");

Now one of the big internal change to channels is that now by default all subscriptions are NOT weakly referenced - they are strongly referenced and must be manually disposed/unsubscribed. This change was required for both Rx-framework and use of lambda statements, as by their nature lambda's can't survive a weak-reference subscription (technically, they can by lifting some reference into their scope, but that's leaky design) - which meant that they would have unsubscribed as soon as you exited the method they were declared in. However, if you know what you are doing, you can still make lambdas weakly-referenced, using an overloaded subscription method. Despite this change, the ChannelObserver<T> by default still by maintains a weakly-referenced subscription, which is exactly like before - and in fact, I still highly recommend the use of ChannelObserver<T> in your Views/ViewModels as you normally wouldn't want to deal potential memory leaks if you did not unsubscribe. Remember channels (private or public) are static resources, and their lifetime spans that of the application - so when you hitch something to it, you are also potentially extending the attaches' lifetime to match that of the channels (Hello, Memory Leak).

ICommand Infrastructure Updates

Earlier we had this distinction between so-called ActionableCommands and ActionCommands, well no more - we've unified the two, and now we just have ActionCommand and ActionCommand<T>(.) Also, I've done bit a of clean-up under the hood, particularly I've abstracted the ICommand base-classes which can now be used to make stand-alone commands (I'll show a nice use-case in a separate post).

TriggerParameter Now, one of the common questions I get asked is how do we pass-in event-arguments to the ViewModel, well the simple answer is that you don't. An event-argument is a View-specific construct, it has no place in the ViewModel, obviously because separation of concerns is the entire point of View-ViewModel partition. That being said, in case where "data" from the event-argument has to passed-onto the ViewModel, we now support that via the new TriggerParameterConverter property (see right) on the ExecuteCommandAction behavior.

TriggerParameterConverter accepts an IValueConverter, which converters the Trigger's parameter for use as the Command's parameter. I hope that is not confusing, what happens is each trigger gets to pass onto its to-be-triggered action(s) a parameter, and in the case with EventTrigger (used above) it passes in the event argument from the selected event (in this case selected above that would be the SelectionChangedEventArgs type). And by specifying the converter for converting SelectionChangedEventArgs to something the ViewModel can understand and digest, we are able to bridge the View-ViewModel separation without violating the separation agreement. Moreover, this works with all sorts of triggers, and remember each trigger passes-through whatever is appropriate to its operation, so in this way we have a very flexible approach that works across the board and not just with events.

New Behaviors and Triggers

UpdateBindingExplicitly I've added three sets of new behaviors, the first of which is called UpdateBindingExplicitlyAction - it as the name suggests allows you to update a property binding explicitly. Consider the example in the screenshot to the right, it shows a TextBox to which we've attached our UpdateBindingExplicitly action. Now, what we're saying there is that whenever the TextChanged event occurs, update the binding for the property called "Text". It's as simple as that - note you can pair the update action with any sort of of trigger, and it will update any (non-read only) dependency property's binding.

The second new action is SetFocusAction (and an accompanying TargetedSetFocusAction); this action allows you to set the focus on any element by pairing it with a Trigger. In fact this is often a common newbie question, how do you set focus in a MVVM application? Well, here is one simple and designer-friendly answer.

The other two new behaviors are BoolValueDisableBehavior and NullValueDisableBehavior, they both allow you to disable or pseudo disable an element depending on a Boolean value or a Null value. This actually tackles an acute problem in Silverlight, where most of the controls don't support an IsEnabled property, and so you can use this behavior to gloss over the differences by disabling input and reducing the opacity in cases where the control is not inherently disable-able. For example, below is a Border control (in Silverlight it doesn't have an IsEnabled property), that is automatically "disabled" when there is no loaded worksheet in the backing ViewModel.

PseudoDisabled

The xaml for this looks like:

   1: <Border ... >
   2:     <i:Interaction.Behaviors>
   3:         <nBehaviors:NullValueDisableBehavior Value="{Binding Worksheet, Mode=OneWay}"/>
   4:     </i:Interaction.Behaviors>
   5: </Border>

Woo, Finally

For a 128kb/75kb (Full Framework / Toolkit Version) additive to your xap files, I think nRoute packs a punch - and with the new release it is more wholesome than ever. Definitely, we still have a long way to go, but I think the big difficult steps have been made. And the focus here forth will not be so much on features but better execution and quality, and for the immediately proceeding release Designer/Blend support will be the big go-go. And finally, finally, a lot of the new features in this release have come from user's suggestions and pain-points (thanks guys), and so I encourage anyone and everyone with feedback to chime in - there is a receiver on the other end.

You can download nRoute (all three versions) from Codeplex including the source
- Targets Silverlight 3 for Web  (Silverlight 4 version will be out once RTM tools are posted)
- Targets Silverlight 3 for Windows Phone 7
- Targets .NET 3.5 for Desktop (.NET 4 version will out with Silverlight 4 release)

Note, we have 6 dlls, 3 for nRoute.Framework and 3 for nRoute.Toolkit

nRoute Dependencies
- System.Windows.Interactivity.dll from Blend SDK
- System.Observable.dll from Rx-framework
 
View the Officer Xcel Demo App, source is also available on Codeplex
more samples to follow

PS: I want to specially thank Carlos Álvarez, he really helped me with throughout the way, especially with the WPF version - it wouldn't have been possible without his support. You must check out his WPF Chronos Framework, its designed for developing (super) MDI applications using Windows Presentation Foundation.

Comments (9) -

Nicholas Blumhardt
Nicholas Blumhardt Australia
on 13-Apr-10 10:56 PM
Wow, this is looking great!

I like the way you described CCA:

>> which is all about abstracting out the IoC container specifics by using higher-order dependencies

Very succinct!

B. Clay Shannon
B. Clay Shannon United States
on 14-Apr-10 9:30 AM
Great stuff; however, the grammar/style police just battered down your door and have slammed you up against the wall. Why? Because you wrote:

<<...for a couple of reasons - first, this release propels nRoute to three platforms, two, it takes big strides in making the underlying infrastructure asynchronous, three, it significantly updates the navigation infrastructure, and four, it>>

You say a couple reasons, then go on to list four. Also, you start off with "first," and then go to "two," etc.

The excerpt quoted above should be:

"...for several reasons: first, this release propels nRoute to three platforms; second, it takes big strides in making the underlying infrastructure asynchronous; third, it significantly updates the navigation infrastructure; and fourth, it..."

Don't let it happen again, or Big Brother and the Grammer/Style goon squad will make another unannounced and unwelcome visit!

mas
mas Spain
on 14-Apr-10 3:47 PM
Hi,

I am testing the last version of the nRoute Toolkit with WPF with the simple thing of the IReverseCommand. However, I've found out a runtime error: "'IReverseCommand' type does not have a public TypeConverter class".

Does it mean nRoute is not valid for WPF?

Rishi
Rishi
on 14-Apr-10 9:48 PM
@Mas there is no last version of nRoute.Toolkit for WPF, as we've only just started supporting WPF with the latest/current release. And I double checked, it works in WPF:

<i:Interaction.Triggers>
  <nTriggers:ReverseCommandTrigger ReverseCommand="{Binding ChangeColorReverseCommand, Mode=Default}">
    <nBehaviors:TargetedSetPropertyAction PropertyName="Background" Value="Red"/>
  </nTriggers:ReverseCommandTrigger>
</i:Interaction.Triggers>

Earlier nRoute only targeted Silverlight.
Rishi

Rishi
Rishi
on 15-Apr-10 8:15 AM
@Nicholas, Thanks, I'm looking forward to having a CCA compatible version out in the future - I think it's gonna help enormously everyone. Plus, I admire the work you are doing in AutoFac, it really helped shape my thoughts about keeping the containers out Smile


business directory
business directory United States
on 13-May-12 1:39 PM
Another exceptional post. You know, I'm very happy I found this. I'll tweet your blog so my buddies can read your writing too!

HERVE LEGER BANDAGE DRESS
HERVE LEGER BANDAGE DRESS People's Republic of China
on 14-May-12 1:23 PM
HERVE LEGER BANDAGE DRESS www.herve-legers-dress.com/...e-bandage-dress.html

chy
chy People's Republic of China
on 16-May-12 9:09 PM
http://www.cheapchristiansandals.net

Pingbacks and trackbacks (6)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading