One of the challenges with modern application development is loosely-coupled communication between various independent components within an application; by and large it is not a technical problem, but one of having a common denominator and ensuring that parties to the communication don't entangle each other with dependencies. To this challenge in nRoute we have a messaging framework that decouples application-wide communication using a mediator, against which you can both publish and subscribe without creating direct dependencies. It works much like other mediators such as Prism's Event Aggregator and MVVM Light Toolkit's Messenger, however here the core concept is based around the observer pattern.

Rx's Observer Pattern

As just mentioned nRoute's messaging broker is based on the observer pattern, or more specifically on the Rx-framework's interpretation of the observer pattern vis-a-vie their IObserver<T> and IObservable<T> interfaces. Within our use context, you can think of an Observable as being a publisher and the Observer being a consumer. When the consumer wants to consume, it subscribes to the publisher (via the Subscribe method) and thereon the publisher can do three specific things - push a series of values (of an agreed type T, via the OnNext method), indicate that it is done (via the OnCompleted method) or if an error were to occur relay that (using the OnError method), which also stops the process. Further, when we subscribe we get an invoke-able token (IDisposable type) which the consumer can use to opt-out/unsubscribe from the publisher's output.

ObservingProcess

The other notable thing about the observer setup is that the communication is all one-way, this allows it to multiplex a single published message to more than one subscriber. Now in our broker implementation, we augment the observable with the capability to be able take in a payload and send it to all registered subscribers.

Observable Channels

nRoute's messaging framework implementation uses a "channel" metaphor to describe its observable broker (IObservable<T>) implementation; and each channel is uniquely defined by the type of is payload (ie. type T in IObservable<T>) it carries, and against each channel you can both publish a payload and subscribe for one or more payloads. Code-wise, these channels are nothing more than generic singleton classes that implement the IObservable<T> interface along with a publish mechanism, which as I eluded pushes the payload to all the subscribed IObserver<T> type consumers.

ObservableChannels

As seen above, each channel is represented by the Channel<T> class, which implements IObservable<T> and inherits from the Channel base class, plus the Manager property gives access to the only instance of the singleton Channel<T> class. Further, as class definition shows a Channel<T> class allows for three things, publish a message of type T, publish asynchronously a message of type T, or subscribe to the channel which yields an IDisposable. The Channel base class gives you convenient access to the same three functions, however in both generic and non-generic ways. Note, you do not have to create any channel object yourself and the payload type of T must be a reference type i.e. a class object.

Publishing to any channel couldn't be any simpler, below we look at six ways to publish a log message of type LogInfo both synchronously and asynchronously:

   1: void PublishLog(LogInfo log)
   2: {
   3:     // using the Channel<T> singleton class
   4:     Channel<LogInfo>.Manager.Publish(log);
   5:     Channel<LogInfo>.Manager.PublishAsync(log);
   6:  
   7:     // using the Channel class generic methods (note the generic type is inferred)
   8:     Channel.Publish(log);
   9:     Channel.PublishAsync(log);
  10:  
  11:     // using the Channel class's weakly-typed methods
  12:     Channel.Publish(typeof(LogInfo), log);
  13:     Channel.PublishAsync(typeof(LogInfo), log);
  14: }

The code above should be self-explanatory, with the main take-away being that communication is done via channels, which themselves are defined by the type of the payload they carry. One other notable is that using an observable channel you cannot currently publish an exception (receivable via the OnError method), or indicate the channel is completed (receivable via the OnCompleted method) as a channel remains open through the application's lifespan.

Disposable Subscribers

Given the IObservable<T> channels the subscribers need to be of IObserver<T> type, and build-into nRoute for ease of use sake is an IObserver<T> implementing ChannelObserver<T> class. ChannelObserversThe ChannelObserver<T> basically helps maintain subscription for a channel of type T, and accordingly it has an IsSubscribed property, along with Subscribe and Unsubscribe methods. Also the channel observer class implements IDisposable, so when you are through with it you can just call the Dispose method on it and it will unsubscribe from the channel if required. Additionally the ChannelObserver<T> class also surfaces some additional options like the subscription thread option, or if you would like to have a strongly-referenced subscription (by default all subscriptions are weakly-referenced) and also allows you to optionally provision a delegate-based filter. Below is a simple use snippet, note that you have to explicitly call the Subscribe method to start observing a channel.

   1: // create the observer
   2: var _observer = new ChannelObserver<LogInfo>((l) => ProcessLog(l));
   3:  
   4: // subscribe on the UI Thread
   5: _observer.Subscribe(ThreadOption.UIThread);
   6:  
   7: // and unsubscribe
   8: _observer.Unsubscribe();

I hope the code speaks for itself, as we basically create the channel observer by providing a lambda to handle any incoming log info, and subscribe and unsubscribe as need be. Note, you can subscribe and unsubscribe multiple times using the same observer, as long as you have not disposed the observer. Also, understand that the ChannelObserver<T> class is just a candy-implementation of IObservable<T> which for convenience-sake manages the IDisposable token internally, however you can alternatively furnish any custom implementation of IObserver<T>, so for example:

   1: // subscribe to channel
   2: var _unsubscribeToken = Channel<LogInfo>.Manager.Subscribe((l) => ProcessLog(l));
   3:  
   4: // and to unsubscribe
   5: _unsubscribeToken.Dispose();

Here we are using the Subscribe extension method in nRoute to subscribe by passing in lambda handler, which yields a disposable token that can be used to unsubscribe from the channel. Now if you wanted to subscribe with say threading options, you just need to pass in the observer explicitly as shown below

   1: // create the observer
   2: var _observer = new RelayObserver<LogInfo>((l) => ProcessLog(l), null, null);
   3:  
   4: // subscribe
   5: var _token = Channel<LogInfo>.Manager.Subscribe(_observer, ThreadOption.UIThread);
   6:  
   7: // and to unsubscribe
   8: _token.Dispose();

RelayObserver<T> is a generic implementation of IObserver<T> in nRoute that takes in three delegates for handling a payload, an exception and a notification of completion. And a complementary RelayObservable<T> implementation of IObservable<T> also exists in nRoute, which helps manage one or more IObserver<T> subscribers.

Dedicated Subscribers

In addition to the disposable subscribers, you can also create dedicated subscribers that automatically subscribe and work without any direct user interaction (kind of like services) - and this is sometimes useful when you want to create dedicated sinks for a channel. Lets look at a simple logging example:

   1: [MapChannelObserver(typeof(LogInfo), "IsolatedLogger",
   2:     InitializationMode=InitializationMode.WhenAvaliable,
   3:     Lifetime=InstanceLifetime.Singleton)]
   4: public class IsolatedLoggerSink : IObserver<LogInfo>
   5: {
   6:  
   7: #region IObserver<LogInfo> Members
   8:  
   9:     public void OnCompleted() { .. }
  10:  
  11:     public void OnError(Exception exception) { .. }
  12:  
  13:     public void OnNext(LogInfo value) { .. }
  14:  
  15: #endregion
  16:  
  17: }

So above, just like any subscriber to the LogInfo type channel the IsolatedLoggerSink class implements IObserver<LogInfo>, and additionally we just decorate it with the MapChannelObserver attribute. The mapping attribute is based on the Resource Locator Framework, and it automatically registers an instance of the class as a subscriber to the channel, and also helps manage the lifetime and initialization work - in the case above, we've set the initialization to be done as soon as the resource is available and the lifetime is set to be singleton.

MapChannelObserver

Now normally once you have decorated the class with the MapChannelObserver attribute you don't have to deal with the subscription issue, however incases where you want manual control you can use the ChannelObserverLocator static class shown above - with it you can resolve any registered instance and explicitly consume it.

Threads, Async and Weak-Reference Issues

One of the features of nRoute's messaging framework is that it allows you to publish either on the publisher's working thread or asynchronously on a background thread, and on the subscribers end you can either consume on the publisher's thread, or on a background thread, or on the main UI thread (see the ThreadOption enum type). By default all subscribers use the publisher's thread, and in most cases this works fine but you have to careful (by manually specifying the TheadOption) in cases where the subscriber updates or effects UI controls as it can lead to cross-threading exceptions.  Also when you are consuming or publishing asynchronously there is a non-trivial provisioning overhead associated with sending and receiving the payload asynchronously to each subscriber - so use it selectively, preferably with coarse-grained operations. 

ChannelsThreading

One of the other important notables is that by default internal references to all the subscribers are weakly-referenced, which ensures that if the subscriber falls out of scope/use its subscription is automatically removed on the next publishing cycle. Now, for most cases this has a negligible effect on performance, however in some cases for performance reasons or otherwise you can choose to have a non weakly-reference held, in which case you must explicitly unsubscribe else the subscriber's reference will be indefinitely held by the channel potentially creating memory leaks. In any case, the best practice is to always unsubscribe from a channel when done.

Future Enhancements

In the next drop of nRoute, I'm looking to put in place two main enhancements - first to allow explicit publishing of exceptions, so just as we can publish a payload in a channel we will be able to publish an exception through the same channel. This gels with our normal understanding than any operation can have two possible outcomes, one as defined by the operation's contract and the other being an exception passed through the call-stack. And so in the same vein, in our decoupled pub/sub type of communication we should be able to specifically "raise" (i.e. send) an error explicitly to all the channel's subscribers. The second improvement I seek is to allow "private channels" that can be uniquely indentified and consumed using a shared key, and unlike the public channels, private channels will be temporal so their owners can close them as required. Private channels will functionally be similar to public channels, except they will have to be addressed using their shared key.

Owing to the ongoing development of the Rx-framework, nRoute currently does not have a binary dependency on the Rx-framework, although we have their equivalent IObservable<T> and IObserver<T> definitions present. However, as the Rx-framework stabilizes future iterations of nRoute will take a direct dependency on it, which quite beneficially will bring into play all the operators and observer constructs from Rx.

Summary

So in this post I've covered the ins and out of the nRoute's messaging framework, with the basic outline being it can help decouple your inter-component communication by playing an intermediary role. Now, to press the point further in my next post I'll put an example how in a MVVM setup such mediated communications can play an important role to keep things sane.

Posted by Rishi on 12-Feb-10 2:51 AM, 37 Comments

Categories: nRoute, Silverlight

Well, as every grandma knows today is the fable iTablet/iSlate/iPad unveiling day and in its spirit I thought I do a little unveiling myself. Over the last couple of months in my spare time I've been developing a Silverlight "application runtime", somewhat like Cloud Light, that is designed around a touch-oriented and tablet-style use. Below are some screenshots from my work, which unfortunately is not quite completed yet and obviously draws a lot of inspiration from a certain touch device.

Screenshot 1

Screenshot 2  Screenshot 3

Some earlier development screenshots.

Screenshot 4
Screenshot 5

Screenshot 6

Now in terms of UX there is a lot more to the above than what meets the eye, especially in terms of an out-and-out touch experience. Pictures can't speak, but from my experience developing this runtime there are two fundamental challenges - one windows management, and two application's design. Because I practically started from scratch, windows management has been my primary focus till now - and I can tell you this, getting the subtleties and usability right is almost a "fine art" deliverable. I don't think I have mastered it but I do think I have a starting point, however from my vantage-point I get the feeling of being caught between the richness of a desktop and the simplicity of an enlarged phone experience. Also, I seriously think to really nail the touch experience we need some breakthrough UX metaphors, something on the lines of what cover-flow brought. I have been thinking hard about it for sometime, and I have some ideas but they are still that just, ideas - let's see what iTablet/iSlate/iPad brings forth in this regard.

And I suppose the bigger of the two problem is what you can broadly term "application's design", and by that I mean how do you best visually structure/expose an application's content. iPhone in this regards was a breakthrough, it gave us a general outline of how to visually structure an application - now, arguably the iPhone'ish way could transpose to a bigger device but I have little physical/hands-on experience to conclusively argue that. Only recently have I have been trying to think about applications in such a form/factor, well, you can try some of my experiments in Cloud Light to see how it might or might-not work in terms of UX.

Cloud Light's Applications

Lastly, this is no revelation but I am pretty sure transposing a normal mouse+keyboard application directly in a touch-environment will fail in terms of usability. Add to that the lesson iPhone Apps taught us in terms of the value of designing the experience to both a hardware's limitations and feature-set, makes me think that specialized apps are the way to go. And in this space Apple is quite smart; as the rumors suggest, Apple is actively courting content specifically for the hardware at hand - and that is a winning strategy in my book as it locks in the content with the infrastructure they sell. And if Microsoft's strategy is to combat Apple with Window 7 on an Hp Slate device, I think they will loose badly yet again.

As for my project, I will keep churning it and take it as far as Silverlight can go. And despite how it might appear, my aim is not to mimic Apple but to expand my UX horizons and develop a supporting framework for both in-browser and out-of-browser applications. Let's see how it goes, for now its over to you Mr. Jobs.

Posted by Rishi on 26-Jan-10 2:54 PM, 42 Comments

Categories: UX

Cloud Light as you know is a small Silverlight-based runtime that hosts, manages and runs cloud-based applications - and with this post we'll look at how you can either create or port existing Silverlight application to run on Cloud Light. Technically there is not much of a difference between a normal Silverlight application and one that runs in Cloud Light, the main divergence is around around how we "declare" and "define" an application. In Cloud Light all application packages (xap files) are first downloaded then probed for any "declared" applications, once found the corresponding application "definitions" are used initialize the application as required. This business of "declaring" and "defining" applications in Cloud Light is materialized via two interfaces, which is what we'll look into this post by porting the iPhone'ish Sudoku Application (from my previous post) to run in Cloud Light.

Cloud Light SudokuSudoku running in Cloud Light

Declare and Define

So the two interfaces to declare and define a Cloud Light application are IAppMeta and IApp - implementation wise, they are really quite simple, have a look:

IAppIAppMeta

IAppMeta implementation is like a declaration of an application - the Cloud Light runtime looks for IAppMeta implementations, which it then initializes and holds onto. These IAppMeta instances, provides two things, one meta-data info like Title, ShortTitle, and IconPath which is used in the UI (like in the ApplicationBar etc), and second it helps with instances of the application (see the CreateAppInstance method).

In similar vein to the Application class in Silverlight, IApp implementations are Cloud Light definition of an application. And again just like the Application class, it helps with the main visual of application (i.e. RootVisual) - note, in this case it has to be a FrameworkElement derivative. Further, the IApp interface also features call-in methods that are used to notify the application as to when it's starting or closing within Cloud Light (i.e. the AppStarting and AppClosing methods). And somewhat unconventionally, an IApp implementation is also delegated with the  task of showing/hiding the application itself (via the AppShow and AppHide methods) - this sort-of also helps when you want to customize the show/hide animation and when there are Child Windows involved.

Also its worth mentioning that owing to the 10KB limit for designing Cloud Light the application API here is quite minimalistic, for example there is no cancellable mechanism when shutting down an application. Further, application/runtime interaction is also limited, it's not quite feature-rich as you expect with a desktop sort-of an environment.

I (Sudoku) App

Now, given a Cloud Light application's requirements, we'll take the Sudoku application's source-code and in a step-by-step manner port it to Cloud Light (note you can download the source-code for the ported application, it's attached below):

  • Sudoku IconTo start with, we need to add reference to Orktane.AppModel.dll assembly, it contains both the IAppMeta and IApp interfaces. You can download it from the bottom of this post
  • Next, since we are not going to use App.xaml anymore we can just delete it
  • To represent the application in Cloud Light we need to have an icon for it - for this port I've created the one shown on the right. The minimum size required is 64x64 pixels, but you can have something larger as it would just scale down. Note the icon must be in PNG format, as that is the only image format that supports alpha transparency in Silverlight. Obviously, we need to add the icon image to the project, I've added it to a "Resources" folder
  • Now, to define our application we need to add an IApp implementation, for this port I've created one called SudokuApp - and within it we basically serve an instance of the MainPage,xaml as the RootVisual (just like the App.xaml) and when asked to show-hide the application we toggle the Visibility of our RootVisual
  • Next we add an IAppMeta implementation, for this port it's the SudokuAppMeta type - and within its implementation we provide a Title, Short Title, and an assembly-qualified Icon Image path (of the image we embedded), and when asked to create application instance we serve our IApp implementation (i.e. the SudokuApp type)
  • Now, there is one last step, and this is only applicable if you are using nRoute Toolkit (the Sudoku application does). So normally to use nRoute you need to bootstrap it when the Silverlight application starts, but in this case we can't as we don't control the host - to remedy this, I've created an nRoute Toolkit adapted which resides in nRoute.Toolkit.CloudLightAdapter.dll assembly (you can also download it from below), and it allows you to lazily initialize nRoute. However, with the adapter you are also required to individually "map" all the assemblies that make use of nRoute in your application. For example have a look at the SudokuAppMeta class's constructor:
   1: public class SudokuAppMeta : IAppMeta
   2: {
   3:     public SudokuAppMeta()
   4:     {
   5:         nRouteAdapter.Initialize();
   6:         nRouteAdapter.MapAssembly(typeof(SudokuAppMeta).Assembly);
   7:     }   
   8:     // IAppMeta implementation
   9: }

And that's it, we are done porting. Now in some cases depending on your application there might be some aesthetic changes you need/want to make, like for the Sudoku application I've removed the background and put the content in a ViewBox to allow scaling, however I've not added support for dragging the application. 

Installing and Uninstall Apps

Lastly, to install the application you need to use the Console Application, and issue a command like "installapp -url:http://www.orktane.com/Labs/CloudLight/Orktane.Samples.Sudoku.xap" - obviously, substitute the Url with one for your application, but do also remember that the Silverlight's cross-domain communications rules apply. Also if you've got an interesting Cloud Light application, please share it with me and I can put it on the Application-Store listing for everyone to use.

InstallSudoku
And to uninstall an application you can just Ctrl+Shift+Click on the application icon, alternatively you can also use an "uninstallapp" Console based command which takes in a Url just like "installapp" command - so to uninstall the Sudoku application you'll write "uninstallapp -url:http://www.orktane.com/Labs/CloudLight/Orktane.Samples.Sudoku.xap" and then refresh/restart Cloud Light.

Summary

So just to recap, to create/port an application for Cloud Light you need a Xap packaged application with IAppMeta and IApp implementations within it, along with an icon. IAppMeta is like a declaration of application, and IApp is the application definition similar to the Application Class in Silverlight.

Download IApp and IAppMeta assembly (Orktane.AppModel.dll),
Download nRoute Toolkit Adapter (nRoute.Toolkit.CloudLightAdapter.dll),
and Download the source-code for the ported Sudoku Application.

Posted by Rishi on 25-Jan-10 11:43 PM, 26 Comments

Categories: Silverlight, Code, Silverlight

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.

For the Mix10K smart coding challenge, I've create an application runtime that hosts, manages and runs cloud-based applications. The runtime is called Cloud Light, and per the rules of the Mix10K challenge the code and visuals weighs-in less than 10KB. The runtime environment also features an online application store from which you can download and install applications.

Cloud Light ScreenshotView the Cloud Light in the Mix 10K gallery and please vote for it.

Runtime Overview

  • Provides basic window management capabilities like opening, closing, activating, minimizing and restoring of windows
  • Allows you to install applications directly from the web
  • Installed applications information is persistent, with the applications themselves downloaded when the runtime starts
  • Allows you to uninstall applications with a single click
  • You can also install Cloud Light as a Silverlight Out-of-Browser Application (right click and choose "Install Cloud Light.." from the context menu)

Title Bar Overview

The Title Bar shows the active application's title and also show the current date-time. Additionally, it features four buttons on the top-right corner that enable full-screen toggling, showing/hiding of the application store, minimizing of the active application and closing of the active application.TopBar

Applications Store Overview

The online Application Store lists all currently available application in the Cloud. To install any application just click on the entry title, and the application is downloaded and installed - once installed, it should appear in the Application Bar. Going further, more applications will be available through the store.

InstallableApplications

Application Bar Overview

The Application Bar hosts all the currently installed applications, each application getting an icon for itself. The icon also with a highlight represents a running application, and each application can only have one instance running at a go. A single click to an application icon starts the application, if already running it activates it, if previously activated it minimizes it, and if minimized it maximizes and activates it - really simple, right. Also if an application is open, Shift+Clicking the icon closes it and by Ctrl+Shift+Clicking on the icon you can uninstall the application.

AppBar

Extensibility

Apart from the limited applications selection available in the Application Store, you can also create your own applications and install them using the Console application. In a separate post I will detail how you can create your own custom applications and install them.

InstallAppCommandLine

Another simple point of customization is setting the wallpapers, again through the console - so something like "setwallpaper -url:http://adsoftheworld.net/download/windows7/winwall7057_23large.jpg" will change the background into:

CloudLight3

And in addition to the built-in Commands, you can also create custom Console-based Script Commands, and have them automatically register with and be availed through the Console Application (see Silverlight Console).

Summary

So for 10KB worth of c# code and xaml, I think we have a surprising functional runtime that is both extensible and light thanks to Silverlight. It in some-ways can be seen as a prototype for a managed Cloud OS that relies on the Cloud but provides applications in the form we know them today. And in terms of the design it speaks to the simplicity and discoverability that iPhone brought, something that I think needs to be embraced in desktop-applications' designs.

View the Cloud Light in the Mix 10K gallery here
and please vote for it if you like it.

Acknowledgements
Default Grass Wallpaper by Radoslaw Rokita [vathanx@live.com]
Application Icons by Judge

Posted by Rishi on 13-Jan-10 7:38 PM, 39 Comments

Categories: Code, Silverlight, Technology

One of the problems with MVVM designs is the inability of the ViewModel to singularly effect change(s) within the View; yes, you can use data-changes through data-binding as a crude-bludgeon, but I'd rather have the right tools for the right job. And that is where Reverse ICommands come in, they allow you to execute an ICommand in your ViewModel and have it trigger a set of specified action(s) in the View - the reverse taxonomy speaks to the fact that reverse ICommands targets your View rather than the ViewModel.

AvatarView the sample application here and the source code is also available at Codeplex.

Design: Extends ICommand

In working terms reverse commands are ICommands that acknowledge when they execute - the acknowledgement gives us the ability to respond to them from within the View. Implementation wise, see the IReverseCommand interface, we only add a CommandExecuted event to the ICommand definition.

IReverseCommand

The other part to reverse commands is the ReverseCommandTrigger behavior, to which we can bind our reverse command and associate one or more Trigger Actions to invoke when the associated command is executed. For example, in the Silverlight Console Project the Console definition has a "Beep" method to which we have to make a beeping sound (obviously) - however, the beeping sound playing control lies in our View and we have to trigger it from our ViewModel. So using reverse commands, first in our ViewModel we declare the reverse command property, initialize it to do nothing in our ViewModel (though you can have it do something else), and execute it when asked to beep (the OnBeep method), have a look:

   1: // we define our reverse command as a property in our ViewModel
   2: public IReverseCommand BeepReverseCommand { get; private set; }
   3:  
   4: // and we set it up like this in our ViewModel
   5: BeepReverseCommand = new ActionCommand(() => { });
   6:  
   7: // we handle Beep call request in our ViewModel and Execute the reverse command
   8: protected override void OnBeep() {
   9:     BeepReverseCommand.Execute();
  10: }

Then in our View, the XAML features the Media Element control and a reverse command Trigger which plays the media:

   1: <!-- We define the sound playing Media Element -->
   2: <MediaElement x:Name="beepAudioMedia"
   3:     Source="/Resources/beep.wma" Volume="1" AutoPlay="False"/>
   4:  
   5: <!-- And we set up Reverse Command Trigger to play the media -->
   6: <nTriggers:ReverseCommandTrigger ReverseCommandBinding="{Binding BeepReverseCommand}">
   7:     <Behaviors:PlayMediaElementAction TargetName="beepAudioMedia"/>
   8: </nTriggers:ReverseCommandTrigger>

As you can see, the workflow of reverse commands is very similar to regular ICommands, except we reverse the receiver/sender roles - the ViewModel here explicitly triggers the Command by calling execute, and the View hooks up Actions to go with the execution of the Command. Also note, all the ICommand implementations in nRoute are reversible because they all implement IReverseCommand - so you can use them as regular and/or reversed commands.

Usage: An Example

The attached sample application is really very simple, it basically has three screens and we control the flow and interaction between them from our ViewModel using ICommands and IReverseCommands. The three screens are realized as Visual States on the View and, as shown below, the Home Screen helps get a user's response to a question, the Trailer Screen shows a movie trailer and the Message Screen self-descriptively shows a message.

 SampleAppViewViewModel

Within our ViewModel, the Home command navigates to the Home Screen, the PlayPause command toggles the pause-state of the trailer, the Response command gets the user's response from the Home Screen. The reverse commands help navigate between the screens by changing the Visual State of the View, and the play/pause reverse commands do as they suggest. The idea here is to show how from within the ViewModel we can, without direct dependencies, control the View - like when we navigate away from the Trailer Screen we pause the movie and when we enter into the Trailer Screen we resume the movie all from the ViewModel. Even the playing state of the trailer is kept within the ViewModel, similarly when we get the initial question's response the ViewModel decides which screen to navigate to, and if appropriate which message to show. All this builds on the separation of concerns principle, and though the functionality here is petty, the application of ICommands and IReverseCommands helps us manage the View-ViewModel interaction in both directions.

Summary: ICommands Reversed

ReverseCommandsModel

Per the principles of MVVM, in SL, we have two primary ways of communication between the View and the ViewModel - one, data-changes signifiers that rely on data-binding, and two, ICommands based invocation of actions from the View. Data-changes as a mechanism for inter-communication works for some cases, but in other cases it is too implicit and imprecise, and this is where ICommands weigh in - they are good for explicit, loosely-coupled, and strongly-typed invoking of actions. However ICommands are one-way creatures designed to be invoked from the View, and handled within the ViewModel.

On the other end, invoking of actions from the ViewModel-to-View is the functional gap that IReverseCommands fulfill, and just like ICommands they are explicit, precise and strongly-typed. Further, as with ICommands you also get ICommands-associated functionality like can-execute checks, enabling-disabling of ICommands, and explicitly defining of dependencies like in nRoute. Now, technically there might be many ways to achieve what reverse commands do but for me the fact that here we have a loosely-coupled setup which makes use of the binding infrastructure in SL and extends one the primary communication mechanism to work in reverse is a handsomely meriting solution.

You can view the Sample App here,
you can download the Sample App source-code here,
and read about the rich support for ICommands in nRoute here.

Posted by Rishi on 07-Jan-10 5:13 AM, 45 Comments

Categories: nRoute, Code

Following up on Part I which described the workings of the Resource Locator Framework (RLF), in this post we will create a search application that uses the RLF to collate search results from various RSS-feed providers. The RFL will be used to earmark and resolve (at runtime) all the various providers, and results from which will be displayed in a tabular format using a MVVM type solution. Additionally, we'll make use of Rx-framework like Observables to asynchronously gather and compose search results.

ResourceLocatorSampleSmall  View the sample application here and the source code is also available at Codeplex.

Getting The Search Providers Results

In our sample application the provides are essentially search-engines that output results in RSS-feed format, and within our application they are represented by an ISearchProvider interface (shown below). The search results are materialized into the SearchResult type, which corresponds to an RSS-feed item and has Title, Description, Dated and Url fields. Further, for searching a provider takes the search keywords, and returns an IObservable - using which we can have the results asynchronously pushed to us.

SearchProviders

The IObservable/IObserver pairing is also very simple, just to recap for those unfamiliar - you can think of the Observable as the publisher and Observer as the consumer. When the consumer wants to consume, it subscribes to the publisher and the publisher can do three specific things - push a series of values (of an agreed type i.e. type T, via the OnNext method), indicate that it is done (via the OnCompleted method) or if an error were to occur relay that (using the OnError method, which also stops the process). Further, when we subscribe we get an invoke-able token (IDisposable type) which the consumer can (prior to completion) use to opt-out/unsubscribe from the publisher's output.

ObservingProcess 
Now in our case, the ISearchProvider is the publisher, which when asked (using search keywords) publishes a series of search results to which we subscribe. And in our sample we have realized the publishing-consuming using nRoute's build-in IObservable<T> and IObserver<T> implementations called RelayObservable<T> and RelayObserver<T> classes. Below is the outline of ISearchProvider's Search method's implementation which pushes the WebClient's response to the RelayObserver<T>'s  subscribers.

   1: var _observable = new RelayObservable<SearchResult>();
   2: ...
   3: _webClient.DownloadStringCompleted += (s, e) => 
   4: { 
   5:     if (e.Error != null)                      // incase of an error
   6:         _observable.OnError(e.Error);
   7:     else if (e.Cancelled)                     // if cancelled we indicate completed
   8:        _observable.OnCompleted();            
   9:     else {                                    // else, we parse and push the results
  10:         ParseAndPushResults(e.Results, _observable.OnNext); 
  11:         _observable.OnCompleted();            // we also indicate we are done
  12:     }
  13: }
  14: ...
  15: return _observable;                           // return the observable
 
On the other end of the stick, when we want to consume the output of the publisher above we have to subscribe - and for that we can either use a RelayObserver<T> or equally use the Subscribe extension method on any IObservable<T>. So below we are subscribing to the ISearchProvider's Observable and thereon we handle the three possible return cases. Also note the cancellation token (IDisposable) variable which we keep around incase we want to cancel. 
 
   1: var _cancellationToken = _searchProvider.Search(SearchText).Subscribe<SearchResult>(
   2:             (r) => _results.Add(r),                 // on result
   3:             (e) => ShowError(e),                    // on error
   4:             () => _isLoading = false);              // on completed
 
And that's it - we have a bona fide asynchronous communication archetype to handle search results in our ViewModel. The rest of the job just involves monkey code to marshal the results to the UI. Also note, because Silverlight can't directly access web-based RSS-feeds (unless the sources opt-in), we have got local ASP.NET proxies to go with the providers.

Getting The Search Providers Themselves

Given we know how to get the search results, our next step is get the providers themselves - and for that we'll create a specific mapping which locates ISearchProvider resources/providers. With the RLF, my general practice to create explicit mappings in a three step process - first create a meta-data class (if needed), create the IResourceLocator, and third create the mapping attributes. We'll cover these steps point-by-point:

Step 1. Create the Metadata Class 

The metadata is many-times optional but in this case we want to get a Title for the search provider and an Icon (path) to go with that. Plus, for ease of use we also store the name of the provider and the implementation type in the meta-class itself.

   1: public class SearchProviderMeta
   2: {
   3:     public SearchProviderMeta(Type providerType, string name, 
   4:         string title, string iconPath) { ... }
   5:  
   6:     public Type ProviderType { get; private set; }
   7:  
   8:     public string Name { get; private set; }
   9:  
  10:     public string Title { get; private set; }
  11:  
  12:     public string IconPath { get; private set; }
  13: }

I think that was painlessly-simple, but the idea is you should be able to use the meta in a strongly-typed fashion.

Step 2. Create the Resource Locator

As you know a resource locator is just an implementation of IResourceLocator interface, and here we have a very straightforward implementation for the search providers.

SearchProviderLocator

Our search provider's IResourceLocator implementation (DefaultSearchProviderLocator class) shown above is quite simple, it returns an instance of the meta-class we created earlier, it also provides the name of the resource, and by initializing the provider-type it can return instances of the provider. Here actually the implementation of IResourceLocator is numbingly-simple but in other cases the Resource Locator can do all kinds of fuzzy things - it's an abstraction that allows each type of resource or even each individual resource to have its own realization strategy. To give you an example of the fuzziness, the default View Services locator in nRoute can look into the Visual Tree and provide you an instance from there or if applicable a resource can opt to register/unregister an instance of itself as it sees fit (see this post for more info).

Step 3. Create the Resource Mapping

The third and final step is to create an attribute that earmarks the resource as being a search provider, for this we have to derive from the MapResourceBase attribute.

MapSearchProviderAttribute

Above our MapSearchProvider attribute in its constructor takes in the name, title and icon path information, using which it creates the meta-class from Step 1. Next, from the base class we override the GetResourceType method which tells the RLF as to which type of resource we are mapping - the answer of course is ISearchProvider type here. Note, the targetType parameter tells us onto which type this attribute is applied on - which in this case has to be our provider type and we duly check for that. We also override the GetResourceLocator to which we return our DefaultSearchProviderLocator from Step 2 - and this then resides in the Resource catalog for ISearchProvider type. I think it is fairly simple, despite the explicit steps involved - however. if you wanted something more ready-to-eat in that case you can use the MapResource attribute or MapService attribute and forge custom mapping.

Earmarking and Consuming The Providers

We've now got the requisite resource mapping and locating functionality in place, and we can just tack the MapSearchProvider attribute and be off to business, so for example:

   1: [MapSearchProvider("BingProvider", "Bing Search", 
   2:         "/nRoute.Samples.SearchProviders;Component/BingLogo.jpg")]
   3: public class BingProvider : ISearchProvider 
   4: {
   5:     ...
   6: }

Now to individually retrieve the BingProvider instance or its locator you can use the following code, note "BingProvider" is the resource identifier name:

   1: // Gets the resource
   2: ResourceLocator.GetResource<ISearchProvider>("BingProvider");
   3: // Gets the resource locator
   4: ResourceLocator.GetResourceLocator<ISearchProvider>("BingProvider");

However, for use in our ViewModel we are interested in getting all the ISearchProvider types registered - not just one. For that we can access the resource catalog (note, the RLF creates individual catalogs per resource type), and we can also listen to any changes as the catalog implements INotifyCollectionChanged. The Resource<T> is a singleton class that holds the catalog, and the ResourceLocator static class helps with resolving, checking for individual resources or their representative locators.

ResourceCataloging

Using the two classes above we get hold of all the locators, and then rig up columns per-provider to show the results - we make use of the metadata held by the locator to display the icon and title of each provider. The locator also acts like a factory for ISearchProvider instances (per search), which we use to get the search results.

Dynamically Getting More Search Providers

The point of mapping using the RLF is that all the resources are discovered and cataloged at runtime, however the fun doesn't have to stop there. RLF also supports dynamically downloading and mapping all earmarked resources within a DLL or XAP file. To demonstrate that with our sample app, we have a two providers housed in an external DLL which on-demand downloaded and mapped - and because the ViewModel is listening changes to the catalog it is immediately reflected in the UI (try the "+ Provider" button). So to download and automatically map resources we use the RemoteResourceLocator class, have a look:

   1: var _remoteResourceUri = new Uri("nRoute.Samples.SearchProvidersEx.dll", UriKind.Relative);
   2: var _resourceLoader = new RemoteResourceLoader();
   3: _resourceLoader.LoadResource(_remoteResourceUri);
 
Alternatively, you can download assemblies/xap-packages yourself and map each assembly (which is the unit of mapping, as it were) using the AssemblyMapper static class. Note, when we map we not only map the Search Providers but all kinds of earmarked resources like Services, Modules, ViewModels, ViewServices etc.

Summary

The point of this sample application was to show how you can at runtime discover and resolve resources using the RLF. Further, by creating custom resource mapping/locators, we were able to precisely materialize resources along with the metadata associated with each individual resource. The process of creating custom mappings involved creating a meta-class, followed by a resource locator (which owns the materialization strategy), and lastly a mapping attribute which brings together the two. We also have the ability to dynamically load remote resources using the build-in loaders, and any earmarked resources therein are automatically registered.

You can view the Sample App here.
and you can download the Sample App source-code here.

Note, for the sample project be sure to build the nRoute.Samples.SearchProvidersEx before running the project (it sends the DLL to the Web Project) and set the Web Project as your startup project.

Posted by Rishi on 04-Jan-10 10:01 AM, 9 Comments

Categories: nRoute, Code, Silverlight

As the name Resource Locator Framework (RLF) suggests the idea is to locate resources and functionally it's like an IoC type registry. However, it is different from a traditional IoC containers in that it allows each type of resource to put in place its own resource materialization strategy, and two it is designed to be customizable and open-ended as opposed to being internalized and closed-looped. RLF forms the basis of many open-ended features in nRoute like Services, Modules, ViewServices, ViewModels etc - so it's quite extensively used and with this post we'll have an in-depth look at its workings. Additionally, we'll follow this up with a Part II that features an how-to create and use your own custom resources, complete with the source-code.

Resourcing

Like with every IoC registry, the first step is to catalog the resources - with RLF rather than creating a single master catalog, we create individual catalog for each type of resource. As shown in the class diagram below, a resource of type T is represented by a Resource<T> singleton class, which provides a static instance via the Catalog property. The idea with the per type catalog, is to minimize contention and give each and every type of resource maximum flexibility and control.
 ResourceLocators

Within a catalog each resource is represented by an IResourceLocator instance, along with a string-based unique identifier. An IResourceLocator, as seen above, identifies the resource's unique name (ResourceName property, which is also used as the identifier), stores meta-data associated with it (ResourceMeta property), and most importantly can provide an instance of the resource (GetResourceInstance method). Generally speaking, an IResourceLocator is kind of like an individual factory for an individual resource.

With regards to the RLF workings, IResourceLocator is the key abstraction by which each type of resource (or if you require even each individual resource) can provide its own materialization strategy - because when the RLF is asked for a resource it delegates to the IResourceLocator. And within the IResourceLocator you can customize the realization of a resource, so for example with Services in nRotue its locator provides lifetime management, whereas with ViewServices its locator can go through the Visual Tree and look for a resource's visual instance, or with ViewModel's locator it can inject the ViewModel in the View - that's the flexibility that sets the RLF apart from other locators/IoC containers. Also, one can use the IResourceLocator to lazily initialize resources, as using the provided API you can either request for the resource instance or it's representative IResourceLocator instance. Resource<T> catalog, in addition to storing a string-keyed dictionary of IResourceLocator, also implements INotifyPropertyChanged to which you can subscribe for notifications when the catalog changes. It also implements an IEnumerable<string> which enumerates (actually provides a snapshot of) the resource keys currently cataloged. The catalog is thread-safe, which is why the related API also provides a TryGetResource<T> and a IsResourceRegistered<T> checker methods. Also, the Default property in Resource<T>represents the concept of a default resource, which you can retrieve without providing a resource key. Also you can earmark any resource as default, and by convention if one has not been specified then the first registered resource is the considered the default instance; plus if there is no registered resource then the Default property returns a null value.

ResourceLocatorClass

The ResourceLocator static class helps you retrieve and check for any given resource, and it also features non-generic versions of all the resource-querying functions shown above. One other point to remember about resource locators in nRoute is that within a catalog, for any individual resource or entire resource-types, you can put in your custom IResourceLocator implementation it's not locked to any predefined types.

Mapping

Given the catalogs, the next task is to enlist resources into the catalogs - for that nRoute's preferred method is to use attributes to earmark or map resources. There is an assembly-based mapping component in nRoute (described ahead), using which we catalog all resources earmarked by any MapResourceBase derived attribute. The MapResourceBase based attributes are specifically picked up for mapping, and as shown below they yield IResourceLocator instances which are then cataloged.

MappingResources

Specifically, with the MapResourceBase attribute we ask for four things - one, give us the type of resource represented by the attribute (GetResourceType method), two can we initialize the locator immediately (via the CanInitialize method, if not we put it in a pending queue and try it recursively), three is it the default resource (IsDefaultResource property), and lastly help us with an IResourceLocator instance (GetResourceLocator method). Once we have the IResourceLocator instance and resource type, we register it with the specified resource type's catalog (Resource<T>.Catalog).

MapResources

As show above, in nRoute we have various derived mapping attributes for thing like Services, Modules, View-ViewModels etc. By having more specific mapping attributes, we also capture meta-data information so for example with the MapViewService attribute we also gather the lifetime and initialization settings, and that is encapsulated into a ViewServiceMeta class which can be accessed via the IResourceLocator's ResourceMeta property. Having the metadata available within the IResourceLocator, also enables the resource locators to effect the materialization of resources.

Further, just like the many MapResourceBase derived attributes shown above, you can also create your own custom mapping attributes for any resource type. In Part II, we'll go through a step-by-step process of creating a custom mapping attribute. Additionally, as a point of extensibility you can choose to extend, replace or ignore the available mapping-attributes in nRoute and have your custom mapping attributes in play - and this should work with all existing infrastructure without change.

Cataloging

In order to catalog the mapped/earmarked resources we have an AssemblyMapper component, which when given an assembly informs (via an Observable Channel) to all interested components that an assembly is available for mapping - the interested parties can then query for specific attributes against the assembly and act upon them as they please. This is how the MapResourceBase derived attributes are mapped as soon as any assembly is passed-to the AssemblyMapper. Further, the AssemblyMapper keeps a listing of assemblies it has mapped, this way if you choose to selectively check and map resources. Also note normally you don't need to be concerned by the AssemblyMapper, as you will normally just deal with MapResourceBase based mappings.

AssemblyMapperLoader

In addition to the AssemblyMapper we also have a RemoteResourceLoader component that can download and map any DLL or XAP packaged resource - this allows you to resolve and avail remote resources at runtime. Further, like the AssemblyMapper it also keeps track of the remote resources it has loaded or is loading. Note that when a remote resource is downloaded by the RemoteResourceLoader it is automatically subjected to mapping by the AssemblyMapper.

MEF'ed in the Future

For those who know Managed Extensibility Framework (MEF) the similarities with RLF are pretty apparent, especially as MEF targets the same sweet-spot of extensible/open-ended use. However, this is incidental as RLF was made independent of MEF and indeed predates MEF's presence in Silverlight. Nonetheless, for SL4 release I am looking into an update path whereby we can carry forward most of the functionality of what is available in nRoute today, but having swapped the underpinnings to MEF. There is a lot that MEF can add in terms of features, like implicit composition, automatic re-composition and resolving of hierarchal dependencies. However, RLF and MEF don't quite functionally reconcile, specifically because RLF's capability of realizing each resource or resource-type in a custom-to-self manner.

Apart from MEF, it is possible to enhance Resource Locators to play nice with any type of IoC containers - so anything resolved by the locators will go through your specified IoC container. However, this will be one-way traffic as you wouldn't be able to resolve RLF registered resources via your IoC container (circular-dependency issues).

Summary

To sum it up I'll just recap point-wise the basics of RLF:

  • For every resource type, an individual catalog is automatically created (Resource<T>.Catalog)
  • Within a catalog, for each resource we register a representative resource locators (IResourceLocator)
  • IResourceLocator instances capture resource name, resource meta-data and also realize resource instances
  • Using MapResourceBase derived attributes, we can capture all earmarked resource locators using the built-in mapping component
  • You can create your custom MapResourceBase derived mapping attributes
  • And using the RemoteResourceLoader class you can download, resolve and avail remote resources at runtime

And in Part II, we'll put the above into practice - which I think will better enlighten the value of RLF, so do check back.

Update: Part II is up.

Posted by Rishi on 04-Jan-10 4:21 AM, 22 Comments

Categories: Silverlight, nRoute

Consoles are a unique animal in this day and age of multi-touch user interfaces - they stand productively tall despite all the enhancements in user-interaction over the years. And as Silverlight grows into a more rounded and generalized platform, there is a case for Command Line Interface tooling - so here is an attempt at a relatively simple implementation of a Silverlight based Console that includes a Console Window Control and a matching set of extensible Commands Framework that allows for executable commands (called script-actions) vocabulary.

SilverlightConsole3

View the demo application here.
Note, the demo application only supports a limited set of commands, type "help" for listing of available commands, for some examples try "setwallpaper -url:http://adsoftheworld.net/download/windows7/winwall7057_17large.jpg"  or "countdown 00:00:10" or "beep" to make a beeping sound.

Console Window Control (Orktane.Console.dll)

In terms of user-interaction the console is a bit of peculiar control, it isn't exposed as a directly usable control but rather is accessible only through a singular static Console class. For the purposes of the Silverlight Console, I've encapsulated the Console class functionality into an IConsole interface, which in turn is visualized and exposed through a Console Window user-control. The idea of an IConsole interface, just like in Windows, is to enable visually-independent consumption of the console functionality, and at the same time also allow having multiple instances of consoles within a single Silverlight application. Now, Silverlight does have a System.Console class but it is cocooned in the SecurityCritical attribute making it useless outside its internal uses.

ConsoleModel

The IConsole functionality above is much simplified compared to the Windows counterpart, we don't deal with screen-buffers, cursors, or position related settings. Also, though internally we do have In and Out streams they are not exposed, and rather than width-by-height buffer size we deal with a string length output buffer. The simplification is in part because the text-rendering functionality in Silverlight is basically all internal, so we are limited to Textbox or Textblock controls for text-based interaction. However with the RichTextArea control in Silverlight 4, it should enable a much richer experience (see Pose Console in WPF). Further, a solution based on column-by-row screen buffer would have been very resource-heavy for Silverlight, so instead we've used a string-based buffer - which you can set by using the SetOutBuffer method.

One other critical difference between the Windows counterpart is that Silverlight doesn't allow blocking calls, so returning values through ReadLine and ReadKey functionality isn't possible, hence ReadKey and ReadLine calls above return void. In place of returning values, both the ReadKey and ReadLine functionality take in an Action delegate which is used to yield the user input - the ReadKey takes in an Action of ConsoleKeyInfo (shown above) delegate and ReadLine takes an Action of String delegate. Now, whenever you set the ReadKey or the ReadLine delegate it switches the input mode between the two, and whenever you set the delegate it would keep sending the input to the same delegate for each input until changed.

Another issue with using the text-controls in Silverlight is that we have to manually disable input, for which you have to use the DisableInput property on the IConsole interface. This takes away the input Textbox, and if you choose you can display alternate text using the DisableInputText property - so for example below we have disabled the input whilst we are downloading in the background and erstwhile we are showing the progress info using the DisableInputText. Note the red indicator on the left of the text, which visually is a separate area (Textbox actually) from the console output area (also a disabled Textbox).

DisabledInputText 

Now to visually realize the IConsole we have the ConsoleWindow user-control that you can directly use, it has a Console property of type IConsole which allows for procedural use of the console. Internally, we have the console functionality separated from the visuals, a View-ViewModel kind of separation as shown below. You can potentially change the visuals or logic by changing either, or you can create your console-visuals using the ConsoleBase as a starting point.

ConsoleWindowModel

Note, since we are not using a cell based display, in the Console Window we use a fixed-width font, with the width pegged for 80 columns. This aspect is hard-coded, but it is consistent to the default Windows console.

Script-Actions Framework (Orktane.ScriptActions.dll)

By itself the ConsoleWindow implementation is dumb as a stick, it has no concept of executable commands, it just handles the input and output business. And so we have this Script Actions framework (or Commands framework), which basically extends the IConsole to allows execution of custom script-actions, where script-actions are executable commands (note, we don't use the word command because of the ICommand-related conation). In simpler terms you can think of script-actions as extensible vocabulary which is executable in a console. A

ScriptActionsModel

As seen above, we have two types of script-actions, one which can execute by itself (IScriptAction) and the other derivative (IConsoleScriptAction) that requires a console instance to execute. The Execute method takes in an Arguments-type parameter, which is a dictionary of parsed switches and command-line arguments. The command line parser is by Richard Lopes, with some additional word done by Jake Ginnivan. However, for a future release I am looking to port the Command Line Parser Library (by Jakub MalĂ˝), which allows for strongly-typed arguments and better structuring of script-actions.

Now, if your ScriptAction class implements the IConsoleScriptAction then the Console instance is passed in and the Initialize method is called prior to execution. And again because we don't have blocking calls in Silverlight you have to manually indicate as to when the script-action has finished its execution, for that you use the ExecutionCompleted event to flag the completion. The close method is called when you've finished, or earlier if the executing environment is itself closing. Further, you can also handle a cancel request (called using the Ctrl+C pairing) by listening to the IConsole's CancelKeyPress event. On the other hand, the IScriptAction based script-action are executed without any indication in the Console (note that is different from when a request command is not found), and once the execution has been called the console returns to an empty console prompt.

On of the features in nRoute, is a MEF like composition component called the Resource Locator - it basically allows you to earmark specific resources and have them cataloged. So based on that, we have a MapScriptAction attribute that flags an implementation of IScriptAction for use in a console; as an example consider:

   1: [MapScriptAction("GC", "GC Memory", 
   2:     ShortDescription = "Forces an immediate garbage collection.",
   3:     Lifetime = InstanceLifetime.PerInstance, UnListed = true)]
   4: public class GCScriptAction : IScriptAction
   5: {
   6:     public void Execute(Arguments args) { 
   7:         GC.Collect();
   8:     }
   9: }

Above, we an IScriptAction implementation that forces an immediate garbage collection on execution, and we have earmarked it with a MapScriptAction attribute. The attribute takes in couple of settings like a unique and callable command-name, a title for the script-action and other options like short-description, a lifetime setting indicating how to handle instantiation, and lastly an option as to if the command is not listed in the help listings. Using the attributes based composition of script-actions makes it painless to have commands availed at runtime or dynamically resourced, for more information please see Introduction to nRoute.Toolkit posts.

Lastly, once we have the script-actions we need to enable their use from within an IConsole instance, for that we have a behavior called ScriptActionConsoleBehavior that attaches to any IConsoleHost implementing (also must be a FrameworkElement) instance. The xaml for that looks like:

   1: <console:ConsoleWindow x:Name="consoleWindow">
   2:     <i:Interaction.Behaviors>
   3:         <scriptActions:ScriptActionConsoleBehavior/>
   4:     </i:Interaction.Behaviors>
   5: </console:ConsoleWindow>

As seen above, the separation of concerns in terms of the console's working-logic and the visuals allows you to plug-in your own custom logic or visual implementation. So for example you could have MEF composed script-actions, or bring Powershell scripts into Silverlight and hook them into a ConsoleWindow. Remember the pairing is necessary, as by itself the Console Window control is dumb-as-a-stick.

Summary

So what we have here is a two-piece solution, one an IConsole based visual control, and two a complimentary console-executable vocabulary of script-actions. And though the solution is not true to the Windows version, it within the limitations of Silverlight a very usable tool. Finally, if you have suggestions or ideas to enhance what's here please do let me know.

Source-code and binaries are available on Codeplex
and you can view the Console Demo Application here.

Posted by Rishi on 29-Dec-09 6:15 AM, 18 Comments

Today I saw a cool article on Code Project on how to do multi-binding in Silverlight using attached properties and a specialized type of value-converter. I though we could do the same thing with Value Converter Relays in nRoute.Toolkit without requiring additional classes/converters. So in this post we'll cover how to easily address multi-binding scenarios (as when you have multiple inputs, but one required output) using value-converter relays in Silverlight.

The Use-Case

The use-case is very simple, we have this form (shown below) that takes in a Person object with three properties namely Surname, First Name and Age - and as you enter them into the form, it updates the title of form with the full name derived from what you have entered. Nothing fancy, but the idea is that we should be able to consume two or more fields through one binding (as in multi-bind).

MultiBindingForm

Value-Converter Relays

Just to reiterate, a relay is like a facade to an actual implementation that can be specified elsewhere such as your code-behind or your ViewModel. In this case, we'll use a code-behind implementation as the requirement is essentially to turn two inputs into a formatted string, and that really is a view-level detail so it should stay there. All the same, if you wanted to use a ViewModel driven implementation then you can use a behaviour named  "BridgeValueConverterBehavior", which as you can guess "bridges" the relay with an implementation from your ViewModel (using bindings).

How-To Steps: Declare, Define and Use

Step 1, we declare the value-converter relay in our UserControl's resources collection, just like any static resource:

   1: <nComponents:ValueConverterRelay x:Key="TitleConverter"/>

Step 2, once we have the relay declared we define it in our code-behind. Here we are using an extension method available in nRoute.Components namespace that allows us to define the value-converter functionality using a lambda statement. Note, it is important to set this before we set the data-context, obviously because it is needed once the data-context is available.

   1: this.SetRelayConverter<Person, string>("TitleConverter", 
   2:     (p) => string.Format("{0}, {1}", p.Surname, p.Forename));

Step 3, to use the formatted string, we just bind to the data-context (which is the Person object) whilst using our value-converter relay:

   1: <TextBlock Text="{Binding Converter={StaticResource TitleConverter}, Mode=OneWay}"/>

And that's it we are done, we have our fake multi-binding in SL using value-converters. However, note there is one niggle, because we are directly setting the Person as our data-context, we have to manually update the data-context on the TextBlock whenever the property changes. This could be avoided by using ViewModels or INotifyPropertyChanged notifications, but since the original sample didn't I've avoided it too.

More Relays

Now that you've see the ValueConverterRelay in action, I'll just mention that we have two other types of relays in nRoute - one called Command Relay and another Value Relay. You can see a Command Relay in action in my recent ICommands related post, and the Value Relay is put to good use in my Web Xcel demo - there I've used it to "pseudo bind" to both a non-dependency property and also to another read-only dependency property. And so to sum it up, consider the use of relays for lot of sticky-stuff like pseudo multi-binding use, binding to data-templates, consuming read-only properties etc. and though it's not pretty it gets the job done.

You can download the value-converter relay project's source code,
note it requires the nRoute.Toolkit which is available on Codeplex,
and the original article on Multi-binding with source is available on Code Project.

Posted by Rishi on 11-Nov-09 2:01 PM, 12 Comments

Categories: nRoute, Silverlight