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); }
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); }
public ConcreteTypeExportHandlerContext() { var typeCatalog = new TypeCatalog(typeof(OrderProcessor)); var catalog = new AggregateCatalog(); ConcreteTypeHandler = new ConcreteTypeExportHandler(); string orderProcessorContract = AttributedModelServices.GetContractName(typeof(OrderProcessor)); var orderProcessPartDefinition = typeCatalog.Parts.Single(p => p.ExportDefinitions.Any(d => d.ContractName == orderProcessorContract)); RepositoryImportDefinition = orderProcessPartDefinition.ImportDefinitions.First(); Context(); }
//[ImportMany(typeof(IFormExstension), AllowRecomposition = true)] //public List<IFormExstension> FormExtensions { get; set; } public void LoadExtensions() { string path = Application.StartupPath + @"\Extensions"; if(Directory.Exists(path)) { var catalog = new AggregateCatalog( new AssemblyCatalog(Assembly.GetExecutingAssembly()), new DirectoryCatalog(path)); var batch = new CompositionBatch(); batch.AddPart(this); _container = new CompositionContainer(catalog); try { _container.Compose(batch); } catch (CompositionException compositionException) { MessageBox.Show(compositionException.ToString()); } } }
public void DeclaredModuleWithTypeInUnreferencedAssemblyIsUpdatedWithTypeNameFromExportAttribute() { AggregateCatalog aggregateCatalog = new AggregateCatalog(); CompositionContainer compositionContainer = new CompositionContainer(aggregateCatalog); var mockFileTypeLoader = new Mock<MefFileModuleTypeLoader>(); mockFileTypeLoader.Setup(tl => tl.CanLoadModuleType(It.IsAny<ModuleInfo>())).Returns(true); ModuleCatalog moduleCatalog = new ModuleCatalog(); ModuleInfo moduleInfo = new ModuleInfo { ModuleName = "MefModuleOne", ModuleType = "some type" }; moduleCatalog.AddModule(moduleInfo); compositionContainer.ComposeExportedValue<IModuleCatalog>(moduleCatalog); compositionContainer.ComposeExportedValue<MefFileModuleTypeLoader>(mockFileTypeLoader.Object); bool wasInit = false; var mockModuleInitializer = new Mock<IModuleInitializer>(); mockModuleInitializer.Setup(x => x.Initialize(It.IsAny<ModuleInfo>())).Callback(() => wasInit = true); var mockLoggerFacade = new Mock<ILoggerFacade>(); MefModuleManager moduleManager = new MefModuleManager( mockModuleInitializer.Object, moduleCatalog, mockLoggerFacade.Object); compositionContainer.SatisfyImportsOnce(moduleManager); moduleManager.Run(); Assert.IsFalse(wasInit); AssemblyCatalog assemblyCatalog = new AssemblyCatalog(GetPathToModuleDll()); aggregateCatalog.Catalogs.Add(assemblyCatalog); compositionContainer.SatisfyImportsOnce(moduleManager); mockFileTypeLoader.Raise(tl => tl.LoadModuleCompleted += null, new LoadModuleCompletedEventArgs(moduleInfo, null)); Assert.AreEqual("MefModulesForTesting.MefModuleOne, MefModulesForTesting, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", moduleInfo.ModuleType); Assert.IsTrue(wasInit); }
public App() { // Add Ctrl+Shift+Z as a redo command. Don't know why it isn't enabled by default. ApplicationCommands.Redo.InputGestures.Add(new KeyGesture(Key.Z, ModifierKeys.Control | ModifierKeys.Shift)); var cmdArgs = Environment.GetCommandLineArgs().Skip(1); App.CommandLineArguments = new CommandLineArguments(cmdArgs); if (App.CommandLineArguments.SingleInstance ?? true) { cmdArgs = cmdArgs.Select(FullyQualifyPath); string message = string.Join(Environment.NewLine, cmdArgs); if (SendToPreviousInstance("dnSpy:\r\n" + message, !App.CommandLineArguments.NoActivate)) { Environment.Exit(0); } } InitializeComponent(); var catalog = new AggregateCatalog(); catalog.Catalogs.Add(new AssemblyCatalog(typeof(App).Assembly)); // Don't use DirectoryCatalog, that causes problems if the plugins are from the Internet zone // see http://stackoverflow.com/questions/8063841/mef-loading-plugins-from-a-network-shared-folder string appPath = Path.GetDirectoryName(typeof(App).Module.FullyQualifiedName); foreach (string plugin in Directory.GetFiles(appPath, "*.Plugin.dll")) { string shortName = Path.GetFileNameWithoutExtension(plugin); try { var asm = Assembly.Load(shortName); asm.GetTypes(); catalog.Catalogs.Add(new AssemblyCatalog(asm)); } catch (Exception ex) { // Cannot show MessageBox here, because WPF would crash with a XamlParseException // Remember and show exceptions in text output, once MainWindow is properly initialized StartupExceptions.Add(new ExceptionData { Exception = ex, PluginName = shortName }); } } compositionContainer = new CompositionContainer(catalog); Languages.Initialize(compositionContainer); if (!System.Diagnostics.Debugger.IsAttached) { AppDomain.CurrentDomain.UnhandledException += ShowErrorBox; Dispatcher.CurrentDispatcher.UnhandledException += Dispatcher_UnhandledException; } TaskScheduler.UnobservedTaskException += DotNet40_UnobservedTaskException; EventManager.RegisterClassHandler(typeof(Window), Hyperlink.RequestNavigateEvent, new RequestNavigateEventHandler(Window_RequestNavigate)); FixEditorContextMenuStyle(); }
public CatalogService(AggregateCatalog catalog) { this._catalog = catalog; }
private static void RegisterExtensions(AggregateCatalog catalog, IEnumerable <string> enumerateFiles, IConsole console) { foreach (var item in enumerateFiles) { AssemblyCatalog assemblyCatalog = null; try { assemblyCatalog = new AssemblyCatalog(item); // get the parts - throw if something went wrong var parts = assemblyCatalog.Parts; // load all the types - throw if assembly cannot load (missing dependencies is a good example) var assembly = Assembly.LoadFile(item); assembly.GetTypes(); catalog.Catalogs.Add(assemblyCatalog); } catch (BadImageFormatException ex) { if (assemblyCatalog != null) { assemblyCatalog.Dispose(); } // Ignore if the dll wasn't a valid assembly console.WriteWarning(ex.Message); } catch (FileLoadException ex) { // Ignore if we couldn't load the assembly. if (assemblyCatalog != null) { assemblyCatalog.Dispose(); } var message = String.Format(LocalizedResourceManager.GetString(nameof(NuGetResources.FailedToLoadExtension)), item); console.WriteWarning(message); console.WriteWarning(ex.Message); } catch (ReflectionTypeLoadException rex) { // ignore if the assembly is missing dependencies var resource = LocalizedResourceManager.GetString(nameof(NuGetResources.FailedToLoadExtensionDuringMefComposition)); var perAssemblyError = string.Empty; if (rex?.LoaderExceptions.Length > 0) { var builder = new StringBuilder(); builder.AppendLine(string.Empty); var errors = rex.LoaderExceptions.Select(e => e.Message).Distinct(StringComparer.Ordinal); foreach (var error in errors) { builder.AppendLine(error); } perAssemblyError = builder.ToString(); } var warning = string.Format(resource, item, perAssemblyError); console.WriteWarning(warning); } } }
public void Initialize() { try { RegisterChummerProtocol(); if (!GlobalSettings.PluginsEnabled) { Log.Info("Plugins are globally disabled - exiting PluginControl.Initialize()"); return; } Log.Info("Plugins are globally enabled - entering PluginControl.Initialize()"); string path = Path.Combine(Utils.GetStartupPath, "plugins"); path = Path.GetFullPath(path); if (!Directory.Exists(path)) { string msg = "Directory " + path + " not found. No Plugins will be available."; throw new ArgumentException(msg); } _objCatalog = new AggregateCatalog(); //delete old NeonJungleLC-Plugin Utils.SafeDeleteDirectory(Path.Combine(path, "NeonJungleLC")); bool blnAnyPlugins = false; foreach (string plugindir in Directory.EnumerateDirectories(path)) { blnAnyPlugins = true; if (plugindir.Contains("SamplePlugin", StringComparison.OrdinalIgnoreCase)) { Log.Warn("Found an old SamplePlugin (not maintaned anymore) and deleteing it to not mess with the plugin catalog composition."); Utils.SafeDeleteDirectory(plugindir); continue; } Log.Trace("Searching in " + plugindir + " for plugin.txt or dlls containing the interface."); //search for a text file that tells me what dll to parse string infofile = Path.Combine(plugindir, "plugin.txt"); if (File.Exists(infofile)) { Log.Trace(infofile + " found: parsing it!"); using (StreamReader file = new StreamReader(infofile)) { string line; while ((line = file.ReadLine()) != null) { string plugindll = Path.Combine(plugindir, line); Log.Trace(infofile + " containes line: " + plugindll + " - trying to find it..."); if (File.Exists(plugindll)) { FileInfo fi = new FileInfo(plugindll); _objMyDirectoryCatalog = new DirectoryCatalog(plugindir, fi.Name); Log.Info("Searching for plugin-interface in dll: " + plugindll); _objCatalog.Catalogs.Add(_objMyDirectoryCatalog); } else { Log.Warn("Could not find dll from " + infofile + ": " + plugindll); _objMyDirectoryCatalog = new DirectoryCatalog(plugindir, "*.dll"); Log.Info("Searching for dlls in path " + _objMyDirectoryCatalog?.FullPath); _objCatalog.Catalogs.Add(_objMyDirectoryCatalog); } } } } else { _objMyDirectoryCatalog = new DirectoryCatalog(plugindir, "*.dll"); Log.Info("Searching for dlls in path " + _objMyDirectoryCatalog?.FullPath); _objCatalog.Catalogs.Add(_objMyDirectoryCatalog); } } if (!blnAnyPlugins) { throw new ArgumentException("No Plugin-Subdirectories in " + path + " !"); } _container = new CompositionContainer(_objCatalog); //Fill the imports of this object StartWatch(); try { _container.ComposeParts(this); } catch (ReflectionTypeLoadException e) { if (Program.ChummerTelemetryClient != null) { foreach (var except in e.LoaderExceptions) { Program.ChummerTelemetryClient.TrackException(except); } Program.ChummerTelemetryClient.Flush(); string msg = $"Plugins (at least not all of them) could not be loaded. Logs are uploaded to the ChummerDevs. Maybe ping one of the Devs on Discord and provide your Installation-id: {Properties.Settings.Default.UploadClientId}"; Log.Info(e, msg); } else { Log.Error(e, "Plugins (at least not all of them) could not be loaded. Please allow logging to upload logs."); } } if (MyPlugins.Count == 0) { throw new ArgumentException("No plugins found in " + path + '.'); } Log.Info("Plugins found: " + MyPlugins.Count + Environment.NewLine + "Plugins active: " + MyActivePlugins.Count); foreach (IPlugin plugin in MyActivePlugins) { try { Log.Info("Initializing Plugin " + plugin); plugin.SetIsUnitTest(Utils.IsUnitTest); plugin.CustomInitialize(Program.MainForm); } catch (ApplicationException) { throw; } catch (Exception e) { Log.Error(e); #if DEBUG throw; #endif } } Log.Info("Initializing Plugins finished."); } catch (System.Security.SecurityException e) { string msg = "Well, the Plugin wanted to do something that requires Admin rights. Let's just ignore this: " + Environment.NewLine + Environment.NewLine; msg += e.ToString(); Log.Warn(e, msg); } catch (Exception e) when(!(e is ApplicationException)) { Log.Fatal(e); throw; } }
private void Run(string dir, string filter, string printerName = "Default") { var catalog = new AggregateCatalog(); //Adds all the parts found in the same assembly as the Program class catalog.Catalogs.Add(new AssemblyCatalog(typeof(Program).Assembly)); var container = new CompositionContainer(catalog); container.ComposeParts(this); linePrinter = LogLinePrinters.First(p => string.Equals(p.Value.Name, printerName, StringComparison.InvariantCultureIgnoreCase)).Value; var filePositions = new Dictionary<string, long>(); //var watcher = new FileSystemWatcher(); //watcher.Path = dir; //watcher.Renamed += (sender, renameArgs) => { lastFileByFileSystemWatcher = renameArgs.FullPath; }; //watcher.EnableRaisingEvents = true; //watcher.Filter = filter; //watcher.IncludeSubdirectories = true; Console.WriteLine($"Watching {dir} for changes on {filter}"); var currentFile = FindLastChangedFile(dir, filter); while (true) { if (currentFile == null) { Thread.Sleep(100); continue; } using (StreamReader reader = new StreamReader( new FileStream( currentFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))) { //start at the end of the file var currentFilePosition = reader.BaseStream.Length; if (filePositions.ContainsKey(currentFile)) { currentFilePosition = filePositions[currentFile]; } else { filePositions[currentFile] = currentFilePosition; } string lastFile = currentFile; while (string.Equals(currentFile = FindLastChangedFile(dir, filter), lastFile)) { Thread.Sleep(100); //if the file size has not changed, idle if (reader.BaseStream.Length == currentFilePosition) { continue; } //seek to the last max offset reader.BaseStream.Seek(currentFilePosition, SeekOrigin.Begin); //read out of the file until the EOF var line = ""; while ((line = reader.ReadLine()) != null) { PrintNewLogLine(currentFile, line); } //update the last max offset and lastFile filePositions[currentFile] = currentFilePosition = reader.BaseStream.Position; lastFile = currentFile; } } } }
public PluginCompositionContainer() { _aggreagateCatalog = new AggregateCatalog(); }
/// <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)); }