Thursday, September 22, 2011

Extending the Personalplaner

Every application should be extensible!
That's why I added the ability to create plugins for the Personalplaner. Well actually I did it mainly just for the fun of it...

To achieve this I used MEF. MEF started as a Codeplex project but now is fully integrated in the .NET Framework in the Assembly System.ComponentModel.Composition.

With the help of MEF it is realy easy to create and use plugins resp. export and import objects.
In my case I only had to create an Interface and implement this in the plugin class and add the class attribute [Export(typeof(IPlugin))] (IPlugin is the interface I created...)

[Export(typeof(IPlugin))]
public partial class PlanAnalysisPlugin : BaseControl, IPlugin
{
    ...
}


In the class that imports the plugins, I only needed to create a CompositionContainer that creates/imports the objects and a container that will containe the imported objects.

CompositionContainer _container;

//public IEnumerable<Lazy<IPlugin, IPluginMetadata>> Plugins
/// <summary>
/// Enumeration containing all loaded pluginsEnumeration containing all loaded plugins
/// </summary>
[ImportMany]
public IEnumerable<IPlugin> Plugins
{
    get;
    set;
}

private bool Compose()
{
    if (!Directory.Exists("plugins"))
        return false;

    var catalog = new AggregateCatalog();
    catalog.Catalogs.Add(new DirectoryCatalog("plugins"));

    _container = new CompositionContainer(catalog);

    try
    {
        this._container.ComposeParts(this);
    }
    catch (Exception)
    {
        return false;
    }

    return true;
}

In my case I decided to keep the plugins in the subfolder named plugins.


If the folder is empty then the application should look like this. On the left side there are only the options for Plan and About.


If I put my plugin into the folder plugins, the application should load and insert it in between Plan and About. In this case I created a plugin that shows some reports and displays some additional inforamation to the plans.


I know that I will most probably be the only person that will ever create a plugin or an extension for the Personalplaner. But with this I can easily extend the Personalplaner with new features without having to create a new version and a setup every time.

No comments: