Quantcast
Channel: Caliburn.Micro: Xaml Made Easy
Viewing all articles
Browse latest Browse all 1760

Updated Wiki: LoadCatalog Result

$
0
0

LoadCatalog Result

Contributed by janoveh

The following is a simple IResult implementation for using MEF's DeploymentCatalog to dynamically download and plug in xaps. In order for it to work properly, you must make sure to add the AggregateCatalog as an exported value in the container.

Implementation

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.ReflectionModel;
using System.Linq;

publicclass LoadCatalog : IResult
{
    staticreadonly Dictionary<string, DeploymentCatalog> Catalogs = new Dictionary<string, DeploymentCatalog>();
    readonlystring uri;

    [Import]
    public AggregateCatalog Catalog { get; set; }

    public LoadCatalog(string relativeUri)
    {
        uri = relativeUri;
    }

    publicvoid Execute(ActionExecutionContext context)
    {
        DeploymentCatalog catalog;

        if(Catalogs.TryGetValue(uri, out catalog))
            Completed(this, new ResultCompletionEventArgs());
        else
        {
            catalog = new DeploymentCatalog(uri);
            catalog.DownloadCompleted += (s, e) =>{
                if(e.Error == null)
                {
                    Catalogs[uri] = catalog;
                    Catalog.Catalogs.Add(catalog);
                    catalog.Parts
                        .Select(part => ReflectionModelServices.GetPartType(part).Value.Assembly)
                        .Where(assembly => !AssemblySource.Instance.Contains(assembly))
                        .Apply(x => AssemblySource.Instance.Add(x));
                }

                Completed(this, new ResultCompletionEventArgs {
                    Error = e.Error,
                    WasCancelled = false
                });
            };

            catalog.DownloadAsync();
        }
    }

    publicevent EventHandler<ResultCompletionEventArgs> Completed = delegate { };
}

Usage

public IEnumerable<IResult> LoadCatalogs()
{
    yieldreturnnew LoadCatalog("TestCatalog1.xap");
    yieldreturnnew LoadCatalog("TestCatalog2.xap");
    yieldreturnnew LoadCatalog("TestCatalog3.xap");
    yieldreturnnew LoadCatalog("TestCatalog4.xap");
}

Much thanks to codeplex user janoveh on whose work this recipe was based.

Viewing all articles
Browse latest Browse all 1760

Trending Articles