Architecting UI plug-ins for PRISM applications

by Marcin Kaluza 19. October 2010 05:59

It often happens that a particular feature of an application is not used very often, but when you need it you would like it to be accessible easily and without hassle: think calculator in an order entry program. Surely the user can live without it and use the calculator provided with the OS, but what if he could access a simple calculator within a click or two inside the application itself? I could give you more examples like this, but they all fall under the same umbrella of add-ons or plug-ins. Things you surely could live without but having them handy makes the work so much easier.

As it happens I have recently built similar functionality into a PRISM application and the rest of the post describes how to do it in a (hopefully) more less generic fashion.

The plan

I envisioned a plug-in to be  visual “gadget” which the user could access through a window hosting all the plug-ins available in an application in a fashion similar to Visual Studio’s Toolbox. The important thing here is the fact that each plug-in would need to provide it’s own UI: at the end of the day the application cannot up-front provide UI for plug-ins which have not yet been written. Given these requirement I came up with the following plan:

  1. The application’s main window would provide screen estate for displaying all the plug-ins in form of a PRISM’s view region
  2. The plug-ins view region would be filled by a PluginsView containing an ItemsControl which would wrap each individual plug-in into expander
  3. Underlying View Model would simply expose a collection of IPlugin elements which could be bound to the view’s item control

The Plugin

Each of the plug-ins is required to implement IPlugin interface which first of all allows it to be discovered by the PluginHost and secondly forces the plug-in to expose a “View” of sorts which can be displayed to the user. As we’re in the PRISM world here, I would expect the View to be also injected into plug-in, but it is not strictly speaking required. Each plug-in also needs to provide user readable name which will be displayed in the UI.

/// <summary>
/// Common interface for all plugins
/// </summary>
public interface IPlugin
{
    /// <summary>
    /// Gets the name of the plugin.
    /// </summary>
    /// <value>The name.</value>
    string Name { get;  }

    /// <summary>
    /// Gets the UI representation of the plugin.
    /// </summary>
    /// <value>The view.</value>
    object View { get; }
}

All the plug-ins need to be registered with the IoC container and this, in case of PRISM applications is usually done during module initialization. One thing which has to be kept in mind in such case is to give unique “key” (name) to each plug-in during registration as there will be more than one implementation of IPlugin available:

public class PluginsModule : IModule
{
    private readonly IUnityContainer _unityContainer;

    public PluginsModule(IUnityContainer unityContainer)
    {
        _unityContainer = unityContainer;
    }

    public void Initialize()
    {
        _unityContainer.RegisterType<ICalculatorPluginView, CalculatorPluginView>();
        _unityContainer.RegisterType<INewsPluginView, NewsPluginView>();

        _unityContainer.RegisterType<IPlugin, CalculatorPlugin>("Calculator");
        _unityContainer.RegisterType<IPlugin, NewsPlugin>("News");
    }
}

 

The PluginHost

The role of the plug-in host is to simply consume all the implementations of IPlugin available in the application and expose them in a single collection. The simplest way to achieve that is to get them injected into the host by an IoC container. I was toying with the idea of using MEF for this purpose but at the end of the day settled for simplicity  and decided that Unity which is anyway used by PRISM will do the job as well. The following code fragment shows the inner workings of the host. As you can see the constructor gets all the implementations of IPlugin as an array which may seem a bit awkward, but this is what Unity expects out of the box. Having said that it is possible to inject an IEnumerable<IPlugin> which would seem more natural but it requires extra parameter when it comes to registering of the PluginHost with the container.

/// <summary>
/// Hosts all the plugins in the application
/// </summary>
public class PluginHost
{
    private readonly IPluginHostView _view;
    private readonly IPlugin[] _plugins;

    /// <summary>
    /// Initializes a new instance of the <see cref="PluginHost"/> class.
    /// </summary>
    /// <param name="view">The view.</param>
    /// <param name="plugins">The plugins.</param>
    public PluginHost(IPluginHostView view, IPlugin[] plugins)
    {
        _view = view;
        _plugins = plugins;
        _view.DataContext = this;
    }

    public IPluginHostView View
    {
        get { return _view; }
    }

    /// <summary>
    /// Gets the list of all the plugins available.
    /// </summary>
    /// <value>The plugins.</value>
    public IEnumerable<IPlugin> Plugins
    {
        get
        {
            return _plugins;
        }
    }
}

The PluginHostView

The purpose of the view is to show all the available plug-ins, each with his own specific UI. There is nothing magical about it apart from the fact that the item control uses item template which in turn uses plugin-provided UI as a content for the expander. I settled for the expander as I wanted to allow the user to collapse or expand them as and when required.

<Grid>
    <ItemsControl ItemsSource="{Binding Plugins}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Expander Margin="5,5,5,0"
                          Header="{Binding Name}"
                          Content="{Binding View}" />
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Grid>

 

Implementing a plug-in

Now given all the groundwork implementing a plug-in is a doodle. The code is fundamentally no different to any other view/view-model combo as the sample below illustrates:

public class NewsPlugin : IPlugin
{
    private readonly INewsPluginView _view;

    public NewsPlugin(INewsPluginView view)
    {
        _view = view;
        _view.DataContext = this;
    }

    /// <summary>
    /// Gets the name of the plugin.
    /// </summary>
    /// <value>The name.</value>
    public string Name
    {
        get { return "Latest News"; }
    }

    /// <summary>
    /// Gets the UI representation of the plugin.
    /// </summary>
    /// <value>The view.</value>
    public object View
    {
        get { return _view;  }
    }

    /// <summary>
    /// Gets the news.
    /// </summary>
    /// <value>The news.</value>
    public IEnumerable<string> News
    {
        get
        {
            return new[]
                       {
                           "Frogs Invade Pratt's Bottom...",
                           "Developer's bonuses set to triple in 2012",
                           "Read more..."
                       };
        }
    }
}

 

Wrapping it all up

The attached sample application illustrates how all the parts interact together. The full source code can be found here.

image

Tags: ,
Categories: C# | CAL | WPF | PRISM

Using Delegate Commands with WPF Views (UPDATED)

by dariuscollins 27. November 2009 00:51

UPDATED: Scroll to end of post.

Please note:  the examples in this post depend on an implementation of the Presentation Model described in a previous post. 

DelegateCommand<T> is a class that comes with the Composite Application Library (CAL or PRISM), which is the latest incarnation of the Composite application block (CAB).  I have included it in my solution for an application that is based on CAB and have also created a second class DelegateCommand which extends DelegateCommand<T> simply by overriding the constructors and specifying T as object.  This second class allows you to use delegate commands when you don't need to use a command parameter.  I will not go into detail here regarding the implementation of the DelegateCommand<T> class (you can look at the code for yourself – see the attached zip file at the bottom of the post), but will stick to describing how it is used.

Delegate commands can be used instead of WPF Routed commands.  The advantage of a delegate command is that they can be bound to directly on the PresentationModel without the need for a pass through method in the View's code behind.  The command parameters are also type safe, whereas with Routed Commands, parameters are always of type object, and so need to be cast before use.

 Delegate commands are exposed on the Presentation Model as a property.  For example:

OrdersPresentationModel: AddCommand Property

public DelegateCommand<Order> AddCommand { get; set; }

Here we are declaring a DelegateCommand<T>. If the command is to be passed a command parameter, the type of the parameter should be included as the template for the command.  If not, use DelegateCommand instead (no template).

I have chosen to use automatic properties for my commands.  I therefore need to initialise the commands from the OnViewReady method.  (Alternatively, I could have included the initialisation in the getter via a null check). I do this by calling the InitialiseCommands method:

OrdersPresentationModel: InitialiseCommands Method

private void InitialiseCommands()

{

    ...

    AddCommand = new DelegateCommand<Order>(OnAdd, CanAdd);

    ...

}

 My OnAdd() and CanAdd() methods are also declared in the presentation model as follows:

OrdersPresentationModel: OnAdd and CanAdd Methods

private static bool CanAdd(Order order)

{

    return order != null;

}

private void OnAdd(Order order)

{

    if (order == null) return;

    Customer.Orders.AddUnique(Order);

}

So how do we use the command?  As simple as any other property binding:  

OrdersView

<Button Margin="5,0,5,0"

        Height="20"

        Width="70"

        Command="{Binding AddCommand}"

        CommandParameter="{Binding ElementName=ordersComboBox, Path=SelectedItem}">

 

 That's it.  Very simple.  Notice that the OnAdd and CanAdd methods are private.  How can we test them then?  Better than just testing the methods, we can actually call the command from the test.  

OrdersPresentationModelTest

public void AddCommand_AddOrder_OrderAddedToCustomersOrdersCollection()

{

    ....

   _model.AddCommand.Execute(new Order(1));

    ....

    model.AddCommand.CanExecute(new Order(1));

    ....

} 

UPDATE:  Thanks to a tip off from a colleague of mine at EMC, Marcin Kaluza, regarding Josh Smith’s excellent post Allowing CommandManager to query your ICommand objects, I have updated the DelegateCommand class by removing the RaiseCanExecuteChanged and the OnCanExecuteChanged methods and instead implementing add and remove accessors on the CanExecuteChanged event that hook the event up to the CommandManager.RequerySuggested event.  As a result, we no longer need to implement a DispatcherTimer (as suggested below) for each view to periodically poll the CanExecute methods.  I’m sure you’ll agree, this is a much neater solution and has the added bonus of removing the concern of CPU spiking, since we are no longer polling the can execute methods every half second or so, but only when the CommandManager detects conditions that might change the ability of a command to execute.  Thanks Josh!

 There is just one fly in the ointment with this approach.  The CanExecute fires only once when the view is loaded.  This seems like a flaw in the DelegateCommand, since the WPF's Routed Command regularly polls CanExecute methods.  There may now be other implementations of the delegate command that claim to have solved this problem (the Relay Command may be one of them), but I have yet to research them.  In the mean time I have implemented a DispatcherTimer that raises the RaiseCanExecuteChanged() on the delegate command every half second.  This is initialised from the OnViewReady method by calling the InitialiseCanExecuteDispatcherTimer()  method on the PresentationModel.  Ideally this should be pushed down into the DelegateCommand class, but I have yet to look into solving that particular problem.

OrdersPresentationModel: InitialiseCanExecuteDispatcherTimer Method

private void InitialiseCanExecuteDispatcherTimer()

{

    _dispatcherTimer = new DispatcherTimer { Interval = new TimeSpan(0, 0, 0, 0,500) };
    _dispatcherTimer.Tick += (sender, e) => AddCommand.RaiseCanExecuteChanged();
    _dispatcherTimer.Start();

}