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, 10 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