public void WhenInitializingAModuleWithNoCatalogPendingToBeLoaded_ThenInitializesTheModule()
        {
            var aggregateCatalog = new AggregateCatalog(new AssemblyCatalog(typeof(MefModuleInitializer).Assembly));
            var compositionContainer = new CompositionContainer(aggregateCatalog);
            compositionContainer.ComposeExportedValue(aggregateCatalog);

            var serviceLocatorMock = new Mock<IServiceLocator>();
            var loggerFacadeMock = new Mock<ILoggerFacade>();

            var serviceLocator = serviceLocatorMock.Object;
            var loggerFacade = loggerFacadeMock.Object;

            compositionContainer.ComposeExportedValue(serviceLocator);
            compositionContainer.ComposeExportedValue(loggerFacade);

            aggregateCatalog.Catalogs.Add(new TypeCatalog(typeof(TestModuleForInitializer)));

            var moduleInitializer = compositionContainer.GetExportedValue<IModuleInitializer>();

            var moduleInfo = new ModuleInfo("TestModuleForInitializer", typeof(TestModuleForInitializer).AssemblyQualifiedName);

            var module = compositionContainer.GetExportedValues<IModule>().OfType<TestModuleForInitializer>().First();

            Assert.IsFalse(module.Initialized);

            moduleInitializer.Initialize(moduleInfo);

            Assert.IsTrue(module.Initialized);
        }
Beispiel #2
0
        public static void Main(string[] args)
        {
            // Initialize the composition catalog
            var aggregationPath = Path.Combine(
                Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                "Workflows");

            if (Directory.Exists(aggregationPath))
            {
                var directoryCatalog = new DirectoryCatalog(aggregationPath);
                using (CompositionContainer container = new CompositionContainer(directoryCatalog))
                {
                    IEnumerable <IProcessDefinitionRegistry> registries =
                        container.GetExportedValues <IProcessDefinitionRegistry>();
                    WfDeployer.Registries = registries;
                }
            }

            var parser = new FluentCommandLineParser <ApplicationArgumments>();

            parser.Setup(a => a.Command).As('c', "command").Required().SetDefault("help");
            parser.Setup(a => a.FlowId).As('f', "flowid").SetDefault(string.Empty);
            parser.Setup(a => a.Version).As('v', "version").SetDefault(-1);
            parser.Setup(a => a.RoleString).As('r', "role").SetDefault(string.Empty);

            var result = parser.Parse(args);

            if (!result.HasErrors)
            {
                Action <ApplicationArgumments> action;
                if (!Commands.TryGetValue(parser.Object.Command, out action))
                {
                    PrintHelp(parser.Object);
                    return;
                }
                action(parser.Object);
            }
            else
            {
                Console.WriteLine(result.ErrorText);
                Console.WriteLine("Use -c help for help");
            }
        }
Beispiel #3
0
        public EditorHost(CompositionContainer compositionContainer)
        {
            CompositionContainer           = compositionContainer;
            TextBufferFactoryService       = CompositionContainer.GetExportedValue <ITextBufferFactoryService>();
            TextEditorFactoryService       = CompositionContainer.GetExportedValue <ITextEditorFactoryService>();
            ProjectionBufferFactoryService = CompositionContainer.GetExportedValue <IProjectionBufferFactoryService>();
            SmartIndentationService        = CompositionContainer.GetExportedValue <ISmartIndentationService>();
            EditorOperationsFactoryService = CompositionContainer.GetExportedValue <IEditorOperationsFactoryService>();
            EditorOptionsFactoryService    = CompositionContainer.GetExportedValue <IEditorOptionsFactoryService>();
            TextSearchService                 = CompositionContainer.GetExportedValue <ITextSearchService>();
            OutliningManagerService           = CompositionContainer.GetExportedValue <IOutliningManagerService>();
            TextBufferUndoManagerProvider     = CompositionContainer.GetExportedValue <ITextBufferUndoManagerProvider>();
            ContentTypeRegistryService        = CompositionContainer.GetExportedValue <IContentTypeRegistryService>();
            ClassificationTypeRegistryService = CompositionContainer.GetExportedValue <IClassificationTypeRegistryService>();

            var errorHandlers = CompositionContainer.GetExportedValues <IExtensionErrorHandler>();

            BasicUndoHistoryRegistry = CompositionContainer.GetExportedValue <IBasicUndoHistoryRegistry>();
        }
Beispiel #4
0
        private T GetRequiredImport <T>() where T : class
        {
            T import = CompositionContainer.GetExportedValueOrDefault <T>();

            if (import == default(T))
            {
                int    importCount       = CompositionContainer.GetExportedValues <T>().Count();
                string extensionTypeName = typeof(T).Name;
                if (importCount > 1)
                {
                    MessageBox.Show(String.Format("You may only include one {0} Extension. {1} were found.", extensionTypeName, importCount));
                }
                else
                {
                    MessageBox.Show(String.Format("A {0} Extension must be included.", extensionTypeName));
                }
            }
            return(import);
        }
        private void InitCatalog()
        {
            AggregateCatalog = new AggregateCatalog();
            AggregateCatalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
            var pluginDirectory = SettingsService.GetPluginDirectory();

            foreach (var directory in Directory.GetDirectories(pluginDirectory, "*.*", SearchOption.AllDirectories))
            {
                AggregateCatalog.Catalogs.Add(new DirectoryCatalog(directory, "*.dll"));
            }

            //var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
            MefContainer = new CompositionContainer(AggregateCatalog);
            MefContainer.ComposeParts();
            foreach (ICheckoutAndBuildPlugin plugin in MefContainer.GetExportedValues <ICheckoutAndBuildPlugin>())
            {
                plugin.Init(new CheckoutAndBuildServiceProvider(this, MefContainer), pluginDirectory);
            }
        }
Beispiel #6
0
        private static IEnumerable <IPlugin> GetPluginsFrom(string path)
        {
            if (Directory.Exists(path))
            {
                try
                {
                    var result    = new List <IPlugin>();
                    var container = new CompositionContainer(new DirectoryCatalog(path));
                    var imanga    = typeof(Manga.IManga);
                    var ilogin    = typeof(Account.ILogin);
                    foreach (var plugin in container.GetExportedValues <IPlugin>())
                    {
                        try
                        {
                            if (!imanga.IsAssignableFrom(plugin.MangaType))
                            {
                                throw new MangaReaderException($"Type in property {nameof(plugin.MangaType)} of " +
                                                               $"type {plugin.GetType()} must be implement {imanga} interface.");
                            }

                            if (!ilogin.IsAssignableFrom(plugin.LoginType))
                            {
                                throw new MangaReaderException($"Type in property {nameof(plugin.LoginType)} of " +
                                                               $"type {plugin.GetType()} must be implement {ilogin} interface.");
                            }

                            Log.Add($"Plugin {plugin.Name} loaded.");
                            result.Add(plugin);
                        }
                        catch (MangaReaderException mre)
                        {
                            Log.Exception(mre);
                        }
                    }
                    return(result);
                }
                catch (System.Exception ex)
                {
                    Log.Exception(ex, string.Format("Plugins from {0} cannot be loaded.", path));
                }
            }
            return(Enumerable.Empty <IPlugin>());
        }
Beispiel #7
0
        public async Task ClientSyncParams()
        {
            var container = new CompositionContainer(new AggregateCatalog(RegisterAssembly.Distinct().Select(_ => new AssemblyCatalog(_)).OfType <ComposablePartCatalog>()));
            var values    = container.GetExportedValues <Pv2ParamType>();

            PayloadV2TestHelper.CreateParams(out var clientParams, out var serverParams, values);

            serverParams.WriteInt(ParamDefinition.ParamInt1, 10);
            serverParams.WriteInt(ParamDefinition.ParamInt2, 5);
            await clientParams.RequestAll();

            var readedInt = clientParams.ReadInt(ParamDefinition.ParamInt1);

            Assert.Equal(10, readedInt);

            var readedInt2 = clientParams.ReadInt(ParamDefinition.ParamInt2);

            Assert.Equal(5, readedInt2);
        }
Beispiel #8
0
        /// <summary>
        /// Gets all exports of type T
        /// </summary>
        public IEnumerable <T> GetExportedValues <T>()
        {
            lock (_exportedValuesLockObject)
            {
                IEnumerable values;
                if (_exportedValues.TryGetValue(typeof(T), out values))
                {
                    return(values.OfType <T>());
                }

                if (!_composableParts.IsCompleted)
                {
                    _composableParts.Wait();
                }
                values = _compositionContainer.GetExportedValues <T>().ToList();
                _exportedValues[typeof(T)] = values;
                return(values.OfType <T>());
            }
        }
Beispiel #9
0
        private static IEnumerable <Assembly> DiscoverAssembliesThatContainExtensionsUsingMef(string extensionsPath)
        {
            var catalog = new DirectoryCatalog(extensionsPath);
            var compositionContainer = new CompositionContainer(catalog);

            try
            {
                var modules = compositionContainer.GetExportedValues <IFunnelWebExtension>();
                return(modules.Select(m => m.GetType().Assembly).Distinct());
            }
            catch (ReflectionTypeLoadException ex)
            {
                if (ex.LoaderExceptions.Length > 0)
                {
                    throw new FunnelWebExtensionLoadException(string.Format("Failed to load {0}", ex.Types[0].Assembly.FullName), ex.LoaderExceptions[0]);
                }
                throw;
            }
        }
Beispiel #10
0
        IEnumerable <RuntimeComponent> m_runtimeParts = null;   // all the parts that MEF brings in

        public MainWindow()
        {
            InitializeComponent();
            m_cmdArgs = Environment.GetCommandLineArgs();

            /*************   MEF  *********************/
            try
            {                                         // let MEF build the app out of discovered parts
                var catalog = new AggregateCatalog(); // var type can not be init'd to null
                // BadFormatImageException occurs as a first chance exception if attempting to load a flat dll
                // as they are w/o a manifest, some32bitstd.dll. It can be safely ignored.
                // The code will continue to load .net dlls relevant to using the Managed Extension Framework (MEF).
                // 'relevant' means the component exports the IWx_Client interface
                catalog = new AggregateCatalog(new DirectoryCatalog("."),
                                               new AssemblyCatalog(Assembly.GetExecutingAssembly()));
                var container = new CompositionContainer(catalog);
                m_runtimeParts = container.GetExportedValues <RuntimeComponent>();  // ctors of the individual user components for the views called here
            }
            catch (ReflectionTypeLoadException)
            {
            }
            catch (Exception)
            {
            }
            foreach (RuntimeComponent win in m_runtimeParts)    // add the component to the ui grid + a separator line
            {
                RowDefinition gridRow = new RowDefinition();
                gridMain.RowDefinitions.Add(gridRow);
                StackPanel stackPnl = new StackPanel();
                stackPnl.Children.Add((UIElement)win);
                Grid.SetRow(stackPnl, gridMain.RowDefinitions.Count - 1);
                gridMain.Children.Add(stackPnl);
                RowDefinition gridRowBorder = new RowDefinition();
                gridMain.RowDefinitions.Add(gridRowBorder);
                Border border = new Border();
                Grid.SetRow(border, gridMain.RowDefinitions.Count - 1);
                border.Background = System.Windows.Media.Brushes.LemonChiffon;
                border.Height     = 10;
                gridMain.Children.Add(border);
            }
            /*************   MEF  *********************/
        }
        public List <TResult> Load <TResult>() where TResult : class
        {
            List <TResult> instances = new List <TResult>();

            try
            {
                if (_container != null)
                {
                    (_container.Catalog as DirectoryCatalog).Refresh();
                    instances = _container.GetExportedValues <TResult>().ToList();
                }
                else
                {
                    DirectoryCatalog catalog = new DirectoryCatalog(FolderPath);
                    _container = new CompositionContainer(catalog);
                    instances  = _container.GetExportedValues <TResult>().ToList();
                }

                return(instances);
            }
            catch (ImportCardinalityMismatchException)//when no contract implementation
            {
                return(instances);
            }
            catch (ReflectionTypeLoadException)//when wrong contract implementation
            {
                return(instances);
            }
            catch (FileNotFoundException)//
            {
                return(instances);
            }
            catch (Exception ex)
            {
                if (Wrapper.instance != null)
                {
                    Wrapper.instance.PrintException(ex);
                }

                throw new FormatException("Load of MEF file failed.", ex);
            }
        }
Beispiel #12
0
        private void LoadPlugins()
        {
            try
            {
                if (!Directory.Exists(@".\Plugins"))
                {
                    return;
                }

                var catalog = new DirectoryCatalog(@".\Plugins", "CInject.Plugin.*.dll");
                catalog.Refresh();

                var container = new CompositionContainer(catalog);
                Plugins = container.GetExportedValues <IPlugin>();

                var pluginArray = Plugins as IPlugin[] ?? Plugins.ToArray();
                PluginList = pluginArray.ToList();

                Parallel.ForEach(pluginArray, (current) =>
                {
                    try
                    {
                        if (current.Menu != null)
                        {
                            PopulatePluginMenu(current);
                        }
                    }
                    catch
                    {
                    }
                });
            }
            catch (AggregateException aggregateException)
            {
                string message = String.Concat(aggregateException.InnerExceptions.Select(x => x.Message));
                MessageBox.Show(Resources.PluginLoadErrorAggregate + message);
            }
            catch (Exception exception)
            {
                MessageBox.Show(Resources.PluginLoadErrorAggregate + exception.Message);
            }
        }
Beispiel #13
0
        public void DoWorkInShadowCopiedDomain()
        {
            // Use RegistrationBuilder to set up our MEF parts.
            var regBuilder = new RegistrationBuilder();

            regBuilder.ForTypesDerivedFrom <IExport>().Export <IExport>();

            var catalog = new AggregateCatalog();

            catalog.Catalogs.Add(new AssemblyCatalog(typeof(Runner).Assembly, regBuilder));
            directoryCatalog = new DirectoryCatalog(pluginPath, regBuilder);
            catalog.Catalogs.Add(directoryCatalog);

            container = new CompositionContainer(catalog);
            container.ComposeExportedValue(container);

            // Get our exports available to the rest of Program.
            exports = container.GetExportedValues <IExport>();
            Console.WriteLine("{0} exports in AppDomain {1}", exports.Count(), AppDomain.CurrentDomain.FriendlyName);
        }
Beispiel #14
0
        public object GetService(Type serviceType)
        {
            string contract = AttributedModelServices.GetContractName(serviceType);
            var    instance = container.GetExportedValues <object>(contract).FirstOrDefault();

            if (instance != null)
            {
                return(instance);
            }

            instance = Create(serviceType);

            if (instance != null)
            {
                return(instance);
            }

            throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
                                                              "Could not locate any instances of contract {0}.", contract));
        }
Beispiel #15
0
        static PluginManager()
        {
            Logger.Debug("Creating");
            DirectoryCatalog catalog = new DirectoryCatalog(Path.Combine(Directory.GetCurrentDirectory(), "Plugins"), "TAS.Server.*.dll");

            ServerContainer = new CompositionContainer(catalog);
            ServerContainer.ComposeExportedValue("AppSettings", ConfigurationManager.AppSettings);
            try
            {
                _enginePlugins = ServerContainer.GetExportedValues <IEnginePluginFactory>();
            }
            catch (ReflectionTypeLoadException e)
            {
                Logger.Error(e, "Plugin load failed: {0}", e.LoaderExceptions);
            }
            catch (Exception e)
            {
                Logger.Error(e, "Plugin load failed: {0}", e);
            }
        }
        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            CompositionContainer cc;
            AggregateCatalog     cat = new AggregateCatalog();

            cat.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));

            cc = new CompositionContainer(cat);

            pdfList.DisplayMemberPath = "Name";
            var list = cc.GetExportedValues <PDFTest>();

            pdfList.ItemsSource = list;


            if (list.Any())
            {
                pdfList.SelectedIndex = 0;
            }
        }
Beispiel #17
0
        private void ImportModules()
        {
            var assemblyDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            var modulesDirectory = Directory.GetDirectories(assemblyDirectory + @"\AdModules");


            var catalog = new AggregateCatalog();

            foreach (var module in modulesDirectory)
            {
                catalog.Catalogs.Add(
                    new DirectoryCatalog(module));
            }

            var container = new CompositionContainer(catalog);

            container.ComposeParts(this);
            _modules = container.GetExportedValues <IAdModule>().ToDictionary(k => k.Title, v => v);
        }
Beispiel #18
0
        public async Task UpdateRiseByServer()
        {
            var container = new CompositionContainer(new AggregateCatalog(RegisterAssembly.Distinct().Select(_ => new AssemblyCatalog(_)).OfType <ComposablePartCatalog>()));
            var values    = container.GetExportedValues <Pv2ParamType>();

            PayloadV2TestHelper.CreateParams(out var clientParams, out var serverParams, values);
            await clientParams.RequestAll();

            var serverBefore = serverParams.ReadInt(ParamDefinition.ParamInt1);
            var clientBefore = clientParams.ReadInt(ParamDefinition.ParamInt1);

            Assert.Equal(serverBefore, clientBefore);
            serverParams.WriteInt(ParamDefinition.ParamInt1, 100);
            await Task.Delay(2_000);

            var clientAfter = clientParams.ReadInt(ParamDefinition.ParamInt1);
            var serverAfter = serverParams.ReadInt(ParamDefinition.ParamInt1);

            Assert.Equal(clientAfter, serverAfter);
        }
Beispiel #19
0
        public EditorHost(CompositionContainer compositionContainer)
        {
            _compositionContainer           = compositionContainer;
            _textBufferFactoryService       = _compositionContainer.GetExportedValue <ITextBufferFactoryService>();
            _textEditorFactoryService       = _compositionContainer.GetExportedValue <ITextEditorFactoryService>();
            _projectionBufferFactoryService = _compositionContainer.GetExportedValue <IProjectionBufferFactoryService>();
            _smartIndentationService        = _compositionContainer.GetExportedValue <ISmartIndentationService>();
            _editorOperationsFactoryService = _compositionContainer.GetExportedValue <IEditorOperationsFactoryService>();
            _editorOptionsFactoryService    = _compositionContainer.GetExportedValue <IEditorOptionsFactoryService>();
            _textSearchService                 = _compositionContainer.GetExportedValue <ITextSearchService>();
            _outliningManagerService           = _compositionContainer.GetExportedValue <IOutliningManagerService>();
            _textBufferUndoManagerProvider     = _compositionContainer.GetExportedValue <ITextBufferUndoManagerProvider>();
            _contentTypeRegistryService        = _compositionContainer.GetExportedValue <IContentTypeRegistryService>();
            _classificationTypeRegistryService = _compositionContainer.GetExportedValue <IClassificationTypeRegistryService>();

            var errorHandlers = _compositionContainer.GetExportedValues <IExtensionErrorHandler>();

            _protectedOperations      = EditorUtilsFactory.CreateProtectedOperations(errorHandlers);
            _basicUndoHistoryRegistry = _compositionContainer.GetExportedValue <IBasicUndoHistoryRegistry>();
        }
Beispiel #20
0
        internal static void Initialize(CompositionContainer composition)
        {
            List <Language> languages = new List <Language>();

            if (composition != null)
            {
                languages.AddRange(composition.GetExportedValues <Language>());
            }
            else
            {
                languages.Add(new CSharpLanguage());
                languages.Add(new VB.VBLanguage());
            }

            // Fix order: C#, VB, IL
            var langs2 = new List <Language>();
            var lang   = languages.FirstOrDefault(a => a is CSharpLanguage);

            if (lang != null)
            {
                languages.Remove(lang);
                langs2.Add(lang);
            }
            lang = languages.FirstOrDefault(a => a is VB.VBLanguage);
            if (lang != null)
            {
                languages.Remove(lang);
                langs2.Add(lang);
            }
            langs2.Add(new ILLanguage(true));
            for (int i = 0; i < langs2.Count; i++)
            {
                languages.Insert(i, langs2[i]);
            }

#if DEBUG
            languages.AddRange(ILAstLanguage.GetDebugLanguages());
            languages.AddRange(CSharpLanguage.GetDebugLanguages());
#endif
            allLanguages = languages.AsReadOnly();
        }
        public InteractiveManager()
        {
            var host = MefHostServices.Create(MefHostServices.DefaultAssemblies.Concat(new[]
            {
                Assembly.Load("Microsoft.CodeAnalysis.Features"),
                Assembly.Load("Microsoft.CodeAnalysis.CSharp.Features"),
            }));

            _workspace    = new InteractiveWorkspace(host);
            _parseOptions = new CSharpParseOptions(kind: SourceCodeKind.Interactive);

            _references = _assemblyTypes.Select(t =>
                                                MetadataReference.CreateFromAssembly(t.Assembly)).ToArray();
            _compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary,
                                                               usings: _assemblyTypes.Select(x => x.Namespace).ToImmutableArray());

            var container = new CompositionContainer(new AssemblyCatalog(typeof(ISignatureHelpProvider).Assembly),
                                                     CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe);

            _signatureHelpProviders = container.GetExportedValues <ISignatureHelpProvider>().ToArray();
        }
        internal static Collection <T> GetExportedPlugins <T>(string directory, string searchPattern = "*.dll")
        {
            Collection <T>       plugins   = new Collection <T>();
            DirectoryCatalog     catalog   = new DirectoryCatalog(directory, searchPattern);
            CompositionContainer container = new CompositionContainer(catalog);

            try
            {
                foreach (var plugin in container.GetExportedValues <T>())
                {
                    plugins.Add(plugin);
                }
            }
            finally
            {
                catalog.Dispose();
                container.Dispose();
            }

            return(plugins);
        }
Beispiel #23
0
        private T GetRequiredImport <T>()
            where T : class
        {
            var imports = CompositionContainer.GetExportedValues <T>().ToList();

            if (imports.Count > 1)
            {
                // If more then one required import, skip default imports
                imports = imports.Where(_ => !_.GetType().GetCustomAttributes(typeof(DefaultRequiredImportAttribute), false).Any()).ToList();
            }

            if (imports.Count != 1)
            {
                var    importCount       = imports.Count;
                string extensionTypeName = typeof(T).Name;
                MessageBox.Show(importCount > 1 ? string.Format(MessageStrings.AppManager_OnlyIncludeOneExtension, extensionTypeName, importCount) : string.Format(MessageStrings.AppManager_NeedExtensionBecauseUIPluginFound, extensionTypeName));
                return(null);
            }

            return(imports[0]);
        }
Beispiel #24
0
        /// <summary>
        /// Loads the available plugins.
        /// </summary>
        public void LoadPlugins()
        {
            if (!Directory.Exists(this.pluginDirectory))
            {
                return;
            }

            if (String.IsNullOrEmpty(this.pluginDirectory))
            {
                return;
            }

            var aggregateCatalog = new AggregateCatalog();
            var subDirs          = Directory.GetDirectories(this.pluginDirectory);

            foreach (var dir in subDirs)
            {
                var catalog = new DirectoryCatalog(dir);

                try
                {
                    CompositionContainer tmpContainer = new CompositionContainer(catalog);
                    tmpContainer.GetExportedValues <WsapmPluginBase>();
                }
                catch (Exception ex) // (CompositionException ex)
                {
                    // Ignore plugins that fail to load.
                    WsapmLog.Log.WriteError(Resources.Wsapm_Core.PuginLoader_CompositionError, ex);
                    continue;
                }

                aggregateCatalog.Catalogs.Add(catalog);
            }

            var compositionContainer = new CompositionContainer(aggregateCatalog);

            compositionContainer.ComposeParts(this);

            CheckForDuplicateGuidsAndManifest();
        }
Beispiel #25
0
        // Load plugins
        private static void LoadPlugins()
        {
            int archivePlugins = 0, compressionPlugins = 0, texturePlugins = 0;

            try
            {
                // Get all of the DLLs in the Plugins directory and load them if they contain any classes that impliment IPuyoToolsPlugin.
                AggregateCatalog     catalog   = new AggregateCatalog(new DirectoryCatalog("Plugins", "*.dll"), new AssemblyCatalog(Assembly.GetExecutingAssembly()));
                CompositionContainer container = new CompositionContainer(catalog);
                Plugins = container.GetExportedValues <IPuyoToolsPlugin>();

                foreach (IPuyoToolsPlugin plugin in Plugins)
                {
                    // Now, let's attempt to determine which type of plugin this is
                    // and add it to the appropiate module lists.

                    if (plugin is ArchiveBase archiveModule)
                    {
                        // Archive module
                        Archive.Formats.Add(ArchiveFormat.Plugin + archivePlugins, archiveModule);
                        archivePlugins++;
                    }

                    else if (plugin is CompressionBase compressionModule)
                    {
                        // Compression module
                        Compression.Formats.Add(CompressionFormat.Plugin + compressionPlugins, compressionModule);
                        compressionPlugins++;
                    }

                    else if (plugin is TextureBase textureModule)
                    {
                        // Texture module
                        Texture.Formats.Add(TextureFormat.Plugin + texturePlugins, textureModule);
                        texturePlugins++;
                    }
                }
            }
            catch { }
        }
Beispiel #26
0
        public void RegisterRequiredServicesIfMissingAndUDPMessageHandler()
        {
            AggregateCatalog _catalog    = new AggregateCatalog(new AssemblyCatalog("UAOOI.Networking.UDPMessageHandler.dll"));
            AggregateCatalog _newCatalog = DefaultServiceRegistrar.RegisterServices(_catalog);

            using (CompositionContainer _container = new CompositionContainer(_newCatalog))
            {
                Assert.AreEqual <int>(9, _container.Catalog.Parts.Count <ComposablePartDefinition>());
                foreach (ComposablePartDefinition _part in _container.Catalog.Parts)
                {
                    Debug.WriteLine("New Part");
                    foreach (ImportDefinition _import in _part.ImportDefinitions)
                    {
                        Debug.WriteLine(string.Format("Imported contracts name => '{0}'", _import.ContractName));
                    }
                    foreach (ExportDefinition _export in _part.ExportDefinitions)
                    {
                        Debug.WriteLine(string.Format("Exported contracts name => '{0}'", _export.ContractName));
                    }
                }
                IMessageHandlerFactory _messageHandlerFactory = _container.GetExportedValue <IMessageHandlerFactory>();
                Assert.IsNotNull(_messageHandlerFactory);
                INetworkingEventSourceProvider _baseEventSource = _messageHandlerFactory as INetworkingEventSourceProvider;
                Assert.IsNull(_baseEventSource);
                IEnumerable <INetworkingEventSourceProvider> _diagnosticProviders = _container.GetExportedValues <INetworkingEventSourceProvider>();
                Assert.AreEqual <int>(3, _diagnosticProviders.Count <INetworkingEventSourceProvider>());
                using (CompositeDisposable _Components = new CompositeDisposable())
                {
                    EventSourceBootstrapper _eventSourceBootstrapper = _container.GetExportedValue <EventSourceBootstrapper>();
                    _Components.Add(_eventSourceBootstrapper);
                    Assert.AreEqual <int>(3, _eventSourceBootstrapper.EventSources.Count <INetworkingEventSourceProvider>());
                    ConsumerDataManagementSetup m_ConsumerConfigurationFactory = _container.GetExportedValue <ConsumerDataManagementSetup>();
                    _Components.Add(m_ConsumerConfigurationFactory);
                    OPCUAServerProducerSimulator m_OPCUAServerProducerSimulator = _container.GetExportedValue <OPCUAServerProducerSimulator>();
                    _Components.Add(m_OPCUAServerProducerSimulator);
                    Assert.AreEqual <int>(3, _Components.Count);
                }
            }
        }
        private List <TPlugin> LoadPlugin(string pluginDirectory)
        {
            CompositionContainer _container = null;

            List <TPlugin> instances = new List <TPlugin>();

            try
            {
                if (_container != null)
                {
                    (_container.Catalog as DirectoryCatalog).Refresh();
                    instances = _container.GetExportedValues <TPlugin>().ToList();
                }
                else
                {
                    DirectoryCatalog catalog = new DirectoryCatalog(pluginDirectory);
                    _container = new CompositionContainer(catalog);
                    instances  = _container.GetExportedValues <TPlugin>().ToList();
                }

                return(instances);
            }
            catch (ImportCardinalityMismatchException)//when no contract implementation
            {
                return(instances);
            }
            catch (ReflectionTypeLoadException)//when wrong contract implementation
            {
                return(instances);
            }
            catch (FileNotFoundException)//
            {
                return(instances);
            }
            catch (Exception ex)
            {
                throw new FormatException("Load of MEF file failed.", ex);
            }
        }
Beispiel #28
0
        public void AutoPopulateButtonPanel()
        {
            Assert.Inconclusive("The test must be adopted from the RI - container cannot be created because there are errors for imports satisfied by IRegionManager export.");
            var catalog = new AggregateCatalog();

            catalog.Catalogs.Add(new AssemblyCatalog(typeof(Shell).Assembly));
            CompositionContainer container = new CompositionContainer(catalog);
            IEnumerable <object> _v1       = container.GetExportedValues <object>();

            Assert.IsNotNull(_v1);
            Assert.AreEqual <int>(2, _v1.Count <object>());

            AutoPopulateExportedViewsBehavior behavior = container.GetExportedValue <AutoPopulateExportedViewsBehavior>();
            Region region = new Region()
            {
                Name = RegionNames.ButtonsRegion
            };

            region.Behaviors.Add("", behavior);
            Assert.AreEqual(1, region.Views.Cast <object>().Count());
            Assert.IsTrue(region.Views.Cast <object>().Any(e => e.GetType() == typeof(ButtonsPanel)));
        }
Beispiel #29
0
        public void Execute(CompositionContainer container)
        {
            try
            {
                var providers = container.GetExportedValues <IInfoProvider>();

                var location = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

                var root = XElement.Load(location + @"\\Config.xml");

                var host = container.GetExportedValue <ISysInfoHost>();
                Debug.Assert(host != null);

                Tools.WriteLine($"{nameof(CurrentDiagnosticsTask)}: Collecting Diagnostics");

                // Run all Info providers
                var results = RunProviders(root, providers);
                var result  = new XElement($"SystemInfo",
                                           new XAttribute("Date", DateTime.Now.ToString("dd-MM-yyyy_HH-mm-ss")),
                                           results);

                // save XML to file
                string resultFile = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                                                 $"{ConfigurationManager.AppSettings["ResultDir"]}",
                                                 "Diagnostics.xml");

                result.Save(resultFile);

                // add XML result file to collected files
                host.AddFile(resultFile, Path.GetFileName(resultFile), true);
            }
            catch (Exception ex)
            {
                _log.Error($"TASK FAILED: {ex.ToString()}.");
                Tools.WriteError($"{nameof(CurrentDiagnosticsTask)}: TASK FAILED: {ex.Message}");
            }

            Tools.WriteLine($"{nameof(CurrentDiagnosticsTask)}: Finished successfully.", ConsoleColor.DarkGreen);
        }
        protected override object GetInstance(Type service, string key)
        {
            this.logger.Info("GetInstance {0}, {1}", service, key);
            string contract = String.IsNullOrEmpty(key) ? AttributedModelServices.GetContractName(service) : key;

            IEnumerable <object> exports;

            try {
                exports = container.GetExportedValues <object>(contract);
            }
            catch (System.Exception ex) {
                this.logger.Error(ex);
                throw;
            }

            if (exports.Any())
            {
                return(exports.First());
            }

            throw new ArgumentException(String.Format("Could not locate any instances of contract {0}.", contract));
        }
Beispiel #31
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            DispatcherUnhandledException += App_OnDispatcherUnhandledException;
            AppDomain.CurrentDomain.UnhandledException += AppDomain_OnUnhandledException;

            _catalog = new AggregateCatalog();
            _catalog.Catalogs.Add(new AssemblyCatalog(typeof(ViewModel).Assembly));
            _catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
            _catalog.Catalogs.Add(new AssemblyCatalog(typeof(IEntityController).Assembly));
            _catalog.Catalogs.Add(new AssemblyCatalog(typeof(AppDbContext).Assembly));
            _catalog.Catalogs.Add(new AssemblyCatalog(typeof(DataModelBase <>).Assembly));
            _catalog.Catalogs.Add(new AssemblyCatalog(typeof(IEntityService).Assembly));
            _catalog.Catalogs.Add(new AssemblyCatalog(typeof(ViewModelBase <,>).Assembly));

            foreach (var assembly in AppSettings.Default.ModuleAssemblies)
            {
                _catalog.Catalogs.Add(new AssemblyCatalog(assembly));
            }

            _container = new CompositionContainer(_catalog, CompositionOptions.DisableSilentRejection);
            var batch = new CompositionBatch();

            batch.AddExportedValue(_container);
            _container.Compose(batch);

            _moduleControllers = _container.GetExportedValues <IModuleController>();

            foreach (var moduleController in _moduleControllers)
            {
                moduleController.Initialize();
            }

            foreach (var moduleController in _moduleControllers)
            {
                moduleController.Run();
            }
        }
        public void WhenInitializingAModuleWithACatalogPendingToBeLoaded_ThenLoadsTheCatalogInitializesTheModule()
        {
            var aggregateCatalog = new AggregateCatalog(new AssemblyCatalog(typeof(MefModuleInitializer).Assembly));
            var compositionContainer = new CompositionContainer(aggregateCatalog);
            compositionContainer.ComposeExportedValue(aggregateCatalog);

            var serviceLocatorMock = new Mock<IServiceLocator>();
            var loggerFacadeMock = new Mock<ILoggerFacade>();

            var serviceLocator = serviceLocatorMock.Object;
            var loggerFacade = loggerFacadeMock.Object;

            compositionContainer.ComposeExportedValue(serviceLocator);
            compositionContainer.ComposeExportedValue(loggerFacade);

            var moduleInitializer = compositionContainer.GetExportedValue<IModuleInitializer>();
            var repository = compositionContainer.GetExportedValue<DownloadedPartCatalogCollection>();

            var moduleInfo = new ModuleInfo("TestModuleForInitializer", typeof(TestModuleForInitializer).AssemblyQualifiedName);

            repository.Add(moduleInfo, new TypeCatalog(typeof(TestModuleForInitializer)));

            moduleInitializer.Initialize(moduleInfo);

            ComposablePartCatalog existingCatalog;
            Assert.IsFalse(repository.TryGet(moduleInfo, out existingCatalog));

            var module = compositionContainer.GetExportedValues<IModule>().OfType<TestModuleForInitializer>().First();

            Assert.IsTrue(module.Initialized);
        }