Esempio n. 1
0
        private static FilteredCatalog BuildLayoutCatalog(ComposablePartCatalog parentCatalog)
        {
            Expression <Func <ComposablePartDefinition, bool> > findAllLayoutExtensions = (def) => (def.ExportDefinitions.Any(exportDef => exportDef.ContractName.EndsWith("LayoutBase")));
            FilteredCatalog newFilteredCatalog = new FilteredCatalog(parentCatalog, findAllLayoutExtensions);

            return(newFilteredCatalog);
        }
Esempio n. 2
0
        /// <summary>
        /// Builds and returns a special catalog, based on the application assembly, that
        /// has been filtered to contain a single preference provider part.
        /// </summary>
        /// <param name="parentCatalog"></param>
        /// <returns>a Berico.LinkAnalysis.SnagL.Modularity.FilteredCatalog containing the
        /// configured preference provider; otherwise the default perference provider</returns>
        private static FilteredCatalog BuildPreferenceProviderCatalog(ComposablePartCatalog parentCatalog)
        {
            // Retrieve the name of the configrued preference provider
            string preferencesProvider = ConfigurationManager.Instance.CurrentConfig.PreferencesProvider.Provider;

            FilteredCatalog newFilteredCatalog = null;

            Expression <Func <ComposablePartDefinition, bool> > findSpecifiedLogger = (def) => (def.ExportDefinitions.Any(exportDef => exportDef.ContractName.EndsWith("IPreferencesProvider"))) && (def.Metadata.ContainsKey("ID") && def.Metadata["ID"].ToString().ToLower().Equals(preferencesProvider.ToLower()));
            Expression <Func <ComposablePartDefinition, bool> > findDefaultLogger   = (def) => (def.ExportDefinitions.Any(exportDef => exportDef.ContractName.EndsWith("IPreferencesProvider"))) && (def.Metadata.ContainsKey("IsDefault") && bool.Parse(def.Metadata["IsDefault"].ToString()) == true);

            // We don't want to search for the specified logger provider if
            // none was specified.
            if (string.IsNullOrEmpty(preferencesProvider))
            {
                return(new FilteredCatalog(parentCatalog, findDefaultLogger));
            }

            // If we get here, we need to try and find the logger provider specified
            // by the user
            newFilteredCatalog = new FilteredCatalog(parentCatalog, findSpecifiedLogger);

            // If the catalog is empty, fall to the default
            if ((newFilteredCatalog.Parts == null) || (newFilteredCatalog.Parts.Count() == 0))
            {
                // If we didn't find any parts, we should try again and just get the
                // default provider
                return(new FilteredCatalog(parentCatalog, findDefaultLogger));
            }

            return(newFilteredCatalog);
        }
Esempio n. 3
0
        public void LoadAssemblies(params object[] targets)
        {
            foreach (var location in GetAssembliesLocation())
            {
                try
                {
                    DirectoryCatalog dirCatalog = new DirectoryCatalog(Path.GetDirectoryName(location), Path.GetFileName(location));
                    var filtCatalog             = new FilteredCatalog(dirCatalog,
                                                                      filter => filter.ExportDefinitions.Any(
                                                                          definition => definition.ContractName == typeof(ITrader).AssemblyQualifiedName));

                    if (filtCatalog.Any())
                    {
                        _aggregate.Catalogs.Add(filtCatalog);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }

            try
            {
                _container.ComposeParts(targets);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Instructs MEF to satisfy all imports, against the current
        /// collection of catalogs,for the provided part.
        /// </summary>
        /// <param name="part">The object (MEF part) that should be composed</param>
        public static void ComposeParts(Object part)
        {
            try
            {
                // The logger is used before configruation and initialization
                // so we want to handle it in a special way.  We just want to
                // compose it using a single filtered catalog to find the default
                // logger.  Everything will be rebuilt and recomposed after
                // configruation.
                if (part is Logging.LoggerManager)
                {
                    // Create a Berico.LinkAnalysis.
                    FilteredCatalog loggerCatalog = BuildLoggerProviderCatalog(new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly()));
                    primaryCatalog.Catalogs.Add(loggerCatalog);

                    CompositionHost.Initialize(new CompositionContainer(primaryCatalog));
                }

                // Now we compose and satisfy the imports for the provided Part
                CompositionInitializer.SatisfyImports(part);
            }
            catch (Exception ex)
            {
                if (logger != null)
                {
                    logger.WriteLogEntry(Logging.LogLevel.ERROR, "An error occurred trying to compose the parts for the provided object.", ex, null);
                }
                else
                {
                    // This is only for testing.  We don't really want to
                    // do this in the long run.
                    MessageBox.Show(ex.Message);
                }
            }
        }
        private ChorusFileTypeHandlerCollection(
            Expression <Func <ComposablePartDefinition, bool> > filter = null,
            string[] additionalAssemblies = null)
        {
            using (var aggregateCatalog = new AggregateCatalog())
            {
                aggregateCatalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
                aggregateCatalog.Catalogs.Add(new DirectoryCatalog(".", "*-ChorusPlugin.dll"));
                if (additionalAssemblies != null)
                {
                    foreach (var assemblyPath in additionalAssemblies)
                    {
                        if (System.IO.File.Exists(assemblyPath))
                        {
                            aggregateCatalog.Catalogs.Add(new AssemblyCatalog(assemblyPath));
                        }
                    }
                }

                ComposablePartCatalog catalog;
                if (filter != null)
                {
                    catalog = new FilteredCatalog(aggregateCatalog, filter);
                }
                else
                {
                    catalog = aggregateCatalog;
                }

                using (var container = new CompositionContainer(catalog))
                {
                    container.ComposeParts(this);
                }
            }
        }
        public void Mef_can_use_container_hierarchy_to_have_scoped_composable_parts()
        {
            var rootContainer         = Mef;
            var rootCatalog           = rootContainer.Catalog;
            var nonSharedPartsCatalog = new FilteredCatalog(rootCatalog, def => IsNonSharedOrAny(def));

            IDisposableScopedService    scoped1, scoped2;
            IDisposableSingletonService singleton1, singleton2;

            using (var scope1 = new CompositionContainer(nonSharedPartsCatalog, rootContainer))
            {
                scoped1    = scope1.GetExport <IDisposableScopedService>().Value;
                singleton1 = scope1.GetExport <IDisposableSingletonService>().Value;
                Assert.IsFalse(scoped1.IsDisposed);
                Assert.IsFalse(singleton1.IsDisposed);

                using (var scope2 = new CompositionContainer(nonSharedPartsCatalog, rootContainer))
                {
                    scoped2    = scope2.GetExport <IDisposableScopedService>().Value;
                    singleton2 = scope2.GetExport <IDisposableSingletonService>().Value;
                    Assert.AreNotSame(scoped1, scoped2);
                    Assert.AreSame(singleton1, singleton2);
                }

                Assert.IsTrue(scoped2.IsDisposed);
                Assert.IsFalse(scoped1.IsDisposed);
                Assert.IsFalse(singleton2.IsDisposed);
            }

            Assert.IsTrue(scoped1.IsDisposed);
            Assert.IsFalse(singleton1.IsDisposed);

            rootContainer.Dispose();
            Assert.IsTrue(singleton1.IsDisposed);
        }
Esempio n. 7
0
        /// <summary>
        /// </summary>
        /// <param name="parentCatalog"></param>
        /// <returns></returns>
        private static FilteredCatalog BuildRankingCatalog(ComposablePartCatalog parentCatalog)
        {
            FilteredCatalog newFilteredCatalog = null;

            Expression <Func <ComposablePartDefinition, bool> > findAllRankingExtensions = (def) => (def.ExportDefinitions.Any(exportDef => exportDef.ContractName.EndsWith("IRanker")));

            newFilteredCatalog = new FilteredCatalog(parentCatalog, findAllRankingExtensions);

            return(newFilteredCatalog);
        }
Esempio n. 8
0
        /// <summary>
        /// Completes initialization of the ExtensionManager class.  This will be called after
        /// all DeploymentCatalogs have finished downloading parts.
        /// </summary>
        /// <param name="catalogs">The external deployment catalogs to load</param>
        private static void CompleteInitialization(IEnumerable <DeploymentCatalog> catalogs)
        {
            lock (syncRoot)
            {
                AggregateCatalog tempCatalog = new AggregateCatalog();

                // Clear the primary catalog
                primaryCatalog.Catalogs.Clear();

                // Build a catalog containing all Parts in the entire assembly
                AssemblyCatalog assemblyCatalog = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());

                foreach (DeploymentCatalog catalog in catalogs)
                {
                    tempCatalog.Catalogs.Add(catalog);
                }

                tempCatalog.Catalogs.Add(assemblyCatalog);

                // Create the two special catalogs for the logger and preference providers
                FilteredCatalog loggerProviderCatalog              = BuildLoggerProviderCatalog(tempCatalog);
                FilteredCatalog preferencesProviderCatalog         = BuildPreferenceProviderCatalog(tempCatalog);
                FilteredCatalog toolbarExtensionsCatalog           = BuildToolbarExtensionsCatalog(tempCatalog);
                FilteredCatalog toolPanelExtensionsCatalog         = BuildToolPanelExtensionsCatalog(tempCatalog);
                FilteredCatalog similarityMeasureExtensionsCatalog = BuildSimilarityMeasureExtensionsCatalog(tempCatalog);
                FilteredCatalog rankingCatalog = BuildRankingCatalog(tempCatalog);
                FilteredCatalog graphDataFormatExtensionsCatalog = BuildGraphDataFormatExtensionsCatalog(tempCatalog);
                FilteredCatalog actionCatalog = BuildActionCatalog(tempCatalog);
                FilteredCatalog layoutCatalog = BuildLayoutCatalog(tempCatalog);

                // Add the two filtered catalogs to the master catalog
                primaryCatalog.Catalogs.Add(loggerProviderCatalog);
                primaryCatalog.Catalogs.Add(preferencesProviderCatalog);
                primaryCatalog.Catalogs.Add(toolbarExtensionsCatalog);
                primaryCatalog.Catalogs.Add(toolPanelExtensionsCatalog);
                primaryCatalog.Catalogs.Add(similarityMeasureExtensionsCatalog);
                primaryCatalog.Catalogs.Add(graphDataFormatExtensionsCatalog);
                primaryCatalog.Catalogs.Add(actionCatalog);
                primaryCatalog.Catalogs.Add(layoutCatalog);
                primaryCatalog.Catalogs.Add(rankingCatalog);
            }

            // Reset the flags
            IsBusy      = false;
            initialized = true;

            // Satisfy the imports for the logger manager
            CompositionInitializer.SatisfyImports(Logging.LoggerManager.Instance);

            //Logging.LoggerManager.Instance.Level = ConfigurationManager.GetValue(ConfigurationManager.PARAMETER_LOGGER_LEVEL);
        }
Esempio n. 9
0
        /// <summary>
        /// Builds and returns a special catalog, based on the application assembly, that
        /// has been filtered to contain all tool panel extensions
        /// </summary>
        /// <param name="parentCatalog"></param>
        /// <returns>a Berico.LinkAnalysis.SnagL.Modularity.FilteredCatalog containing all
        /// Tool Panel extensions</returns>
        private static FilteredCatalog BuildToolPanelExtensionsCatalog(ComposablePartCatalog parentCatalog)
        {
            // Retrieve the name of the configrued preference provider
            //string preferencesProvider = ConfigurationManager.GetValue(ConfigurationManager.PARAMETER_PREFERENCES_PROVIDER);

            FilteredCatalog newFilteredCatalog = null;

            Expression <Func <ComposablePartDefinition, bool> > findAllToolPanelItemExtensions = (def) => (def.ExportDefinitions.Any(exportDef => exportDef.ContractName.EndsWith("IToolPanelItemViewExtension")) || (def.Metadata.ContainsKey("ID") && def.Metadata["ID"].ToString().ToLower().Equals("toolpanelitemviewmodelextension")));

            // If we get here, we need to try and find the logger provider specified
            // by the user
            newFilteredCatalog = new FilteredCatalog(parentCatalog, findAllToolPanelItemExtensions);

            return(newFilteredCatalog);
        }
Esempio n. 10
0
        /// <summary>
        /// Disposes of the instance.
        /// </summary>
        /// <param name="disposing"></param>
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (filter != null)
            {
                filter.Dispose();
                filter = null;
            }

            if (aggregate != null)
            {
                aggregate.Dispose();
                aggregate = null;
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Builds and returns a special catalog, based on the application assembly, that
        /// has been filtered to contain all graph data format classes
        /// </summary>
        /// <param name="parentCatalog"></param>
        /// <returns>a Berico.LinkAnalysis.SnagL.Modularity.FilteredCatalog containing the
        /// configured preference provider; otherwise the default perference provider</returns>
        private static FilteredCatalog BuildGraphDataFormatExtensionsCatalog(ComposablePartCatalog parentCatalog)
        {
            // Retrieve the name of the configrued preference provider
            //string preferencesProvider = ConfigurationManager.GetValue(ConfigurationManager.PARAMETER_PREFERENCES_PROVIDER);

            FilteredCatalog newFilteredCatalog = null;

            Expression <Func <ComposablePartDefinition, bool> > findAllSimilarityMeasureExtensions = (def) => (def.ExportDefinitions.Any(exportDef => exportDef.ContractName.EndsWith("IGraphDataFormat")));

            //Expression<Func<ComposablePartDefinition, bool>> findDefaultLogger = (def) => (def.ExportDefinitions.Any(exportDef => exportDef.ContractName.EndsWith("IPreferencesProvider"))) && (def.Metadata.ContainsKey("IsDefault") && bool.Parse(def.Metadata["IsDefault"].ToString()) == true);

            // If we get here, we need to try and find the logger provider specified
            // by the user
            newFilteredCatalog = new FilteredCatalog(parentCatalog, findAllSimilarityMeasureExtensions);

            return(newFilteredCatalog);
        }
        private void Initialize()
        {
            var aggregateCatalog = new AggregateCatalog();

            this.InstancesToDispose.Add(aggregateCatalog);

            foreach (var assembly in this.AssembliesToInclude.Distinct())
            {
                var assemblyCatalog = new AssemblyCatalog(assembly);

                aggregateCatalog.Catalogs.Add(assemblyCatalog);
                this.InstancesToDispose.Add(assemblyCatalog);
            }

            foreach (var type in this.TypesToInclude.Distinct())
            {
                var typeCatalog = new TypeCatalog(type);

                aggregateCatalog.Catalogs.Add(typeCatalog);
                this.InstancesToDispose.Add(typeCatalog);
            }

            // Add a filter removing types from the test.
            Func <ComposablePartDefinition, bool> filter =
                (definition) =>
                this.TypesToRemove.All(type => definition.ExportDefinitions.All(e => e.ContractName != type.FullName));

            var filteredCatalog = new FilteredCatalog(aggregateCatalog, filter);

            this.InstancesToDispose.Add(filteredCatalog);

            this.Container = new CompositionContainer(
                filteredCatalog,
                CompositionOptions.DisableSilentRejection | CompositionOptions.ExportCompositionService
                | CompositionOptions.IsThreadSafe);

            this.Container.ComposeExportedValue(this.Container);

            foreach (var stub in this.StubsToCompose)
            {
                this.ComposeStub(stub.Type, stub.Instance);
            }

            this.OnInitialized();
        }
Esempio n. 13
0
        public static IFormattingEngine Create(ImmutableArray <string> ruleTypes)
        {
            var catalog = new AssemblyCatalog(typeof(FormattingEngine).Assembly);

            var ruleTypesHash     = new HashSet <string>(ruleTypes, StringComparer.InvariantCultureIgnoreCase);
            var notFoundRuleTypes = new HashSet <string>(ruleTypes, StringComparer.InvariantCultureIgnoreCase);

            var filteredCatalog = new FilteredCatalog(catalog, cpd =>
            {
                if (cpd.ExportDefinitions.Any(em =>
                                              em.ContractName == AttributedModelServices.GetContractName(typeof(ISyntaxFormattingRule)) ||
                                              em.ContractName == AttributedModelServices.GetContractName(typeof(ILocalSemanticFormattingRule)) ||
                                              em.ContractName == AttributedModelServices.GetContractName(typeof(IGlobalSemanticFormattingRule)) ||
                                              em.ContractName == AttributedModelServices.GetContractName(typeof(IFormattingFilter))))
                {
                    object ruleType;
                    if (cpd.Metadata.TryGetValue(RuleTypeConstants.PartMetadataKey, out ruleType))
                    {
                        if (ruleType is string)
                        {
                            notFoundRuleTypes.Remove((string)ruleType);
                            if (!ruleTypesHash.Contains((string)ruleType))
                            {
                                return(false);
                            }
                        }
                    }
                }

                return(true);
            });

            var container           = new CompositionContainer(filteredCatalog);
            var engine              = container.GetExportedValue <IFormattingEngine>();
            var consoleFormatLogger = new ConsoleFormatLogger();

            //  Need to do this after the catalog is queried, otherwise the lambda won't have been run
            foreach (var notFoundRuleType in notFoundRuleTypes)
            {
                consoleFormatLogger.WriteErrorLine("The specified rule type was not found: {0}", notFoundRuleType);
            }

            return(engine);
        }
Esempio n. 14
0
        private ChorusFileTypeHandlerCollection(
            Expression <Func <ComposablePartDefinition, bool> > filter = null,
            string[] additionalAssemblies = null)
        {
            using (var aggregateCatalog = new AggregateCatalog())
            {
                aggregateCatalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
                aggregateCatalog.Catalogs.Add(new DirectoryCatalog(".", "*-ChorusPlugin.dll"));
                if (additionalAssemblies != null)
                {
                    foreach (var assemblyPath in additionalAssemblies)
                    {
                        aggregateCatalog.Catalogs.Add(new AssemblyCatalog(assemblyPath));
                    }
                }

                ComposablePartCatalog catalog;
                if (filter != null)
                {
                    catalog = new FilteredCatalog(aggregateCatalog, filter);
                }
                else
                {
                    catalog = aggregateCatalog;
                }

                using (var container = new CompositionContainer(catalog))
                {
                    try
                    {
                        container.ComposeParts(this);
                    }
                    catch (ReflectionTypeLoadException ex)
                    {
                        var loaderExceptions = ex.LoaderExceptions;
                        System.Diagnostics.Debug.Fail("Loading exception!");
                        throw new AggregateException(ex.Message, loaderExceptions);
                    }
                }
            }
        }
        public void MefExportFactoryDoesntThrow()
        {
            var rootCatalog           = new TypeCatalog(typeof(SessionManager), typeof(Helper));
            var nonSharedPartsCatalog = new FilteredCatalog(rootCatalog, def =>
            {
                var md  = def.Metadata;
                var key = CompositionConstants.PartCreationPolicyMetadataName;
                return(!md.ContainsKey(key) ||
                       (CreationPolicy)md[key] == CreationPolicy.Any ||
                       (CreationPolicy)md[key] == CreationPolicy.NonShared);
            });

            var rootContainer = new CompositionContainer(rootCatalog);

            Helper.flag = false;

            Assert.DoesNotThrow(() =>
            {
                // first request
                using (var requestScope = new CompositionContainer(nonSharedPartsCatalog, rootContainer))
                {
                    var sessionManager = requestScope.GetExport <ISessionManager>();
                    var sessionId      = sessionManager.Value.CreateSession();
                    Assert.AreEqual("123", sessionId);
                }
            },
                                "First request has thrown an exception");

            Assert.DoesNotThrow(() =>
            {
                // second request
                using (var requestScope = new CompositionContainer(nonSharedPartsCatalog, rootContainer))
                {
                    var sessionManager = requestScope.GetExport <ISessionManager>();
                    var sessionId      = sessionManager.Value.CreateSession();
                    Assert.AreEqual("321", sessionId);
                }
            },
                                "Second request has thrown an exception");
        }
Esempio n. 16
0
        public Bootstrapper()
        {
            var catalog = new AggregateCatalog(new AssemblyCatalog(typeof(App).Assembly));
            if (ViewModelLocator.Container.Catalog != null)
            {
                catalog.Catalogs.Add(ViewModelLocator.Container.Catalog);
            }
            Expression<Func<ComposablePartDefinition, bool>> expression =
                definition => !definition.Metadata.ContainsKey("IsDesignService") ||
                    definition.Metadata.ContainsKey("IsDesignService") &&
                    (bool) definition.Metadata["IsDesignService"] == Designer.IsInDesignMode;
            var filteredCatalog = new FilteredCatalog(catalog, expression);
            var providers = new List<ExportProvider>(ViewModelLocator.Container.Providers);
            var container = new CompositionContainer(filteredCatalog, providers.ToArray());

            var batch = new CompositionBatch();
            batch.AddExportedValue(container);

            ViewModelLocator.Container = container;

            container.Compose(batch);
        }
Esempio n. 17
0
        public EmbeddedMessageContentHandlerRepository()
        {
            var libChorusAssembly = Assembly.GetExecutingAssembly();

            //Set the codebase variable appropriately depending on the OS
            var codeBase = libChorusAssembly.CodeBase.Substring(Platform.IsUnix ? 7 : 8);
            var baseDir  = Path.GetDirectoryName(codeBase);

            // REVIEW: for some reason using *.* or *.dll didn't work - creating the catalogs in
            // unit tests (on Linux) failed with FileNotFoundException - don't know why.
            using (var aggregateCatalog = new AggregateCatalog(new DirectoryCatalog(baseDir, "Chorus.exe"),
                                                               new AssemblyCatalog(libChorusAssembly)))
                using (var catalog = new FilteredCatalog(aggregateCatalog,
                                                         def => !def.Metadata.ContainsKey("IsDefault")))
                    using (var defaultExportProvider = new CatalogExportProvider(new TypeCatalog(typeof(IEmbeddedMessageContentHandler))))
                    {
                        using (var container = new CompositionContainer(catalog, defaultExportProvider))
                        {
                            defaultExportProvider.SourceProvider = container;
                            container.ComposeParts(this);
                        }
                    }
        }
Esempio n. 18
0
        private void Compose(PluginContainer pluginContainer, IPluginHost host)
        {
            var catalog = new AggregateCatalog();
            var count = 0;
            foreach (var directory in Directory.GetDirectories(Repository))
            {
                Logger.DebugFormat("Found plugin in '{0}'", directory);
                catalog.Catalogs.Add(new DirectoryCatalog(directory));
                count++;
            }
            Logger.InfoFormat("Found {0} plugin(s) in the repository. (Validation not done)", count);

            var filteredCatatog = new FilteredCatalog(catalog, def => this.FilterPlugin(def));

            var container = new CompositionContainer(filteredCatatog);
            var composition = new CompositionBatch();
            composition.AddPart(pluginContainer);

            container.Compose(composition);
        }
Esempio n. 19
0
        private static FilteredCatalog BuildLayoutCatalog(ComposablePartCatalog parentCatalog)
        {
            Expression<Func<ComposablePartDefinition, bool>> findAllLayoutExtensions = (def) => (def.ExportDefinitions.Any(exportDef => exportDef.ContractName.EndsWith("LayoutBase")));
            FilteredCatalog newFilteredCatalog = new FilteredCatalog(parentCatalog, findAllLayoutExtensions);

            return newFilteredCatalog;
        }
Esempio n. 20
0
        /// <summary>
        /// Builds and returns a special catalog, based on the application assembly, that
        /// has been filtered to contain a single preference provider part.
        /// </summary>
        /// <param name="parentCatalog"></param>
        /// <returns>a Berico.LinkAnalysis.SnagL.Modularity.FilteredCatalog containing the 
        /// configured preference provider; otherwise the default perference provider</returns>
        private static FilteredCatalog BuildPreferenceProviderCatalog(ComposablePartCatalog parentCatalog)
        {
            // Retrieve the name of the configrued preference provider
            string preferencesProvider = ConfigurationManager.Instance.CurrentConfig.PreferencesProvider.Provider;

            FilteredCatalog newFilteredCatalog = null;

            Expression<Func<ComposablePartDefinition, bool>> findSpecifiedLogger = (def) => (def.ExportDefinitions.Any(exportDef => exportDef.ContractName.EndsWith("IPreferencesProvider"))) && (def.Metadata.ContainsKey("ID") && def.Metadata["ID"].ToString().ToLower().Equals(preferencesProvider.ToLower()));
            Expression<Func<ComposablePartDefinition, bool>> findDefaultLogger = (def) => (def.ExportDefinitions.Any(exportDef => exportDef.ContractName.EndsWith("IPreferencesProvider"))) && (def.Metadata.ContainsKey("IsDefault") && bool.Parse(def.Metadata["IsDefault"].ToString()) == true);

            // We don't want to search for the specified logger provider if
            // none was specified.
            if (string.IsNullOrEmpty(preferencesProvider))
            {
                return new FilteredCatalog(parentCatalog, findDefaultLogger);
            }

            // If we get here, we need to try and find the logger provider specified
            // by the user
            newFilteredCatalog = new FilteredCatalog(parentCatalog, findSpecifiedLogger);

            // If the catalog is empty, fall to the default
            if ((newFilteredCatalog.Parts == null) || (newFilteredCatalog.Parts.Count() == 0))
            {
                // If we didn't find any parts, we should try again and just get the
                // default provider
                return new FilteredCatalog(parentCatalog, findDefaultLogger);
            }

            return newFilteredCatalog;
        }
Esempio n. 21
0
        /// <summary>
        /// Builds and returns a special catalog, based on the application assembly, that
        /// has been filtered to contain all tool panel extensions
        /// </summary>
        /// <param name="parentCatalog"></param>
        /// <returns>a Berico.LinkAnalysis.SnagL.Modularity.FilteredCatalog containing all
        /// Tool Panel extensions</returns>
        private static FilteredCatalog BuildToolPanelExtensionsCatalog(ComposablePartCatalog parentCatalog)
        {
            // Retrieve the name of the configrued preference provider
            //string preferencesProvider = ConfigurationManager.GetValue(ConfigurationManager.PARAMETER_PREFERENCES_PROVIDER);

            FilteredCatalog newFilteredCatalog = null;

            Expression<Func<ComposablePartDefinition, bool>> findAllToolPanelItemExtensions = (def) => (def.ExportDefinitions.Any(exportDef => exportDef.ContractName.EndsWith("IToolPanelItemViewExtension")) || (def.Metadata.ContainsKey("ID") && def.Metadata["ID"].ToString().ToLower().Equals("toolpanelitemviewmodelextension")));

            // If we get here, we need to try and find the logger provider specified
            // by the user
            newFilteredCatalog = new FilteredCatalog(parentCatalog, findAllToolPanelItemExtensions);

            return newFilteredCatalog;
        }
Esempio n. 22
0
        /// <summary>
        /// </summary>
        /// <param name="parentCatalog"></param>
        /// <returns></returns>
        private static FilteredCatalog BuildRankingCatalog(ComposablePartCatalog parentCatalog)
        {
            FilteredCatalog newFilteredCatalog = null;

            Expression<Func<ComposablePartDefinition, bool>> findAllRankingExtensions = (def) => (def.ExportDefinitions.Any(exportDef => exportDef.ContractName.EndsWith("IRanker")));
            newFilteredCatalog = new FilteredCatalog(parentCatalog, findAllRankingExtensions);

            return newFilteredCatalog;
        }
Esempio n. 23
0
 /// <summary>
 /// Adds a predicate condition that exposes additional instances from the source.
 /// </summary>
 /// <param name="predicate"></param>
 public void Or(Func <ComposablePartDefinition, bool> predicate)
 {
     // filter remainder of previous filter
     aggregate.Catalogs.Add(filter = filter.Complement.Filter(i => predicate(i)));
 }
Esempio n. 24
0
 /// <summary>
 /// Initializes a new instance. By default no instances from <paramref name="source"/> are exposed.
 /// </summary>
 /// <param name="source"></param>
 public DynamicFilteredCatalog(ComposablePartCatalog source)
 {
     aggregate = new AggregateCatalog(filter = source.Filter(i => false));
 }
Esempio n. 25
0
        public void ResolveSaucesByFilteredCatalog()
        {
            var representative = typeof(Ploeh.Samples.Menu.Mef.Attributed.Unmodified.Abstract.SauceBéarnaise);
            var assemblyCatalog = new AssemblyCatalog(representative.Assembly);
            var catalog = new FilteredCatalog(assemblyCatalog, def => def.ExportDefinitions.Any(x => x.ContractName.Contains("Sauce")));
            var container = new CompositionContainer(catalog);

            var sauces = container.GetExportedValues<IIngredient>();

            Assert.True(sauces.OfType<SauceBéarnaise>().Any());
            Assert.True(sauces.OfType<SauceHollandaise>().Any());
            Assert.True(sauces.OfType<SauceMousseline>().Any());

            Assert.False(sauces.OfType<Steak>().Any());
        }
Esempio n. 26
0
        /// <summary>
        /// Builds and returns a special catalog, based on the application assembly, that
        /// has been filtered to contain all similarity measure classes
        /// </summary>
        /// <param name="parentCatalog"></param>
        /// <returns>a Berico.LinkAnalysis.SnagL.Modularity.FilteredCatalog containing the 
        /// configured preference provider; otherwise the default perference provider</returns>
        private static FilteredCatalog BuildSimilarityMeasureExtensionsCatalog(ComposablePartCatalog parentCatalog)
        {
            // Retrieve the name of the configrued preference provider
            //string preferencesProvider = ConfigurationManager.GetValue(ConfigurationManager.PARAMETER_PREFERENCES_PROVIDER);

            FilteredCatalog newFilteredCatalog = null;

            Expression<Func<ComposablePartDefinition, bool>> findAllSimilarityMeasureExtensions = (def) => (def.ExportDefinitions.Any(exportDef => exportDef.ContractName.EndsWith("ISimilarityMeasure")) || (def.Metadata.ContainsKey("ID") && def.Metadata["ID"].ToString().ToLower().Equals("SimilarityMeasureExtension")));
            //Expression<Func<ComposablePartDefinition, bool>> findDefaultLogger = (def) => (def.ExportDefinitions.Any(exportDef => exportDef.ContractName.EndsWith("IPreferencesProvider"))) && (def.Metadata.ContainsKey("IsDefault") && bool.Parse(def.Metadata["IsDefault"].ToString()) == true);

            // If we get here, we need to try and find the logger provider specified
            // by the user
            newFilteredCatalog = new FilteredCatalog(parentCatalog, findAllSimilarityMeasureExtensions);

            return newFilteredCatalog;
        }