MEF Directory Catalog that will handle outdated MEF Components
Inheritance: ComposablePartCatalog
コード例 #1
0
        /// <summary>
        /// Gets provider repository.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <returns>
        /// Provider repository.
        /// </returns>
        private CompositionContainer GetCompositionContainer(IInput input)
        {
            CompositionContainer container;

            using (var catalog = new AggregateCatalog())
            {
                var adaptersDirectory = AssemblyHelper.GetExecutingAssemblyDirectory();
                var item = new SafeDirectoryCatalog(adaptersDirectory);
                catalog.Catalogs.Add(item);

                CompositionContainer tempContainer = null;
                try
                {
                    tempContainer = new CompositionContainer(catalog);
                    var ctorAdapterParameters = new ProviderParameters {
                        Data = input.Data
                    };
                    tempContainer.ComposeExportedValue(ctorAdapterParameters);
                    tempContainer.ComposeParts(this);
                    container     = tempContainer;
                    tempContainer = null;
                }
                catch
                {
                    throw;
                }
                finally
                {
                    tempContainer?.Dispose();
                }
            }

            return(container);
        }
コード例 #2
0
ファイル: Validator.cs プロジェクト: HicServices/RDMP
        public static void RefreshExtraTypes(SafeDirectoryCatalog mef, ICheckNotifier notifier)
        {
            lock (oLockExtraTypes)
            {
                _extraTypes = null;

                List <Type> extraTypes = new List <Type>();

                //Get all the Types in the assembly that are compatible with Constraint (primary or secondary)
                extraTypes.AddRange(mef.GetAllTypes().Where(

                                        //type is
                                        type =>
                                        type != null &&
                                        //of the correct Type
                                        (typeof(IConstraint).IsAssignableFrom(type) || typeof(PredictionRule).IsAssignableFrom(type)) //Constraint or prediction
                                        &&
                                        !type.IsAbstract
                                        &&
                                        !type.IsInterface
                                        &&
                                        type.IsClass
                                        )

                                    );

                _extraTypes = extraTypes.ToArray();
            }
        }
コード例 #3
0
        public void DoWorkInShadowCopiedDomain()
        {
            try
            {
                string pluginsPath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "PlugIns");
                SafeDirectoryCatalog pluginsCatalog = new SafeDirectoryCatalog(pluginsPath);


                _container = new CompositionContainer(pluginsCatalog);
                _container.ComposeParts(this);
            }
            catch (CompositionException compositionException)
            {
                MessageBox.Show(compositionException.ToString(), "Plugin Loader", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (DirectoryNotFoundException directoryException)
            {
                MessageBox.Show(directoryException.ToString(), "Plugin Loader", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (ReflectionTypeLoadException loaderException)
            {
                if (loaderException.LoaderExceptions != null && loaderException.LoaderExceptions.Length > 0)
                {
                    MessageBox.Show(loaderException.LoaderExceptions[0].ToString(), "Plugin Loader", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    MessageBox.Show(loaderException.ToString(), "Plugin Loader", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
コード例 #4
0
        public void DllFileDuplication_Ignored()
        {
            // Setup 2 directories that will contain duplicate copies of the same dll
            var badDir1 = new DirectoryInfo(Path.Combine(TestContext.CurrentContext.TestDirectory, "Bad1"));
            var badDir2 = new DirectoryInfo(Path.Combine(TestContext.CurrentContext.TestDirectory, "Bad2"));

            if (badDir1.Exists)
            {
                badDir1.Delete(true);
            }

            badDir1.Create();

            if (badDir2.Exists)
            {
                badDir2.Delete(true);
            }

            badDir2.Create();

            var dllToCopy = new FileInfo(Path.Combine(TestContext.CurrentContext.TestDirectory, "Rdmp.Core.dll"));

            // copy the dll to both folders
            File.Copy(dllToCopy.FullName, Path.Combine(badDir1.FullName, "Rdmp.Core.dll"));
            File.Copy(dllToCopy.FullName, Path.Combine(badDir2.FullName, "Rdmp.Core.dll"));

            var tomem = new ToMemoryCheckNotifier();

            var sdc = new SafeDirectoryCatalog(tomem, badDir1.FullName, badDir2.FullName);

            Assert.AreEqual(sdc.DuplicateDllsIgnored, 1);

            badDir1.Delete(true);
            badDir2.Delete(true);
        }
コード例 #5
0
            private void ComposePlugins(HttpApplication context)
            {
                var directoryCatalog = new SafeDirectoryCatalog("bin");

                Container = new CompositionContainer(directoryCatalog);
                Container.ComposeParts(this, Responders);

                var store = context.GetWarningStore();

                foreach (var exception in directoryCatalog.Exceptions)
                {
                    store.Add(new[] { exception.GetType().Name, exception.Message });
                }

                //wireup converters into serializer
                Responders.RegisterConverters();
            }
コード例 #6
0
ファイル: WritersCache.cs プロジェクト: lanicon/iExportEngine
        /// <summary>
        /// Gets writers repository.
        /// </summary>
        /// <param name="settings">Writer cache settings.</param>
        /// <returns>
        /// Writer repository.
        /// </returns>
        private CompositionContainer GetCompositionContainer(WritersCacheSettings settings)
        {
            CompositionContainer container;

            using (var catalog = new AggregateCatalog())
            {
                foreach (var path in settings.Items)
                {
                    var item = new SafeDirectoryCatalog(path);
                    catalog.Catalogs.Add(item);
                    using (var writerWatcher = GetWriterWatcher(path))
                    {
                        var addWatcher = _watchers.All(watch => watch.Path != path);
                        if (addWatcher)
                        {
                            _watchers.Add(writerWatcher);
                        }
                    }
                }

                CompositionContainer tempContainer = null;
                try
                {
                    tempContainer = new CompositionContainer(catalog);
                    try
                    {
                        tempContainer.ComposeParts(this);
                        container     = tempContainer;
                        tempContainer = null;
                    }
                    catch (CompositionException)
                    {
                        throw;
                    }
                }
                finally
                {
                    tempContainer?.Dispose();
                }
            }

            return(container);
        }
コード例 #7
0
        private void ComposePlugins(HttpApplication application)
        {
            var batch = new CompositionBatch();

            var directoryCatalog = new SafeDirectoryCatalog("bin");

            Container = new CompositionContainer(directoryCatalog);
            Container.ComposeParts(this, Responders);

            Container.Compose(batch);

            Plugins = Container.GetExports <IGlimpsePlugin, IGlimpsePluginRequirements>();

            var store = application.Context.GetWarnings();

            store.AddRange(directoryCatalog.Exceptions.Select(exception => new ExceptionWarning(exception)));

            //wireup converters into serializer
            Responders.RegisterConverters();
        }
コード例 #8
0
        /// <summary>
        /// Composes the part.
        /// </summary>
        /// <param name="sourceObject">The source object.</param>
        /// <returns>The source object after composition</returns>
        private static object ComposePart(object sourceObject)
        {
            string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;

            using (var aggregateCatalog = new AggregateCatalog())
            {
                //using (new LoggerExemptionScope(typeof(ConsoleLogger)))
                //{
                // Use a SafeDirectoryCatalog so that ReflectionTypeLoadExceptions are handled gracefully...
                using (var safeDirectoryCatalog = new SafeDirectoryCatalog(baseDirectory))
                {
                    aggregateCatalog.Catalogs.Add(safeDirectoryCatalog);

                    using (var container = new CompositionContainer(aggregateCatalog))
                    {
                        container.ComposeParts(sourceObject);
                        return(sourceObject);
                    }
                }
                //}
            }
        }
コード例 #9
0
        private void DoImport()
        {
            //An aggregate catalog that combines multiple catalogs
            //Adds all the parts found in all assemblies in the same directory as the executing program
            var catalog = new SafeDirectoryCatalog(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

            //Create the CompositionContainer with the parts in the catalog
            CompositionContainer container = new CompositionContainer(catalog);

            //Fill the imports of this object
            container.ComposeParts(this);
            foreach (Lazy <ICreateFactory, IDescription> plugin in pluginProviders)
            {
                try
                {
                    var val = plugin.Value;
                }
                catch (CompositionException ex)
                {
                    Log.ErrorException("pluginProviders have an invalid value: ", ex);
                }
            }
        }
コード例 #10
0
 public void Setup(SafeDirectoryCatalog result)
 {
     SafeDirectoryCatalog        = result;
     HaveDownloadedAllAssemblies = true;
 }
コード例 #11
0
 public static void TestIsDotNetAssembly()
 {
     Assert.True(SafeDirectoryCatalog.IsDotNetAssembly(Path.Combine(
                                                           RuntimeEnvironment.GetRuntimeDirectory(),
                                                           "System.Net.dll")));
 }
コード例 #12
0
ファイル: Startup.cs プロジェクト: HicServices/RDMP
        private void LoadMEF(ICatalogueRepository catalogueRepository, ICheckNotifier notifier)
        {
            DirectoryInfo downloadDirectory = catalogueRepository.MEF.DownloadDirectory;

            //make sure the MEF directory exists
            if (!downloadDirectory.Exists)
            {
                downloadDirectory.Create();
            }

            var compatiblePlugins = catalogueRepository.PluginManager.GetCompatiblePlugins();

            List <DirectoryInfo> dirs   = new List <DirectoryInfo>();
            List <DirectoryInfo> toLoad = new List <DirectoryInfo>();

            //always load the current application directory
            toLoad.Add(new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory));

            for (int i = 0; i < compatiblePlugins.Length; i++)
            {
                var subDirName = compatiblePlugins[i].GetPluginDirectoryName(downloadDirectory);
                var subdir     = Directory.CreateDirectory(subDirName);

                dirs.Add(subdir);

                var existingFiles = subdir.GetFiles("*" + PackPluginRunner.PluginPackageSuffix).ToList();

                //if we have not downloaded this yet
                if (!existingFiles.Any(f => f.Name.Equals(compatiblePlugins[i].Name)))
                {
                    compatiblePlugins[i].LoadModuleAssemblies.SingleOrDefault()?.DownloadAssembly(subdir);
                }
                else
                {
                    notifier.OnCheckPerformed(new CheckEventArgs("Found existing file '" + compatiblePlugins[i].Name + "' so didn't bother downloading it.", CheckResult.Success));
                }

                foreach (var archive in  subdir.GetFiles("*" + PackPluginRunner.PluginPackageSuffix).ToList())
                {
                    //get rid of any old out dirs
                    var outDir = subdir.EnumerateDirectories("out").SingleOrDefault();

                    bool mustUnzip = true;

                    //if there's already an unpacked version
                    if (outDir != null && outDir.Exists)
                    {
                        //if the directory has no files we have to unzip - otherwise it has an unzipped version already yay
                        mustUnzip = !outDir.GetFiles("*.dll", SearchOption.AllDirectories).Any();

                        if (mustUnzip)
                        {
                            outDir.Delete(true);
                        }
                    }
                    else
                    {
                        outDir = subdir.CreateSubdirectory("out");
                    }

                    if (mustUnzip)
                    {
                        using (var zf = ZipFile.OpenRead(archive.FullName))
                            try
                            {
                                zf.ExtractToDirectory(outDir.FullName);
                            }
                            catch (Exception ex)
                            {
                                notifier.OnCheckPerformed(new CheckEventArgs("Could not extract Plugin to '" + outDir.FullName + "'", CheckResult.Warning, ex));
                            }
                    }
                    else
                    {
                        notifier.OnCheckPerformed(new CheckEventArgs("Found existing directory '" + outDir.FullName + "' so didn't bother unzipping.", CheckResult.Success));
                    }

                    toLoad.AddRange(_environmentInfo.GetPluginSubDirectories(outDir.CreateSubdirectory("lib"), notifier));

                    //tell them we downloaded it
                    MEFFileDownloaded(this,
                                      new MEFFileDownloadProgressEventArgs(subdir, compatiblePlugins.Length, i + 1,
                                                                           archive.Name, false, MEFFileDownloadEventStatus.Success));
                }
            }

            //The only Directories in MEF folder should be Plugin subdirectories, any that don't correspond with a plugin should be deleted
            foreach (DirectoryInfo unexpectedDirectory in downloadDirectory.GetDirectories().Where(expected => !dirs.Any(d => d.FullName.Equals(expected.FullName))))
            {
                try
                {
                    unexpectedDirectory.Delete(true);
                    notifier.OnCheckPerformed(new CheckEventArgs("Deleted unreferenced plugin folder " + unexpectedDirectory.FullName, CheckResult.Success));
                }
                catch (Exception ex)
                {
                    notifier.OnCheckPerformed(
                        new CheckEventArgs(
                            "Found unreferenced (no Plugin) folder " + unexpectedDirectory.FullName +
                            " but we were unable to delete it (possibly because it is in use, try closing all your local RDMP applications and restarting this one)",
                            CheckResult.Fail, ex));
                }
            }

            AssemblyResolver.SetupAssemblyResolver(toLoad.ToArray());

            MEFSafeDirectoryCatalog = new SafeDirectoryCatalog(notifier, toLoad.Select(d => d.FullName).ToArray());
            catalogueRepository.MEF.Setup(MEFSafeDirectoryCatalog);

            notifier.OnCheckPerformed(new CheckEventArgs("Loading Help...", CheckResult.Success));
            var sw = Stopwatch.StartNew();

            if (!CatalogueRepository.SuppressHelpLoading)
            {
                catalogueRepository.CommentStore.ReadComments(Environment.CurrentDirectory, "SourceCodeForSelfAwareness.zip");
            }

            sw.Stop();
            notifier.OnCheckPerformed(new CheckEventArgs("Help loading took:" + sw.Elapsed, CheckResult.Success));
        }