public void Process(PluginLoadContext context) { try { foreach (var field in context.PluginType.GetFields()) { var translationattribute = field.GetCustomAttribute <SynapseTranslation>(); if (translationattribute == null) { continue; } if (!FieldInfo.GetFieldFromHandle(field.FieldHandle).FieldType.Name.Contains("SynapseTranslation")) { continue; } if (field.GetValue(context.Plugin) == null) { var translation = Activator.CreateInstance(FieldInfo.GetFieldFromHandle(field.FieldHandle).FieldType, new object[] { Server.Get.Files.GetTranslationPath(context.Information.Name) }); field.SetValue(context.Plugin, translation); } else { field.FieldType.GetMethod("Reload").Invoke(field.GetValue(context.Plugin), new object[] { }); } } foreach (var property in context.PluginType.GetProperties()) { var translationattribute = property.GetCustomAttribute <SynapseTranslation>(); if (translationattribute == null) { continue; } if (property.Name.Contains("SynapseTranslation")) { continue; } if (property.GetValue(context.Plugin) == null) { var translation = Activator.CreateInstance(property.PropertyType, new object[] { Server.Get.Files.GetTranslationPath(context.Information.Name) }); property.SetValue(context.Plugin, translation); } else { property.PropertyType.GetMethod("Reload").Invoke(property.GetValue(context.Plugin), new object[] { }); } } } catch (Exception e) { SynapseController.Server.Logger.Error($"Synapse-Injector: Injecting Config failed!!\n{e}"); throw; } }
public async Task LoadPluginAssembly_Guard_Works() { var testContext = SetupAssemblyLoadContext(); var loadContext = testContext.Sut(); var fileSystemUtility = testContext.GetMock <IFileSystemUtilities>(); var pluginAssemblyPath = "/var/home/MyPluginAssembly.dll"; var pluginDependencyContextProvider = testContext.GetMock <IPluginDependencyContextProvider>(); var pluginDependencyContext = testContext.GetMock <IPluginDependencyContext>(); var contract = TestableTypeBuilder.New() .WithName("IMyTestType") .WithNamespace("Test.Type") .Build(); var assembly = this.GetType().Assembly; var assemblyStream = File.OpenRead(assembly.Location); fileSystemUtility.Setup(f => f.EnsureFileExists(pluginAssemblyPath)).Returns(pluginAssemblyPath); fileSystemUtility.Setup(f => f.ReadFileFromDisk(pluginAssemblyPath)).ReturnsAsync(assemblyStream); var pluginLoadContext = new PluginLoadContext(pluginAssemblyPath, contract, "netcoreapp3.1"); pluginDependencyContextProvider.Setup(p => p.FromPluginLoadContext(pluginLoadContext)).ReturnsAsync(pluginDependencyContext.Object); var priseAssembly = await loadContext.LoadPluginAssembly(pluginLoadContext); await Assert.ThrowsExceptionAsync <AssemblyLoadingException>(() => loadContext.LoadPluginAssembly(pluginLoadContext)); }
internal PluginContainer HandlePlugin(PluginLoadContext loadContext, Assembly assembly, string path, ILogger logger) { Type pluginType = assembly.GetTypes().FirstOrDefault(type => type.IsSubclassOf(typeof(PluginBase))); PluginBase plugin; if (pluginType == null || pluginType.GetConstructor(Array.Empty <Type>()) == null) { plugin = default; logger?.LogError("Loaded assembly contains no type implementing PluginBase with public parameterless constructor."); return(new PluginContainer(new PluginInfo(Path.GetFileNameWithoutExtension(path)), path)); } else { logger?.LogInformation("Creating plugin instance..."); plugin = (PluginBase)Activator.CreateInstance(pluginType); } string name = assembly.GetName().Name; var attribute = pluginType.GetCustomAttribute <PluginAttribute>(); var info = attribute != null ? new PluginInfo(name, attribute) : new PluginInfo(name); if (attribute == null) { logger?.LogWarning($"Plugin is missing {nameof(PluginAttribute)}. Name defaults to '{info.Name}', version defaults to {info.Version}."); } return(new PluginContainer(plugin, info, assembly, loadContext, path)); }
protected IPluginLoadContext GetPluginLoadContext(string pluginAssemblyPath, Action <PluginLoadContext> configure = null) { var pluginLoadContext = new PluginLoadContext(pluginAssemblyPath, GetContractType(), "netcoreapp3.1"); configure?.Invoke(pluginLoadContext); return(pluginLoadContext); }
public async Task Load_UnRooted_PathToAssembly_Throws_ArgumentNullException() { var testContext = SetupAssemblyLoadContext(); var loadContext = testContext.Sut(); var pluginLoadContext = new PluginLoadContext("../testpath", this.GetType(), "netcoreapp3.1"); await Assert.ThrowsExceptionAsync <AssemblyLoadingException>(() => loadContext.LoadPluginAssembly(pluginLoadContext)); }
public PluginContainer GetPlugin(string path, ILogger logger) { var loadContext = new PluginLoadContext(Path.GetFileNameWithoutExtension(path) + "LoadContext", path); var assembly = loadContext.LoadFromAssemblyPath(path); return(HandlePlugin(loadContext, assembly, path, logger)); }
public Assembly LoadPlugin(string path) { if (string.IsNullOrEmpty(path)) { throw new ArgumentException($"'{nameof(path)}' cannot be null or empty.", nameof(path)); } string v = Path.GetFullPath(Path.Combine( Path.GetDirectoryName( Path.GetDirectoryName( Path.GetDirectoryName( Path.GetDirectoryName( Path.GetDirectoryName(typeof(Program).Assembly.Location))))))); var root = v; string v1 = Path.GetFullPath(Path.Combine(root, path.Replace('\\', Path.DirectorySeparatorChar))); string pluginLocation = v1; _logger.LogInfo($"Loading plugin from: {pluginLocation}"); PluginLoadContext loadContext = new PluginLoadContext(pluginLocation); loadContext.GetType(); Assembly assembly = loadContext.LoadFromAssemblyName(new AssemblyName(Path.GetFileNameWithoutExtension(pluginLocation))); var loaded = assembly; return(loaded); }
/// <summary> /// Helper method to load an assembly which contains a single plugin /// </summary> /// <param name="pluginLocation">string</param> /// <returns>IPlugin</returns> private static IPlugin LoadPlugin(string pluginLocation) { if (!File.Exists(pluginLocation)) { Console.WriteLine($"Can't find: {pluginLocation}"); return(null); } Console.WriteLine($"Loading plugin from: {pluginLocation}"); var loadContext = new PluginLoadContext(pluginLocation); var assembly = loadContext.LoadFromAssemblyName(new AssemblyName(Path.GetFileNameWithoutExtension(pluginLocation))); var interfaceType = typeof(IPlugin); foreach (var type in assembly.GetExportedTypes()) { if (!type.GetInterfaces().Contains(interfaceType)) { continue; } var plugin = Activator.CreateInstance(type) as IPlugin; return(plugin); } return(null); }
/// <summary> /// Helper method to load an assembly which contains plugins /// </summary> /// <param name="pluginBuilder">IPluginBuilder</param> /// <param name="pluginAssemblyLocation">string</param> /// <returns>IPlugin</returns> private static Assembly LoadPlugin(IPluginBuilder pluginBuilder, string pluginAssemblyLocation) { if (!File.Exists(pluginAssemblyLocation)) { // TODO: Log an error, how to get a logger here? return(null); } // This allows validation like AuthenticodeExaminer if (!pluginBuilder.ValidatePlugin(pluginAssemblyLocation)) { return(null); } // TODO: Log verbose that we are loading a plugin var pluginName = Path.GetFileNameWithoutExtension(pluginAssemblyLocation); // TODO: Decide if we rather have this to come up with the name: AssemblyName.GetAssemblyName(pluginLocation) var pluginAssemblyName = new AssemblyName(pluginName); if (AssemblyLoadContext.Default.TryGetAssembly(pluginAssemblyName, out _)) { return(null); } var loadContext = new PluginLoadContext(pluginAssemblyLocation, pluginName); return(loadContext.LoadFromAssemblyName(pluginAssemblyName)); }
internal static Assembly LoadPluginAssembly(this FileInfo file) { var loadContext = new PluginLoadContext(file.FullName); var assembly = loadContext.LoadFromAssemblyPath(file.FullName); return(assembly); }
protected PluginLoadContext ToPluginLoadContext <T>(AssemblyScanResult plugin) { var hostFramework = HostFrameworkUtils.GetHostframeworkFromHost(); var pathToAssembly = Path.Combine(plugin.AssemblyPath, plugin.AssemblyName); return(PluginLoadContext.DefaultPluginLoadContext(pathToAssembly, typeof(T), hostFramework)); }
private Type?LoadType() { if (TypeName == null) { throw new ArgumentNullException(nameof(TypeName), "The type name must be specified"); } if (AssemblyName == null) { throw new ArgumentNullException(nameof(TypeName), "The assembly name must be specified"); } if (string.IsNullOrWhiteSpace(AssemblyPath)) { var assemblies = AppDomain.CurrentDomain.GetAssemblies(); var assembly = assemblies.First(x => x.GetName().Name == AssemblyName); var type = assembly.GetType(TypeName); return(type); } else { var loadContext = new PluginLoadContext(AssemblyPath); var assembly = loadContext.LoadFromAssemblyName(new AssemblyName(AssemblyName)); var type = assembly.GetType(TypeName); return(type); } }
public async Task Unload_No_PathToAssembly_Throws_ArgumentNullException() { var loader = new DefaultAssemblyLoader(() => null); var loadContext = new PluginLoadContext("Path To Plugin", this.GetType(), "netcoreapp3.1"); loadContext.FullPathToPluginAssembly = null; await Assert.ThrowsExceptionAsync <ArgumentNullException>(() => loader.Unload(loadContext)); }
public void Process(PluginLoadContext context) { try { foreach (var field in context.PluginType.GetFields()) { var configAttribute = field.GetCustomAttribute <Config>(); if (configAttribute == null) { continue; } var section = configAttribute.section; Type t = FieldInfo.GetFieldFromHandle(field.FieldHandle).FieldType; if (section == null) { section = t.FullName?.Replace(".", " "); } if (!typeof(IConfigSection).IsAssignableFrom(t)) { continue; } object typeObj = Activator.CreateInstance(t); object config = SynapseController.Server.Configs.GetOrSetDefault(section, typeObj); field.SetValue(context.Plugin, config); } foreach (var property in context.PluginType.GetProperties()) { var configAttribute = property.GetCustomAttribute <Config>(); if (configAttribute == null) { continue; } var section = configAttribute.section; Type t = property.PropertyType; if (section == null) { section = t.FullName?.Replace(".", " "); } if (!typeof(IConfigSection).IsAssignableFrom(t)) { continue; } object typeObj = Activator.CreateInstance(t); object config = SynapseController.Server.Configs.GetOrSetDefault(section, typeObj); property.SetValue(context.Plugin, config); } } catch (Exception e) { SynapseController.Server.Logger.Error($"Synapse-Injector: Injecting Config failed!!\n{e}"); throw; } }
public IActionResult GenericPost([FromBody] GenericRequest request) { Log.Debug("BEGUN: Start Post Method"); IEFTPlugin plugin; var response = new GenericResponse() { Payload = request.PayLoad, Info = request.Info, Result = new Result() { ErrorCode = "", OperationType = request.OperationType, } }; //var operation = DictionaryExtensions.DictionaryToObject<Operation>(request.PayLoad.AdditionalInfo); //operation.CashierID = request.PayLoad.CashierID; //operation.CurrencyCode = request.PayLoad.CurrencyCode; //operation.SessionId = request.PayLoad.SessionId; //operation.OperationType = request.OperationType; try { _plugins = PluginLoadContext.ReadExtensions(Config); plugin = _plugins; var infoPlugin = plugin.GetInfo(); response.Info.PluginInfo = infoPlugin; if (!infoPlugin.Capabilities.Any(x => x.ToLower() == request.OperationType.ToLower())) { response.Result.Status = "Error"; response.Result.ResponseCode = "Operation not supported"; Log.Fatal("END: Operation not supported by plugin"); return(BadRequest(JsonConvert.SerializeObject(response))); } else { if (synch) { Log.Debug("END: Post Method"); return(Post(request, response, plugin)); } else { Log.Debug("END: Post Method"); return(PostAsync(request, response, plugin)); } } } catch (Exception e) { Log.Fatal("END: Error ", e); return(BadRequest(JsonConvert.SerializeObject(response))); } }
private Assembly LoadPluginAssembly(string path) { string pluginLocation = path.Replace('\\', Path.DirectorySeparatorChar); _logger.LogDebug($"Loading assembly file: {pluginLocation}"); PluginLoadContext loadContext = new PluginLoadContext(pluginLocation); return(loadContext.LoadFromAssemblyName(new AssemblyName(Path.GetFileNameWithoutExtension(pluginLocation)))); }
static void Main(string[] args) { var aaa = Path.GetFullPath(Path.Combine(typeof(Program).Assembly.Location, @"../../../../../NLogTest/bin/Debug/netcoreapp3.1/NLogTest.dll")); var loader = new PluginLoadContext(aaa); var ass = loader.LoadFromAssemblyPath(aaa); var pg2 = ass.GetType("NLogTest.Program"); pg2.GetMethod("Main", BindingFlags.Static | BindingFlags.NonPublic).Invoke(null, new object[] { Array.Empty <string>() }); }
public async Task Load_No_PathToAssembly_Throws_ArgumentNullException() { var testContext = SetupAssemblyLoadContext(); var loadContext = testContext.Sut(); var pluginLoadContext = new PluginLoadContext("Path To Plugin", this.GetType(), "netcoreapp3.1"); pluginLoadContext.FullPathToPluginAssembly = null; await Assert.ThrowsExceptionAsync <ArgumentNullException>(() => loadContext.LoadPluginAssembly(pluginLoadContext)); }
internal static Assembly LoadPlugin(string relativePath) { var root = GetRoot(); string pluginLocation = Path.GetFullPath(Path.Combine(root, relativePath.Replace('\\', Path.DirectorySeparatorChar))); Debug.Log($"Loading commands from: {pluginLocation}"); PluginLoadContext loadContext = new PluginLoadContext(pluginLocation); return(loadContext.LoadFromAssemblyName(new AssemblyName(Path.GetFileNameWithoutExtension(pluginLocation)))); }
public Tuple <PluginLoadContext, IEnumerable <Assembly> > GetAssembliesAndLoadContext(string path) { var pluginLoadContext = new PluginLoadContext(); var assemblies = Directory .EnumerateFiles(path, "*.dll", SearchOption.AllDirectories) .Select(pluginLoadContext.LoadFromAssemblyPath) .Distinct(); return(new Tuple <PluginLoadContext, IEnumerable <Assembly> >(pluginLoadContext, assemblies)); }
public static IMvcBuilder AddPluginFutures(this IMvcBuilder mvcBuilder, IHostEnvironment environment) { var pluginContext = new PluginContext(); var pluginsFolder = Path.Combine(environment.ContentRootPath, pluginFolderName); foreach (var dir in Directory.GetDirectories(pluginsFolder)) { var pluginFolder = Path.GetFileName(dir); var pluginAssemblyPath = Path.Combine(dir, pluginFolder + assemblyFileExtension); if (!File.Exists(pluginAssemblyPath)) continue; var pluginManifestFile = Path.Combine(dir, pluginManifestName); if (!File.Exists(pluginManifestFile)) continue; PluginInfo pluginInfo = null; using (var reader = new StreamReader(pluginManifestFile)) { string content = reader.ReadToEnd(); pluginInfo = JsonSerializer.Deserialize<PluginInfo>(content); } if (pluginInfo == null) continue; var pluginLoadContext = new PluginLoadContext(pluginAssemblyPath); pluginInfo.Assembly = pluginLoadContext.LoadDefaultAssembly(); pluginContext.Plugins.Add(pluginInfo); var partFactory = ApplicationPartFactory.GetApplicationPartFactory(pluginInfo.Assembly); foreach (var part in partFactory.GetApplicationParts(pluginInfo.Assembly)) { mvcBuilder.PartManager.ApplicationParts.Add(part); } // This piece finds and loads related parts, such as WebPlugin1.Views.dll var relatedAssembliesAttrs = pluginInfo.Assembly.GetCustomAttributes<RelatedAssemblyAttribute>(); foreach (var attr in relatedAssembliesAttrs) { var assembly = pluginLoadContext.LoadFromAssemblyName(new AssemblyName(attr.AssemblyFileName)); partFactory = ApplicationPartFactory.GetApplicationPartFactory(assembly); foreach (var part in partFactory.GetApplicationParts(assembly)) { mvcBuilder.PartManager.ApplicationParts.Add(part); } } } mvcBuilder.Services.AddSingleton(pluginContext); return mvcBuilder; }
public Tuple <PluginLoadContext, Assembly> GetAssemblyAndLoadContext(string path) { var pluginLoadContext = new PluginLoadContext(); var assembly = pluginLoadContext.LoadFromAssemblyPath(path); if (assembly is null) { throw new PluginException($"[{nameof(GetAssemblyAndLoadContext)}] Error: Could not load the assembly under the given path: {path}"); } return(new Tuple <PluginLoadContext, Assembly>(pluginLoadContext, assembly)); }
public PluginContainer GetPlugin(string path, ILogger logger) { string name = Path.GetFileNameWithoutExtension(path); FileStream fileStream; try { fileStream = File.OpenRead(path); } catch { logger.LogError($"Reloading '{Path.GetFileName(path)}' failed, file is not accessible."); return(new PluginContainer(new PluginInfo(name), name)); } SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(SourceText.From(fileStream)); fileStream.Dispose(); var compilation = CSharpCompilation.Create(name, new[] { syntaxTree }, MetadataReferences, CompilationOptions); using var memoryStream = new MemoryStream(); EmitResult emitResult = compilation.Emit(memoryStream); if (!emitResult.Success) { if (logger != null) { foreach (var diagnostic in emitResult.Diagnostics) { if (diagnostic.Severity != DiagnosticSeverity.Error || diagnostic.IsWarningAsError) { continue; } logger.LogError($"Compilation failed: {diagnostic.Location} {diagnostic.GetMessage()}"); } } return(new PluginContainer(new PluginInfo(name), name)); } else { memoryStream.Seek(0, SeekOrigin.Begin); var loadContext = new PluginLoadContext(name + "LoadContext", path); var assembly = loadContext.LoadFromStream(memoryStream); return(PluginProviderSelector.CompiledPluginProvider.HandlePlugin(loadContext, assembly, path, logger)); } }
public async Task Load_Works() { var mockLoadContext = this.mockRepository.Create <IAssemblyLoadContext>(); var assemblyShim = this.mockRepository.Create <IAssemblyShim>(); var loader = new DefaultAssemblyLoader(() => mockLoadContext.Object); var loadContext = new PluginLoadContext("/home/maarten/assembly.dll", this.GetType(), "netcoreapp3.1"); mockLoadContext.Setup(c => c.LoadPluginAssembly(loadContext)).ReturnsAsync(assemblyShim.Object); var assembly = await loader.Load(loadContext); Assert.AreEqual(assemblyShim.Object, assembly); }
public void CreateRunnableInstance(ScheduleContext context) { loadContext = AssemblyHelper.LoadAssemblyContext(context.Schedule.Id, context.Schedule.AssemblyName); RunnableInstance = AssemblyHelper.CreateTaskInstance( loadContext, context.Schedule.Id, context.Schedule.AssemblyName, context.Schedule.ClassName ); if (RunnableInstance == null) { throw new InvalidCastException($"任务实例创建失败,请确认目标任务是否派生自TaskBase类型。程序集:{context.Schedule.AssemblyName},类型:{context.Schedule.ClassName}"); } }
/// <summary> /// Load existing plugin assembly /// </summary> /// <param name="pluginPath">Path for loading the plugin assembly</param> /// <returns>Assembly or null</returns> static Assembly LoadPlugin(string pluginPath) { // An assembly is the compiled output of your code, typically a DLL. It's the smallest unit of deployment for any .NET project. PluginLoadContext loadContext = new PluginLoadContext(pluginPath); // check if file is available/exists if (File.Exists(pluginPath)) { return(loadContext.LoadFromAssemblyName(new AssemblyName(Path.GetFileNameWithoutExtension(pluginPath)))); } else { return(null); } }
public void GetInfo_ShouldReturnPluginInfoIfExist() { ConfigureWithoutBindMethod(); try { _plugins = PluginLoadContext.ReadExtensions(Config); } catch (Exception e) { } ConfigureWithoutBindMethod(); var infoPlugin = _plugins.GetInfo(); Assert.IsNotNull(infoPlugin); }
protected IList <TPluginType> LoadDataPluginsFromDlls <TPluginType>(string[] pluginPaths) where TPluginType : class, IBasePlugin { var loadedPlugins = new List <TPluginType>(); foreach (var pluginPath in pluginPaths) { _logger.LogInformation($"Loading Data plugins from {pluginPath}."); PluginLoadContext loadContext = new PluginLoadContext(pluginPath); var pluginAssembly = loadContext.LoadFromAssemblyName(new AssemblyName(Path.GetFileNameWithoutExtension(pluginPath))); loadedPlugins.AddRange(LoadDataPluginsFromAssembly <TPluginType>(pluginAssembly)); } _logger.LogInformation("Loading plugins completed."); return(loadedPlugins); }
public void Process(PluginLoadContext context) { foreach (var @class in context.Classes) { if (!typeof(ISynapseCommand).IsAssignableFrom(@class)) { continue; } var inf = @class.GetCustomAttribute <CommandInformation>(); if (inf == null) { continue; } var classObject = Activator.CreateInstance(@class); Handlers.RegisterCommand(classObject as ISynapseCommand, true); } }
static Assembly LoadPlugin(string relativePath) { // Navigate up to the solution root string root = Path.GetFullPath(Path.Combine( Path.GetDirectoryName( Path.GetDirectoryName( Path.GetDirectoryName( Path.GetDirectoryName( Path.GetDirectoryName(typeof(Program).Assembly.Location))))))); string pluginLocation = Path.GetFullPath(Path.Combine(root, relativePath.Replace('\\', Path.DirectorySeparatorChar))); Console.WriteLine($"Loading commands from: {pluginLocation}"); PluginLoadContext loadContext = new PluginLoadContext(pluginLocation); return(loadContext.LoadFromAssemblyName(new AssemblyName(Path.GetFileNameWithoutExtension(pluginLocation)))); }