private IImportClient FindClient( string pluginDirectory, ImportConnectionInfo connectionInfo, ImportContext context) { container?.Dispose(); catalog?.Dispose(); // We can add logic here to check for multiple constructions of the import client from the same app domain, // but with different version requests. Compare the plugin directory that was passed in, against a static plugin // directory variable -----------------NOTE - is this not already happening in the calling method? // Note: You MUST use a specific enough filename filter for your plugins and prevent MEF from trying // to do things like load native binaries. this.catalog = new DirectoryCatalog(pluginDirectory, "Relativity.DataExchange.Wrapper.*.dll"); this.container = new CompositionContainer(catalog); this.ImportClients.Clear(); container.ComposeExportedValue("ImportConnectionInfo", connectionInfo); container.ComposeExportedValue("ImportContext", context); container.ComposeParts(this); if (this.ImportClients.Count == 0) { throw new InvalidOperationException( "The import cannot be completed because no plugins were discovered."); } List <Lazy <IImportClient> > candidates = this.ImportClients.ToList(); if (candidates.Count > 1) { throw new InvalidOperationException( "The import cannot be completed because more than 1 plugin was discovered."); } IImportClient client = candidates[0].Value; return(client); }
/// <summary> /// Assembles the calculator components /// </summary> public void AssembleCalculatorComponents() { try { //Creating an instance of aggregate catalog. It aggregates other catalogs var aggregateCatalog = new AggregateCatalog(); //Build the directory path where the parts will be available var directoryPath = string.Concat(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) .Split('\\').Reverse().Skip(3).Reverse().Aggregate((a, b) => a + "\\" + b) , "\\", "ExportComponents\\Components"); Debug.WriteLine("Path is: [" + directoryPath + "]"); //Load parts from the available dlls in the specified path using the directory catalog var directoryCatalog = new DirectoryCatalog(directoryPath, "*.dll"); //Load parts from the current assembly if available var asmCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); //Add to the aggregate catalog aggregateCatalog.Catalogs.Add(directoryCatalog); aggregateCatalog.Catalogs.Add(asmCatalog); //Crete the composition container var container = new CompositionContainer(aggregateCatalog); // Composable parts are created here i.e. the Import and Export components assembles here container.ComposeParts(this); } catch (Exception ex) { throw ex; } }
public static void LoadContainer(IUnityContainer container, string path, string pattern) { var dirCat = new DirectoryCatalog(path, pattern); var importDef = BuildImportDefinition(); try { using (var aggregateCatalog = new AggregateCatalog()) { aggregateCatalog.Catalogs.Add(dirCat); using (var compositionContainer = new CompositionContainer(aggregateCatalog)) { IEnumerable <Export> exports = compositionContainer.GetExports(importDef); IEnumerable <IComponent> modules = exports.Select(export => export.Value as IComponent).Where(m => m != null); var registerComponent = new RegisterComponent(container); foreach (IComponent module in modules) { module.SetUp(registerComponent); } } } } catch (ReflectionTypeLoadException typeLoadException) { var builder = new StringBuilder(); foreach (Exception loaderException in typeLoadException.LoaderExceptions) { builder.AppendFormat("{0}\n", loaderException.Message); } throw new TypeLoadException(builder.ToString(), typeLoadException); } }
/// <summary> /// constructor /// </summary> private Container() { // An aggregate catalog that combines multiple catalogs var catalog = new AggregateCatalog(); // Adds all the parts found in the folder whether Microsoft.AcccessiblityInsights.Extentions.dll // later we will need to make it configurable. var dirCatalog = new DirectoryCatalog(Path.GetDirectoryName(typeof(Container).Assembly.Location), ExtensionSearchPattern); catalog.Catalogs.Add(dirCatalog); // Dynamically search for assemblies when it fails to resolve _extensionPaths = GetExtensionPaths(); _assemblyEventResolver = new ResolveEventHandler(CurrentDomain_AssemblyResolve); AppDomain.CurrentDomain.AssemblyResolve += _assemblyEventResolver; // Adds all the parts found in .\Extensions directory foreach (string path in _extensionPaths) { catalog.Catalogs.Add(new DirectoryCatalog(path, ExtensionSearchPattern)); } //Create the CompositionContainer with the parts in the catalog _container = new CompositionContainer(catalog); //Fill the imports of this object try { _container.ComposeParts(this); } catch { // Fail silently, since the code is designed to run without extensions // and our Telemetry extension will always be null at this point } }
public void ConfigureServices(IServiceCollection services) { var builder = services.AddMvcCore() .AddJsonFormatters(); if (Directory.Exists("plugins")) { var catalog = new DirectoryCatalog("plugins"); var container = new CompositionContainer(catalog); container.SatisfyImportsOnce(this); foreach (var item in controllers.Select(x => x.GetType().Assembly).Distinct()) { builder.AddApplicationPart(item); } } services.AddCors(); services.AddSingleton <WebSocketManager>(); services.AddSingleton <IInputManager, KeyboardManager>(); services.AddSingleton <IInputManager, JoystickMgr>(); }
// Select an addon version that is equal to or lower than the current EarTrumpet version. // New addons are implicitly compatible. // If no lower-or-equal version is found, the addon is incompatible and won't be loaded. private DirectoryCatalog SelectAddon(string path) { try { Trace.WriteLine($"AddonResolver SelectAddon: {path}"); var versionRoot = Path.Combine(path, "Versions"); var versions = Directory.GetDirectories(versionRoot).Select(f => Path.GetFileName(f)).Select(f => Version.Parse(f)).OrderBy(v => v); foreach (var version in versions.Reverse()) { if (version <= App.PackageVersion) { var cat = new DirectoryCatalog(Path.Combine(versionRoot, version.ToString()), "EarTrumpet*.dll"); _addonDirectoryPaths.Add(cat.Path); return(cat); } } } catch (Exception ex) { Trace.WriteLine($"AddonResolver SelectAddon: {ex}"); } Trace.WriteLine($"AddonResolver SelectAddon: Return without selection: {path}"); return(null); }
public int ExtensionLoader(string strFolderSearchName) { var catalog = new AggregateCatalog(); //catalog.Catalogs.Add(CFPAssemblyCatalog); //This must be passed from System "Program" in CheckerFrameProgram. To use some System Func ID related to system (JigId =0 & JigID = 1000) //Add catalog from "Extensions" Directory //string strExtensionsPath = Application.StartupPath + @"\Extensions"; string strExtensionsPath = Application.StartupPath + @"\" + strFolderSearchName; //catalog.Catalogs.Add(new DirectoryCatalog(strExtensionsPath)); var test = new DirectoryCatalog(strExtensionsPath); lststrLoadFiles = test.LoadedFiles.ToList <string>(); catalog.Catalogs.Add(test); //var assemblies = catalog.Parts.Select(part => ReflectionModelServices.GetPartType(part).Value.Assembly).Distinct().ToList(); //var assemblies = test.Parts.Select(part => ReflectionModelServices.GetPartType(part).Value.Assembly).Distinct().ToList(); //test.Parts. //Create compositioner container with parts in catalog _container = new CompositionContainer(catalog); //Fill the imports of this object try { _container.ComposeParts(this); return(0); //OK code } catch (Exception ex) { MessageBox.Show(ex.Message, "ExtensionLoader() Fail!"); return(1); //Unexpected error code } }
public void LoadParts(params Assembly[] ass) { try { AggregateCatalog agg = new AggregateCatalog(); DirectoryCatalog catalog = new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory, "XLY.*.dll"); agg.Catalogs.Add(catalog); string toolkitsFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "XlyToolkits"); if (Directory.Exists(toolkitsFolder)) { var toolkitPath = Directory.GetDirectories(toolkitsFolder); foreach (var item in toolkitPath) { DirectoryCatalog toolKitExe = new DirectoryCatalog(item, "*.exe"); agg.Catalogs.Add(toolKitExe); } } AssemblyCatalog ac = new AssemblyCatalog(this.GetType().Assembly); agg.Catalogs.Add(ac); if (ass != null) { foreach (var item in ass) { agg.Catalogs.Add(new AssemblyCatalog(item)); } } com = new CompositionContainer(agg, true); com.ComposeParts(this); } catch (Exception ex) { LoggerManagerSingle.Instance.Error(ex); } }
public void Load() { try { DirectoryCatalog catalog_plugin = new DirectoryCatalog(Path.Combine(Environment.CurrentDirectory, gatewayPath)); CompositionContainer container = new CompositionContainer(catalog_plugin); CompositionBatch bath = new CompositionBatch(); bath.AddPart(this); container.Compose(bath); string[] hows = new string[plugins.Length]; int i = 0; foreach (var plugin in plugins) { hows[i] = plugin.How; i++; } Config.Hows = string.Join(",", hows); } catch (Exception ex) { throw new Exception($"Errors.ERROR_LOADING_GATEWAY, ex: {ex.Message}"); } }
private void _ButtonClick(object sender, RoutedEventArgs e) { try { var compositionBatch = new CompositionBatch(); compositionBatch.AddExportedValue <IPluginPart>(new DynamicPart(new SquarePart())); compositionBatch.AddExportedValue <IPluginPart>(new DynamicPart(new TextPart())); _mainContainer.Compose(compositionBatch); if (_directoryCatalog == null) { _directoryCatalog = new DirectoryCatalog(Directory.GetCurrentDirectory()); _mainCatalog.Catalogs.Add(_directoryCatalog); } else { _directoryCatalog.Refresh(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public App() { var catalog = new DirectoryCatalog(Environment.CurrentDirectory); var container = new CompositionContainer(catalog); var bootstrapper = new DelegateBootstrapper(() => {}, container.Dispose); _bootstrapper = bootstrapper.InitalizeModules(container) .CatchDispatcherExceptions(this, ex => { _logger.Error(ex); return(true); }) .CatchTaskExceptions(ex => { _logger.Error(ex); return(true); }) .CatchAppDomainExceptions(AppDomain.CurrentDomain, (ex, handled) => { _logger.Error(ex); }); }
public static CompositionContainer regisgter() { lock (obj) { try { AggregateCatalog aggregateCatalog = new AggregateCatalog(); string path = AppDomain.CurrentDomain.BaseDirectory; var thisAssembly = new DirectoryCatalog(path, "*.dll"); if (thisAssembly.Count() == 0) { path = path + "bin\\"; thisAssembly = new DirectoryCatalog(path, "*.dll"); } aggregateCatalog.Catalogs.Add(thisAssembly); var _container = new CompositionContainer(aggregateCatalog); return(_container); } catch (Exception ex) { return(null); } } }
private void LoadPlugins() { logger.Info("load plugins"); var folders = new HashSet <string>(); var catalog = new AggregateCatalog(new ApplicationCatalog()); var spDir = new DirectoryInfo(AppSettings.ShadowedPluginsFullPath); foreach (var dir in spDir.GetDirectories()) { var subCatalog = new DirectoryCatalog(dir.FullName); catalog.Catalogs.Add(subCatalog); folders.Add(dir.FullName); } AppDomain.CurrentDomain.SetupInformation.PrivateBinPath = string.Join(";", folders); var container = new CompositionContainer(catalog); container.SatisfyImportsOnce(this); }
void AddOutPlugins() { // Plugin目录 var dir = EngineNS.CEngine.Instance.FileManager.Bin + "Plugins"; if (System.IO.Directory.Exists(dir)) { var cata = new DirectoryCatalog(dir); mCatalog.Catalogs.Add(cata); foreach (var subDir in System.IO.Directory.GetDirectories(dir)) { try { var tagDir = subDir.Replace("\\", "/"); // 优先选择bin目录下的文件 foreach (var testDir in System.IO.Directory.GetDirectories(tagDir)) { var tempDir = testDir.Replace("\\", "/"); if (tempDir == tagDir + "/bin") { tagDir = tempDir; break; } } cata = new DirectoryCatalog(tagDir); mCatalog.Catalogs.Add(cata); } catch (System.Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); } } } }
public PluginManagerSI() { try { Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory); var catalog = new DirectoryCatalog(@".\", "*.plg.dll"); var container = new CompositionContainer(catalog); var batch = new CompositionBatch(); batch.AddPart(this); container.Compose(batch); PlgItem?.Initialize(null); } catch (ReflectionTypeLoadException ee) { var li = new LogItem { App = "wsDataBaseSync", Stacktrace = ee.GetStackTrace(5), Message = ee.GetAllMessages(), Method = "PluginManagerSI" }; CLogJson.Write(li); } }
public MultiDirectoryCatalog(IEnumerable <string> directories, string searchPattern = "*.dll") { this.searchPattern = searchPattern; this.directories = new ObservableCollection <string>(); directoryCatalogs = new Collection <DirectoryCatalog>(); foreach (string directory in directories) { this.directories.Add(directory); } var directoriesToScan = directories.Concat(directories.Where(d => Directory.Exists(d)) .SelectMany(d => Directory.GetDirectories(d, "*", SearchOption.AllDirectories))) .Distinct().ToArray(); foreach (var directory in directoriesToScan) { if (Directory.Exists(directory) && Directory.GetFiles(directory, "*.dll").Length > 0) { DirectoryCatalog catalog = new DirectoryCatalog(directory, searchPattern); directoryCatalogs.Add(catalog); } } }
/// <summary> /// Dynamically imports available plugins. /// </summary> public void Import() { string pluginsAbsolutePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), _pluginsFolder); if (!Directory.Exists(pluginsAbsolutePath)) { System.Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "Plugins directory does not exist! \n\t{0}", pluginsAbsolutePath)); return; } _parsers = new List <ISolutionParser>(); using (ComposablePartCatalog catalog = new DirectoryCatalog(pluginsAbsolutePath)) { using (CompositionContainer cc = new CompositionContainer(catalog)) { cc.ComposeParts(this); Initialized = true; } } }
public static CompositionContainer Reg(string path = "") { lock (Obj) { try { var aggregateCatalog = new AggregateCatalog(); path = path.IsNullOrEmpty() ? AppDomain.CurrentDomain.BaseDirectory : path; var thisAssembly = new DirectoryCatalog(path, "*.dll"); //if (!thisAssembly.Any()) //{ // path = path + "bin\\"; // thisAssembly = new DirectoryCatalog(path, "*.dll"); //} aggregateCatalog.Catalogs.Add(thisAssembly); var container = new CompositionContainer(aggregateCatalog); return(container); } catch (Exception) { return(null); } } }
private void Initialize() { Log.Info("Starting MEF Composition"); var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var dllsCatalog = new DirectoryCatalog(path, "*.dll"); var exeCatalog = new DirectoryCatalog(path, "*.exe"); MefContainer = new CompositionContainer(new AggregateCatalog(dllsCatalog, exeCatalog)); Log.Info("Finished MEF Composition. Number of Parts: {0}", MefContainer.Catalog.Parts.Count()); Log.Info("List of Parts -- Begin"); MefContainer.Catalog.Parts.ForEach(c => Log.Info(c.ToString())); Log.Info("List of Parts -- End"); // Push commandline arguments to the container. MefContainer.ComposeExportedValue(new CommandLineArguments { Arguments = _args }); PerformApplicatoinStartupTasks(); }
protected override void Configure() { DirectoryCatalog directoryCatalog = new DirectoryCatalog(@"./"); AssemblySource.Instance.AddRange( directoryCatalog.Parts.Select(p => ReflectionModelServices.GetPartType(p).Value.Assembly) ); AggregateCatalog catalog = new AggregateCatalog(AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType <ComposablePartCatalog>()); CatalogExportProvider provider = new CatalogExportProvider(catalog); Container = new CompositionContainer(new ApplicationCatalog()); provider.SourceProvider = Container; CompositionBatch batch = new CompositionBatch(); batch.AddExportedValue <IWindowManager>(new WindowManager()); batch.AddExportedValue <IEventAggregator>(new EventAggregator()); batch.AddExportedValue(Container); batch.AddExportedValue(catalog); batch.AddExportedValue(this); Container.Compose(batch); }
/// <summary> /// Configures the <see cref="AggregateCatalog"/> used by MEF. /// </summary> protected override void ConfigureAggregateCatalog() { this.UpdateBootstrapperState("Configuring catalogs"); base.ConfigureAggregateCatalog(); var currentAssemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); if (currentAssemblyPath == null) { throw new InvalidOperationException("Cannot find directory path for " + Assembly.GetExecutingAssembly().FullName); } var sw = new Stopwatch(); sw.Start(); this.UpdateBootstrapperState("Loading CDP4 Catalogs"); var dllCatalog = new DirectoryCatalog(path: currentAssemblyPath, searchPattern: "CDP4*.dll"); this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(CDP4IMEBootstrapper).Assembly)); this.AggregateCatalog.Catalogs.Add(dllCatalog); this.UpdateBootstrapperState($"CDP4 Catalogs loaded in: {sw.ElapsedMilliseconds} [ms]"); }
static PluginManager() { Logger.Debug("Creating"); using (DirectoryCatalog catalog = new DirectoryCatalog(Path.Combine(Directory.GetCurrentDirectory(), "Plugins"), "TAS.Server.*.dll")) { var container = new CompositionContainer(catalog); container.ComposeExportedValue("AppSettings", ConfigurationManager.AppSettings); try { _enginePlugins = container.GetExportedValues <IEnginePluginFactory>(); } catch (ReflectionTypeLoadException e) { foreach (var loaderException in e.LoaderExceptions) { Logger.Error(e, "Plugin load exception: {0}", loaderException); } } catch (Exception e) { Logger.Error(e, "Plugin load failed: {0}", e); } } }
public void Configure() { var priorityAssemblies = SelectAssemblies().ToList(); var priorityCatalog = new AggregateCatalog(priorityAssemblies.Select(x => new AssemblyCatalog(x))); var priorityProvider = new CatalogExportProvider(priorityCatalog); var path = Path.GetDirectoryName( new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath); var codecCatalog = new DirectoryCatalog(path); var codecProvider = new CatalogExportProvider(codecCatalog); Container = new CompositionContainer(priorityProvider, codecProvider); priorityProvider.SourceProvider = Container; codecProvider.SourceProvider = Container; var batch = new CompositionBatch(); batch.AddExportedValue(Container); Container.Compose(batch); IoC.GetInstance = GetInstance; IoC.GetAllInstances = GetAllInstances; }
/// <summary> /// Creates a composition container using the specified assembly path. /// </summary> /// <param name="assemblyPath">The assembly path.</param> /// <returns>The composition container instance.</returns> public static IContainer Create(string assemblyPath = ".") { var catalog = new DirectoryCatalog(assemblyPath, _defaultAssemblySearchPattern); return(Create(new AggregateCatalog(catalog), catalog.FullPath)); }
public void Initialize() { try { RegisterChummerProtocol(); if (GlobalOptions.PluginsEnabled == false) { Log.Info("Plugins are globally disabled - exiting PluginControl.Initialize()"); return; } Log.Info("Plugins are globally enabled - entering PluginControl.Initialize()"); string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins"); if (!Directory.Exists(path)) { string msg = "Directory " + path + " not found. No Plugins will be available."; MyPlugins = new List <IPlugin>(); throw new ArgumentException(msg); } catalog = new AggregateCatalog(); var plugindirectories = Directory.GetDirectories(path); if (!plugindirectories.Any()) { throw new ArgumentException("No Plugin-Subdirectories in " + path + " !"); } foreach (var plugindir in plugindirectories) { Log.Trace("Searching in " + plugindir + " for plugin.txt or dlls containing the interface."); //search for a textfile, that tells me what dll to parse string infofile = Path.Combine(plugindir, "plugin.txt"); if (File.Exists(infofile)) { Log.Trace(infofile + " found: parsing it!"); System.IO.StreamReader file = new System.IO.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); myDirectoryCatalog = new DirectoryCatalog(path: plugindir, searchPattern: fi.Name); Log.Info("Searching for plugin-interface in dll: " + plugindll); catalog.Catalogs.Add(myDirectoryCatalog); } else { Log.Warn("Could not find dll from " + infofile + ": " + plugindll); myDirectoryCatalog = new DirectoryCatalog(path: plugindir, searchPattern: "*.dll"); myDirectoryCatalog = new DirectoryCatalog(path: plugindir, searchPattern: "*.dll"); Log.Info("Searching for dlls in path " + myDirectoryCatalog?.FullPath); catalog.Catalogs.Add(myDirectoryCatalog); } } file.Close(); } else { myDirectoryCatalog = new DirectoryCatalog(path: plugindir, searchPattern: "*.dll"); Log.Info("Searching for dlls in path " + myDirectoryCatalog?.FullPath); catalog.Catalogs.Add(myDirectoryCatalog); } } container = new CompositionContainer(catalog); //Fill the imports of this object StartWatch(); container.ComposeParts(this); Log.Info("Plugins found: " + MyPlugins.Count()); if (!MyPlugins.Any()) { throw new ArgumentException("No plugins found in " + path + "."); } Log.Info("Plugins active: " + MyActivePlugins.Count()); foreach (var plugin in MyActivePlugins) { try { Log.Info("Initializing Plugin " + plugin.ToString()); plugin.SetIsUnitTest(Utils.IsUnitTest); plugin.CustomInitialize(Program.MainForm); } catch (ApplicationException e) { throw; } catch (Exception e) { Log.Error(e); } } 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) { if (e is ApplicationException) { throw; } Log.Fatal(e); throw; } }
/// <summary> /// Refresh the plugin catalog. /// </summary> public void Load() { // Check if environmental settings are correct: if (!Directory.Exists(PluginDirectory)) { throw new PluginHostException("Could not find plug-in directory!"); } if (Simulators != null || Widgets != null || Extensions != null) { throw new PluginHostException("Can only load plug-ins from a clean set of lists."); } var simulatorsToDrop = new List <IPluginSimulator>(); var widgetsToDrop = new List <IPluginWidget>(); var extensionsToDrop = new List <IPluginExtension>(); Simulators = new List <IPluginSimulator>(); Widgets = new List <IPluginWidget>(); Extensions = new List <IPluginExtension>(); // Try to refresh DLL's from the plugin directory: try { PluginCatalog = new DirectoryCatalog(PluginDirectory, "SimTelemetry.Plugins.*.dll"); PluginCatalog.Refresh(); PluginContainer = new CompositionContainer(PluginCatalog); PluginContainer.ComposeParts(this); } catch (ReflectionTypeLoadException ex) { foreach (var exc in ex.LoaderExceptions) { GlobalEvents.Fire(new DebugWarning("Error whilst importing plugin namespaces; the following type couldn't be loaded correctly.", exc), false); } throw new PluginHostException("Could not initialize plug-ins!", ex); } catch (CompositionException ex) { foreach (var exc in ex.Errors) { GlobalEvents.Fire(new DebugWarning("Error whilst importing plugin namespaces; the following type couldn't be loaded correctly.", exc.Exception), false); } throw new PluginHostException("Could not initialize plug-ins!", ex); } catch (Exception ex) { throw new PluginHostException("Could not initialize plug-ins!", ex); } if (Simulators == null) { throw new PluginHostException("Simulators aren't properly initialized"); } if (Widgets == null) { throw new PluginHostException("Widgets aren't properly initialized"); } if (Extensions == null) { throw new PluginHostException("Extensions aren't properly initialized"); } // Initialize all plug-ins foreach (var sim in Simulators) { string simName = "??"; try { simName = sim.Name; sim.Initialize(); } catch (Exception ex) { simulatorsToDrop.Add(sim); GlobalEvents.Fire(new DebugWarning("Unloading simulator plugin '" + simName + "' (assembly " + ex.Source + "), exception was thrown during initialize()", ex), false); } } Simulators = Simulators.Where(x => !simulatorsToDrop.Contains(x)).ToList(); foreach (var widget in Widgets) { string widgetName = "??"; try { widgetName = widget.Name; widget.Initialize(); } catch (Exception ex) { widgetsToDrop.Add(widget); GlobalEvents.Fire(new DebugWarning("Unloading widget plugin '" + widgetName + "' (assembly " + ex.Source + "), exception was thrown during initialize()", ex), false); } } Widgets = Widgets.Where(x => !widgetsToDrop.Contains(x)).ToList(); foreach (var ext in Extensions) { string extName = "??"; try { extName = ext.Name; ext.Initialize(); } catch (Exception ex) { extensionsToDrop.Add(ext); GlobalEvents.Fire(new DebugWarning("Unloading extension plugin '" + extName + "' (assembly " + ex.Source + "), exception was thrown during initialize()", ex), false); } } Extensions = Extensions.Where(x => !extensionsToDrop.Contains(x)).ToList(); // Fire PluginsLoaded event var loadEvent = new PluginsLoaded { Simulators = Simulators, Widgets = Widgets, Extensions = Extensions, FailedSimulators = simulatorsToDrop, FailedWidgets = widgetsToDrop, FailedExtensions = extensionsToDrop }; GlobalEvents.Fire(loadEvent, true); }
public void Constructor_InvalidAssembly_ShouldBeFine() { using (File.CreateText(Path.Combine(TemporaryFileCopier.GetTemporaryDirectory(), "Test.dll"))) { } var cat = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory()); }
public void LoadedFiles_EmptyDirectory_ShouldBeFine() { var cat = new DirectoryCatalog(TemporaryFileCopier.GetTemporaryDirectory()); Assert.Equal(0, cat.LoadedFiles.Count); }
private void Compose() { AfterglowRuntime.Logger.Info("Loading Plugins..."); string folder = Path.Combine((new FileInfo(System.Reflection.Assembly.GetEntryAssembly().Location)).Directory.FullName, PLUGINS_DIRECTORY); var catalog = new DirectoryCatalog(folder); var container = new CompositionContainer(catalog); try { container.ComposeParts(this); AfterglowRuntime.Logger.Info("The following plugins were loaded"); if (LightSetupPlugins != null && LightSetupPlugins.Any()) { LightSetupPluginTypes.ToList().ForEach(p => AfterglowRuntime.Logger.Info("Type: Light Setup Plugin Name: {0}", p.Name)); } else { AfterglowRuntime.Logger.Fatal("No Light Setup Plugins were loaded"); } if (CapturePlugins != null && CapturePlugins.Any()) { CapturePluginTypes.ToList().ForEach(p => AfterglowRuntime.Logger.Info("Type: Capture Plugin Name: {0}", p.Name)); } else { AfterglowRuntime.Logger.Fatal("No Capture Plugins were loaded"); } if (ColourExtractionPlugins != null && ColourExtractionPlugins.Any()) { ColourExtractionPluginTypes.ToList().ForEach(p => AfterglowRuntime.Logger.Info("Type: Colour Extraction Plugin Name: {0}", p.Name)); } else { AfterglowRuntime.Logger.Info("No Colour Extraction Plugins were loaded"); } if (PostProcessPlugins != null && PostProcessPlugins.Any()) { PostProcessPluginTypes.ToList().ForEach(p => AfterglowRuntime.Logger.Info("Type: Post Process Plugin Name: {0}", p.Name)); } else { AfterglowRuntime.Logger.Info("No Post Process Plugins were loaded"); } if (PreOutputPlugins != null && PreOutputPlugins.Any()) { PreOutputPluginTypes.ToList().ForEach(p => AfterglowRuntime.Logger.Info("Type: Pre Output Plugin Name: {0}", p.Name)); } else { AfterglowRuntime.Logger.Info("No Pre Output Plugins were loaded"); } if (OutputPlugins != null && OutputPlugins.Any()) { OutputPluginTypes.ToList().ForEach(p => AfterglowRuntime.Logger.Info("Type: Output Plugin Name: {0}", p.Name)); } else { AfterglowRuntime.Logger.Fatal("No Output Plugins were loaded"); } } catch (System.Reflection.ReflectionTypeLoadException reflectionTypeLoadException) { foreach (Exception exception in reflectionTypeLoadException.LoaderExceptions) { AfterglowRuntime.Logger.Fatal(exception, "Plugin Loader"); } } finally { AfterglowRuntime.Logger.Info("Plugin Loading Complete"); } }
private IEnumerable <InfoRuleState> GetInfoRules() { IEnumerable <IInfoRule> validatorPlugs = null; using (var catalog = new DirectoryCatalog(Path.Combine(_acDomain.GetPluginBaseDirectory(PluginType.InfoConstraint), "Bin"))) { using (var container = new CompositionContainer(catalog)) { var infoRuleImport = new InfoRuleImport(); infoRuleImport.ImportsSatisfied += (sender, e) => { validatorPlugs = e.InfoRules; }; container.ComposeParts(infoRuleImport); } } var infoRuleRepository = _acDomain.RetrieveRequiredService <IRepository <InfoRule, Guid> >(); var oldEntities = infoRuleRepository.AsQueryable().ToList(); var deleteList = new List <InfoRule>(); var newList = new List <InfoRule>(); var infoRules = new List <InfoRuleState>(); var entities = new List <InfoRule>(); bool saveChanges = false; foreach (var item in validatorPlugs) { var entity = new InfoRule(item.Id) { IsEnabled = 0 }; var oldEntity = oldEntities.FirstOrDefault(a => a.Id == item.Id); if (oldEntity != null) { ((IEntityBase)entity).CreateBy = oldEntity.CreateBy; ((IEntityBase)entity).CreateOn = oldEntity.CreateOn; ((IEntityBase)entity).CreateUserId = oldEntity.CreateUserId; entity.IsEnabled = oldEntity.IsEnabled; ((IEntityBase)entity).ModifiedBy = oldEntity.ModifiedBy; ((IEntityBase)entity).ModifiedOn = oldEntity.ModifiedOn; ((IEntityBase)entity).ModifiedUserId = oldEntity.ModifiedUserId; } entities.Add(entity); infoRules.Add(InfoRuleState.Create(entity, item)); } // 待添加的新的 foreach (var item in entities) { var item1 = item; var old = oldEntities.FirstOrDefault(a => a.Id == item1.Id); if (old == null) { newList.Add(item); } } // 待移除的旧的 foreach (var oldEntity in oldEntities) { var item2 = oldEntity; var entity = entities.FirstOrDefault(a => a.Id == item2.Id); if (entity == null) { deleteList.Add(oldEntity); } } if (newList.Count > 0) { saveChanges = true; foreach (var item in newList) { infoRuleRepository.Context.RegisterNew(item); } } if (deleteList.Count > 0) { saveChanges = true; foreach (var item in deleteList) { infoRuleRepository.Context.RegisterDeleted(item); } } if (saveChanges) { using (var coordinator = TransactionCoordinatorFactory.Create(infoRuleRepository.Context, _acDomain.EventBus)) { coordinator.Commit(); } } return(infoRules); }
public CompositionContainer(DirectoryCatalog catalog) { }