public CollectibleAssemblyLoadContext Get(string moduleName, IServiceCollection services, ApplicationPartManager apm, IServiceScope scope, InBizModuleEnum inBizModuleEnum = InBizModuleEnum.Boot)
        {
            string folderName = inBizModuleEnum == InBizModuleEnum.Boot ? "boot" : "hot";
            CollectibleAssemblyLoadContext context = new CollectibleAssemblyLoadContext(moduleName);
            IReferenceLoader  loader              = scope.ServiceProvider.GetService <IReferenceLoader>();
            InBizModuleLoader inBizModuleLoader   = scope.ServiceProvider.GetService <InBizModuleLoader>();
            string            filePath            = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "modules", folderName, moduleName, $"{moduleName}.dll");
            string            viewFilePath        = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "modules", folderName, moduleName, $"{moduleName}.Views.dll");
            string            referenceFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "modules", folderName, moduleName);

            if (File.Exists(filePath))
            {
                using (FileStream fs = new FileStream(filePath, FileMode.Open))
                {
                    Assembly assembly = context.LoadFromStream(fs);
                    context.SetEntryPoint(assembly);
                    loader.LoadStreamsIntoContext(context, referenceFolderPath, assembly);
                    AssemblyPart controllerAssemblyPart = new AssemblyPart(assembly);
                    apm.ApplicationParts.Add(controllerAssemblyPart);
                    //services.AddAssembly(assembly);
                    foreach (var type in assembly.GetTypes())
                    {
                        if (AbpModule.IsAbpModule(type))
                        {
                            inBizModuleLoader.LoadModules(services, type, new PlugInSourceList());
                            inBizModuleLoader.ConfigureServices(services);
                            inBizModuleLoader.InitializeModules(new Volo.Abp.ApplicationInitializationContext(scope.ServiceProvider));
                        }
                    }
                    var resources = assembly.GetManifestResourceNames();
                    if (resources.Any())
                    {
                        foreach (var item in resources)
                        {
                            var stream = new MemoryStream();
                            var source = assembly.GetManifestResourceStream(item);
                            source.CopyTo(stream);
                            context.RegisterResource(item, stream.ToArray());
                        }
                    }
                }
            }
            else
            {
                return(null);
            }
            if (File.Exists(viewFilePath))
            {
                using (FileStream fsView = new FileStream(viewFilePath, FileMode.Open))
                {
                    Assembly vwAssembly = context.LoadFromStream(fsView);
                    loader.LoadStreamsIntoContext(context, referenceFolderPath, vwAssembly);

                    InBizRazorAssemblyPart moduleView = new InBizRazorAssemblyPart(vwAssembly, moduleName);
                    apm.ApplicationParts.Add(moduleView);
                }
            }
            context.Enable();
            return(context);
        }
Esempio n. 2
0
 public DynamicComponentEntry()
 {
     className = "";
     context   = null;
     assembly  = null;
     type      = null;
 }
Esempio n. 3
0
 public DynamicComponentEntry(string _className, CollectibleAssemblyLoadContext _context, Assembly _assembly, System.Type _type)
 {
     className = _className;
     context   = _context;
     assembly  = _assembly;
     type      = _type;
 }
        private bool IsAssemblyValid()
        {
            AssemblyLoadContext assemblyLoadContext = new CollectibleAssemblyLoadContext();

            try
            {
                Assembly plugin;
                try
                {
                    plugin = PluginTester.LoadPlugin(assemblyLoadContext, Model.FileGuid);
                }
                catch (Exception e)
                {
                    Toaster.Error($"Vložený soubor není platná knihovna. ({e.Message})");
                    return(false);
                }

                try
                {
                    PluginTester.TestImplementation(plugin);
                }
                catch (Exception e)
                {
                    Toaster.Error(e.Message, "Chyba implementace");
                    return(false);
                }
            }
            finally
            {
                assemblyLoadContext.Unload();
            }

            return(true);
        }
Esempio n. 5
0
        public void EnableModule(string moduleName)
        {
            if (!PluginsLoadContexts.Any(moduleName))
            {
                var context = new CollectibleAssemblyLoadContext();

                var filePath            = $"{AppDomain.CurrentDomain.BaseDirectory}Modules\\{moduleName}\\{moduleName}.dll";
                var referenceFolderPath = $"{AppDomain.CurrentDomain.BaseDirectory}Modules\\{moduleName}";
                using (var fs = new FileStream(filePath, FileMode.Open))
                {
                    var assembly = context.LoadFromStream(fs);


                    DefaultReferenceLoader loader = new DefaultReferenceLoader(referenceFolderPath, $"{moduleName}.dll");
                    loader.LoadStreamsIntoContext(context);


                    var controllerAssemblyPart = new MystiqueAssemblyPart(assembly);

                    AdditionalReferencePathHolder.AdditionalReferencePaths.Add(filePath);
                    _partManager.ApplicationParts.Add(controllerAssemblyPart);
                    PluginsLoadContexts.AddPluginContext(moduleName, context);
                }
            }
            else
            {
                var context = PluginsLoadContexts.GetContext(moduleName);
                var controllerAssemblyPart = new MystiqueAssemblyPart(context.Assemblies.First());
                _partManager.ApplicationParts.Add(controllerAssemblyPart);
            }

            ResetControllActions();
        }
        public T CSharpScriptEvaluate <T>(string lambda)
        {
            var returnTypeAsString = GetCSharpRepresentation(typeof(T), true);
            var outerClass         = StandardHeader + $"public static class Wrapper {{ public static {returnTypeAsString} expr = {lambda}; }}";

            var compilation = CSharpCompilation.Create("FilterCompiler_" + Guid.NewGuid(),
                                                       new[] { CSharpSyntaxTree.ParseText(outerClass) },
                                                       References,
                                                       new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using var assemblyLoadContext = new CollectibleAssemblyLoadContext();
            using var ms = new MemoryStream();

            var cr = compilation.Emit(ms);

            if (!cr.Success)
            {
                throw new InvalidOperationException("Error in expression: " + cr.Diagnostics.First(e =>
                                                                                                   e.Severity == DiagnosticSeverity.Error).GetMessage());
            }

            ms.Seek(0, SeekOrigin.Begin);
            var assembly = assemblyLoadContext.LoadFromStream(ms);

            var outerClassType = assembly.GetType("Wrapper");

            var exprField = outerClassType.GetField("expr", BindingFlags.Public | BindingFlags.Static);

            // ReSharper disable once PossibleNullReferenceException
            return((T)exprField.GetValue(null));
        }
        /// <summary>
        /// Loads the auto-detect plug-in from assembly file.
        /// </summary>
        /// <param name="detectorAssembly">File name</param>
        public void Load(string detectorAssembly)
        {
            // Get CustomerInterface
            Type interfaceType = typeof(IValueDetector);

            AssemblyLoadContext alc = new CollectibleAssemblyLoadContext();
            string assembleDirPath  = Directory.GetParent(detectorAssembly).FullName;

            alc.Resolving += (context, assembleName) =>
            {
                string assemblyPath = Path.Combine(assembleDirPath, $"{assembleName.Name}.dll");
                if (assemblyPath != null)
                {
                    return(context.LoadFromAssemblyPath(assemblyPath));
                }
                return(null);
            };

            Assembly assembly = alc.LoadFromAssemblyPath(detectorAssembly);

            Type[] types = assembly.GetTypes();

            // Find a class that implement Customer Interface
            foreach (Type type in types)
            {
                if (type.IsClass && interfaceType.IsAssignableFrom(type) == true)
                {
                    detectorInstanceTypeName = type.FullName;
                    break;
                }
            }
            alc.Unload();
        }
        public List <IMigration> GetAllMigrations(string connectionString)
        {
            var context      = new CollectibleAssemblyLoadContext();
            var assemblyPath = $"{_tempFolderName}/{_pluginConfiguration.Name}.dll";

            using (var fs = new FileStream(assemblyPath, FileMode.Open, FileAccess.Read))
            {
                var dbHelper       = new DbHelper(connectionString);
                var assembly       = context.LoadFromStream(fs);
                var migrationTypes = assembly.ExportedTypes.Where(p => p.GetInterfaces().Contains(typeof(IMigration)));

                List <IMigration> migrations = new List <IMigration>();
                foreach (var migrationType in migrationTypes)
                {
                    var constructor = migrationType.GetConstructors().First(p => p.GetParameters().Count() == 1 && p.GetParameters()[0].ParameterType == typeof(DbHelper));

                    migrations.Add((IMigration)constructor.Invoke(new object[] { dbHelper }));
                }

                context.Unload();

                GC.Collect();
                GC.WaitForPendingFinalizers();

                return(migrations.OrderBy(p => p.Version).ToList());
            }
        }
Esempio n. 9
0
        public void EnableModule(string moduleName)
        {
            if (!PluginsLoadContexts.Any(moduleName))
            {
                CollectibleAssemblyLoadContext context = new CollectibleAssemblyLoadContext(moduleName);

                string filePath            = $"{AppDomain.CurrentDomain.BaseDirectory}Modules\\{moduleName}\\{moduleName}.dll";
                string referenceFolderPath = $"{AppDomain.CurrentDomain.BaseDirectory}Modules\\{moduleName}";
                using (FileStream fs = new FileStream(filePath, FileMode.Open))
                {
                    System.Reflection.Assembly assembly = context.LoadFromStream(fs);
                    _referenceLoader.LoadStreamsIntoContext(context, referenceFolderPath, assembly);

                    MystiqueAssemblyPart controllerAssemblyPart = new MystiqueAssemblyPart(assembly);

                    AdditionalReferencePathHolder.AdditionalReferencePaths.Add(filePath);
                    _partManager.ApplicationParts.Add(controllerAssemblyPart);
                    PluginsLoadContexts.Add(moduleName, context);
                }
            }
            else
            {
                CollectibleAssemblyLoadContext context = PluginsLoadContexts.Get(moduleName);
                MystiqueAssemblyPart           controllerAssemblyPart = new MystiqueAssemblyPart(context.Assemblies.First());
                _partManager.ApplicationParts.Add(controllerAssemblyPart);
            }

            ResetControllActions();
        }
Esempio n. 10
0
        public List <IMigration> GetAllMigrations(string connectionString)
        {
            CollectibleAssemblyLoadContext context = new CollectibleAssemblyLoadContext(_pluginConfiguration.Name);
            string assemblyPath = Path.Combine(_tempFolderName, $"{_pluginConfiguration.Name}.dll");

            using (FileStream fs = new FileStream(assemblyPath, FileMode.Open, FileAccess.Read))
            {
                System.Reflection.Assembly assembly       = context.LoadFromStream(fs);
                IEnumerable <Type>         migrationTypes = assembly.ExportedTypes.Where(p => p.GetInterfaces().Contains(typeof(IMigration)));

                List <IMigration> migrations = new List <IMigration>();
                foreach (Type migrationType in migrationTypes)
                {
                    System.Reflection.ConstructorInfo constructor = migrationType.GetConstructors().First(p => p.GetParameters().Count() == 1 && p.GetParameters()[0].ParameterType == typeof(IDbHelper));

                    migrations.Add((IMigration)constructor.Invoke(new object[] { _dbHelper }));
                }

                context.Unload();

                GC.Collect();
                GC.WaitForPendingFinalizers();

                return(migrations.OrderBy(p => p.Version).ToList());
            }
        }
Esempio n. 11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOptions();

            services.Configure <ConnectionStringSetting>(Configuration.GetSection("ConnectionStringSetting"));

            services.AddScoped <IPluginManager, PluginManager>();
            services.AddScoped <IUnitOfWork, UnitOfWork>();

            var mvcBuilders = services.AddMvc()
                              .AddRazorRuntimeCompilation(o =>
            {
                foreach (var item in _presets)
                {
                    o.AdditionalReferencePaths.Add(item);
                }

                AdditionalReferencePathHolder.AdditionalReferencePaths = o.AdditionalReferencePaths;
            });

            services.Configure <RazorViewEngineOptions>(o =>
            {
                o.AreaViewLocationFormats.Add("/Modules/{2}/Views/{1}/{0}" + RazorViewEngine.ViewExtension);
                o.AreaViewLocationFormats.Add("/Views/Shared/{0}.cshtml");
            });

            services.AddSingleton <IActionDescriptorChangeProvider>(MyActionDescriptorChangeProvider.Instance);
            services.AddSingleton(MyActionDescriptorChangeProvider.Instance);

            var provider = services.BuildServiceProvider();

            using (var scope = provider.CreateScope())
            {
                var option = scope.ServiceProvider.GetService <MvcRazorRuntimeCompilationOptions>();


                var unitOfWork        = scope.ServiceProvider.GetService <IUnitOfWork>();
                var allEnabledPlugins = unitOfWork.PluginRepository.GetAllEnabledPlugins();

                foreach (var plugin in allEnabledPlugins)
                {
                    var context    = new CollectibleAssemblyLoadContext();
                    var moduleName = plugin.Name;
                    var filePath   = $"{AppDomain.CurrentDomain.BaseDirectory}Modules\\{moduleName}\\{moduleName}.dll";

                    _presets.Add(filePath);
                    using (var fs = new FileStream(filePath, FileMode.Open))
                    {
                        var assembly = context.LoadFromStream(fs);

                        var controllerAssemblyPart = new MyAssemblyPart(assembly);

                        mvcBuilders.PartManager.ApplicationParts.Add(controllerAssemblyPart);
                        PluginsLoadContexts.AddPluginContext(plugin.Name, context);
                    }
                }
            }
        }
Esempio n. 12
0
        public static void MystiqueSetup(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddSingleton <IMvcModuleSetup, MvcModuleSetup>();
            services.AddScoped <IPluginManager, PluginManager>();
            services.AddSingleton <IActionDescriptorChangeProvider>(ActionDescriptorChangeProvider.Instance);
            services.AddSingleton <IReferenceContainer, DefaultReferenceContainer>();
            services.AddSingleton <IReferenceLoader, DefaultReferenceLoader>();
            services.AddSingleton(ActionDescriptorChangeProvider.Instance);

            var mvcBuilder = services.AddMvc();

            var provider = services.BuildServiceProvider();

            using (var scope = provider.CreateScope())
            {
                var pluginManager     = scope.ServiceProvider.GetService <IPluginManager>();
                var allEnabledPlugins = pluginManager.GetAllEnabledPlugins();
                var loader            = scope.ServiceProvider.GetService <IReferenceLoader>();

                foreach (var plugin in allEnabledPlugins)
                {
                    var context             = new CollectibleAssemblyLoadContext();
                    var moduleName          = plugin.Name;
                    var filePath            = $"{AppDomain.CurrentDomain.BaseDirectory}Modules\\{moduleName}\\{moduleName}.dll";
                    var referenceFolderPath = $"{AppDomain.CurrentDomain.BaseDirectory}Modules\\{moduleName}";

                    _presets.Add(filePath);
                    using (var fs = new FileStream(filePath, FileMode.Open))
                    {
                        // LoadFromAssemblyPath改成了LoadFromStream
                        var assembly = context.LoadFromStream(fs);
                        loader.LoadStreamsIntoContext(context, referenceFolderPath, assembly);

                        var controllerAssemblyPart = new MyAssemblyPart(assembly);
                        mvcBuilder.PartManager.ApplicationParts.Add(controllerAssemblyPart);
                        PluginsLoadContexts.AddPluginContext(plugin.Name, context);
                    }
                }
            }

            //Razor视图的运行时编译
            mvcBuilder.AddRazorRuntimeCompilation(o =>
            {
                foreach (var item in _presets)
                {
                    o.AdditionalReferencePaths.Add(item);
                }
                AdditionalReferencePathHolder.AdditionalReferencePaths = o.AdditionalReferencePaths;
            });

            services.Configure <RazorViewEngineOptions>(o =>
            {
                o.AreaViewLocationFormats.Add("/Modules/{2}/Views/{1}/{0}" + RazorViewEngine.ViewExtension);
                o.AreaViewLocationFormats.Add("/Views/Shared/{0}.cshtml");
            });
        }
Esempio n. 13
0
 private void unloadAssemblyLoadContext()
 {
     if (bundleAssemblyLoadContext != null)
     {
         bundleAssemblyLoadContext.Unload();
         bundleAssemblyLoadContext = null;
         GC.Collect();
         GC.WaitForPendingFinalizers();
     }
 }
Esempio n. 14
0
        public void DisableModule(string moduleName)
        {
            ApplicationPart last = _partManager.ApplicationParts.First(p => p.Name == moduleName);

            _partManager.ApplicationParts.Remove(last);

            CollectibleAssemblyLoadContext context = PluginsLoadContexts.Get(moduleName);

            context.Disable();

            ResetControllActions();
        }
Esempio n. 15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddOptions();


            services.Configure <ConnectionStringSetting>(Configuration.GetSection("ConnectionStringSetting"));

            services.AddScoped <IPluginManager, PluginManager>();
            services.AddScoped <IUnitOfWork, UnitOfWork>();

            var mvcBuilders = services.AddMvc();

            mvcBuilders.AddMvcOptions(o => o.EnableEndpointRouting = false);

            services.Configure <RazorViewEngineOptions>(o =>
            {
                o.AreaViewLocationFormats.Add("/Modules/{2}/Views/{1}/{0}" + RazorViewEngine.ViewExtension);
                o.AreaViewLocationFormats.Add("/Views/Shared/{0}.cshtml");
            });

            services.AddSingleton <IActionDescriptorChangeProvider>(MyActionDescriptorChangeProvider.Instance);
            services.AddSingleton(MyActionDescriptorChangeProvider.Instance);

            var provider = services.BuildServiceProvider();

            using (var scope = provider.CreateScope())
            {
                var unitOfWork        = scope.ServiceProvider.GetService <IUnitOfWork>();
                var allEnabledPlugins = unitOfWork.PluginRepository.GetAllEnabledPlugins();

                foreach (var plugin in allEnabledPlugins)
                {
                    var context    = new CollectibleAssemblyLoadContext();
                    var moduleName = plugin.Name;
                    using (var fs = new FileStream($"{AppDomain.CurrentDomain.BaseDirectory}Modules\\{moduleName}\\{moduleName}.dll", FileMode.Open))
                    {
                        var assembly = context.LoadFromStream(fs);
                        var controllerAssemblyPart = new AssemblyPart(assembly);
                        mvcBuilders.PartManager.ApplicationParts.Add(controllerAssemblyPart);
                    }

                    PluginsLoadContexts.AddPluginContext(plugin.Name, context);
                }
            }
        }
        public CollectibleAssemblyLoadContext Get(string moduleName, IMvcBuilder mvcBuilder, IServiceScope scope, IDataStore dataStore, IQueryDocumentation documentation)
        {
            CollectibleAssemblyLoadContext context = new CollectibleAssemblyLoadContext(moduleName);
            IReferenceLoader loader = scope.ServiceProvider.GetService <IReferenceLoader>();

            string filePath            = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Modules", moduleName, $"{moduleName}.dll");
            string viewFilePath        = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Modules", moduleName, $"{moduleName}.Views.dll");
            string referenceFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Modules", moduleName);

            using (FileStream fs = new FileStream(filePath, FileMode.Open))
            {
                Assembly assembly = context.LoadFromStream(fs);

                context.SetEntryPoint(assembly);

                loader.LoadStreamsIntoContext(context, referenceFolderPath, assembly);

                AssemblyPart controllerAssemblyPart = new AssemblyPart(assembly);
                mvcBuilder.PartManager.ApplicationParts.Add(controllerAssemblyPart);


                var resources = assembly.GetManifestResourceNames();

                if (resources.Any())
                {
                    foreach (var item in resources)
                    {
                        var stream = new MemoryStream();
                        var source = assembly.GetManifestResourceStream(item);
                        source.CopyTo(stream);

                        context.RegisterResource(item, stream.ToArray());
                    }
                }

                BuildNotificationProvider(assembly, scope);
                RegisterModuleQueries(dataStore, moduleName, assembly, scope, documentation);
            }

            using (FileStream fsView = new FileStream(viewFilePath, FileMode.Open))
            {
                Assembly viewAssembly = context.LoadFromStream(fsView);
                loader.LoadStreamsIntoContext(context, referenceFolderPath, viewAssembly);

                CoolCatRazorAssemblyPart moduleView = new CoolCatRazorAssemblyPart(viewAssembly, moduleName);
                mvcBuilder.PartManager.ApplicationParts.Add(moduleView);
            }

            context.Enable();

            return(context);
        }
        public async Task <List <Game> > NewTournamentAsync(League league)
        {
            var context = new CollectibleAssemblyLoadContext();

            var competitors = await GetCompetitorsAsync(context, league);

            var games = GetGames(competitors);

            context.Unload();

            RunGames(games);

            return(games);
        }
Esempio n. 18
0
        private static void HandleModuleLoadEvent(IServiceProvider serviceProvider, CollectibleAssemblyLoadContext context)
        {
            #region 加载插件实体类
            var daoFactories = serviceProvider.GetServices <IDaoFactory>();
            foreach (var factory in daoFactories)
            {
                if (context.PluginContext.PluginEntityAssemblies.ContainsKey(factory.FactoryName))
                {
                    factory.AddExtraEntityAssemblies(context.PluginContext.PluginEntityAssemblies[factory.FactoryName].ToArray());
                }
            }

            #endregion
        }
Esempio n. 19
0
        public void LoadStreamsIntoContext(CollectibleAssemblyLoadContext context)
        {
            var streams       = new List <Stream>();
            var di            = new DirectoryInfo(_folderName);
            var allReferences = di.GetFiles("*.dll").Where(p => p.Name != _excludeFile);

            foreach (var file in allReferences)
            {
                using (var sr = new StreamReader(file.OpenRead()))
                {
                    context.LoadFromStream(sr.BaseStream);
                }
            }
        }
Esempio n. 20
0
        public void LoadStreamsIntoContext(CollectibleAssemblyLoadContext context, string moduleFolder, Assembly assembly)
        {
            AssemblyName[] references = assembly.GetReferencedAssemblies();

            foreach (AssemblyName item in references)
            {
                string name = item.Name;

                string version = item.Version.ToString();

                Stream stream = _referenceContainer.GetStream(name, version);

                if (stream != null)
                {
                    _logger.LogDebug($"Found the cached reference '{name}' v.{version}");
                    context.LoadFromStream(stream);
                }
                else
                {
                    if (IsSharedFreamwork(name) || name.Contains("CoolCat.Core"))
                    {
                        continue;
                    }

                    string dllName  = $"{name}.dll";
                    string filePath = $"{moduleFolder}/{dllName}";

                    if (!File.Exists(filePath))
                    {
                        _logger.LogWarning($"The package '{dllName}' in '{filePath}' is missing.");
                        continue;
                    }

                    using (FileStream fs = new FileStream(filePath, FileMode.Open))
                    {
                        Assembly referenceAssembly = context.LoadFromStream(fs);

                        MemoryStream memoryStream = new MemoryStream();

                        fs.Position = 0;
                        fs.CopyTo(memoryStream);
                        fs.Position           = 0;
                        memoryStream.Position = 0;
                        _referenceContainer.SaveStream(name, version, memoryStream);

                        LoadStreamsIntoContext(context, moduleFolder, referenceAssembly);
                    }
                }
            }
        }
Esempio n. 21
0
 public void FreeResources()
 {
     try
     {
         bool isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
         if (isWindows == false)
         {
             context?.Unload();
         }
         context  = null;
         assembly = null;
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex);
     }
 }
Esempio n. 22
0
        async Task <Option <T, string>[]> IExecutionService.Execute <T>(CompileResult compileResult, string className, string funcName, object[][] args, Type[] paramTypes)
        {
            using (var dll = new MemoryStream(compileResult.Dll))
                using (var pdb = new MemoryStream(compileResult.Pdb))
                {
                    var context = new CollectibleAssemblyLoadContext();
                    var obj     = context.LoadFromStream(dll, pdb);
                    var type    = obj.GetType(className);
                    var inst    = Activator.CreateInstance(type);
                    var fun     = GetMethod(funcName, type);
                    var r       = await Task.WhenAll(
                        args.Select(
                            async a =>
                    {
                        var castArgs     = CastArgs(a, paramTypes).ToArray();
                        using var source = new CancellationTokenSource();
                        source.CancelAfter(TimeSpan.FromMilliseconds(ExecutionTimeoutMilliseconds));
                        try
                        {
                            return(Optional.Option.Some <T, string>(
                                       await Task <T> .Factory.StartNew(
                                           () => (T)fun.Invoke(
                                               inst,
                                               BindingFlags.Default | BindingFlags.InvokeMethod,
                                               null,
                                               castArgs.Append(source.Token).ToArray(),
                                               CultureInfo.InvariantCulture),
                                           source.Token,
                                           TaskCreationOptions.None,
                                           TaskScheduler.Current)));
                        }
                        catch (Exception e)
                        {
                            var final = GetFinalException(e);
                            var line  = new StackTrace(final, true).GetFrame(0).GetFileLineNumber();
                            return(Optional.Option.None <T, string>(
                                       $"Runtime Error line {line} - {final.Message}"));
                        }
                    }));

                    context.Unload();
                    return(r);
                }
        }
Esempio n. 23
0
        public void EnableModule(string moduleName)
        {
            if (!PluginsLoadContexts.Any(moduleName))
            {
                CollectibleAssemblyLoadContext context = new CollectibleAssemblyLoadContext(moduleName);

                var filePath            = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Modules", moduleName, $"{moduleName}.dll");
                var viewFilePath        = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Modules", moduleName, $"{moduleName}.Views.dll");
                var referenceFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Modules", moduleName);
                using (FileStream fs = new FileStream(filePath, FileMode.Open))
                {
                    var assembly = context.LoadFromStream(fs);
                    _referenceLoader.LoadStreamsIntoContext(context, referenceFolderPath, assembly);

                    context.SetEntryPoint(assembly);

                    var controllerAssemblyPart = new MystiqueAssemblyPart(assembly);

                    AdditionalReferencePathHolder.AdditionalReferencePaths.Add(filePath);
                    _partManager.ApplicationParts.Add(controllerAssemblyPart);
                    PluginsLoadContexts.Add(moduleName, context);
                    context.Enable();
                }

                using (FileStream fsView = new FileStream(viewFilePath, FileMode.Open))
                {
                    var viewAssembly = context.LoadFromStream(fsView);
                    _referenceLoader.LoadStreamsIntoContext(context, referenceFolderPath, viewAssembly);

                    var moduleView = new MystiqueRazorAssemblyPart(viewAssembly, moduleName);
                    _partManager.ApplicationParts.Add(moduleView);
                }
            }
            else
            {
                var context = PluginsLoadContexts.Get(moduleName);
                var controllerAssemblyPart = new MystiqueAssemblyPart(context.Assemblies.First());
                _partManager.ApplicationParts.Add(controllerAssemblyPart);
                context.Enable();
            }

            ResetControllActions();
        }
Esempio n. 24
0
        // Create a weak reference to the AssemblyLoadContext that will allow us to detect when the unload completes.
        public static void ExecuteAssembly(out WeakReference alcWeakRef)
        {
            var context = new CollectibleAssemblyLoadContext();

            alcWeakRef = new WeakReference(context);
            {
                var assemblyPath = Path.Combine(Directory.GetCurrentDirectory(), "NetCore3Collectible.dll");
                var assembly     = context.LoadFromAssemblyPath(assemblyPath);
                var type         = assembly.GetType("NetCore3Collectible.CollectibleInstrumented");
                var instance     = Activator.CreateInstance(type);
                var GetDistributedTracePayload = type.GetMethod("GetDistributedTracePayload", BindingFlags.Instance | BindingFlags.Public);
                var result = GetDistributedTracePayload?.Invoke(instance, null); //instance method, no parameters
                if (null == result)
                {
                    throw new Exception("NetCore3Collectible.CollectibleInstrumented.GetDistributedTracePayload returned a null");
                }
            }
            context.Unload();
        }
Esempio n. 25
0
        public void CollectibleTypeTest()
        {
            CollectibleAssemblyLoadContext context = new CollectibleAssemblyLoadContext();

            RuntimeHelpers.RunClassConstructor(context.LoadFromAssemblyPath(Assembly.GetExecutingAssembly().Location)
                                               .GetType(typeof(CollectibleUnmanagedStruct).FullName).TypeHandle);

            RuntimeHelpers.RunClassConstructor(Assembly.GetExecutingAssembly()
                                               .GetType(typeof(UncollectibleUnmanagedStruct).FullName).TypeHandle);

            using DataTarget dataTarget = DataTarget.CreateSnapshotAndAttach(Process.GetCurrentProcess().Id);

            ClrHeap heap = dataTarget.ClrVersions.Single(v => v.ModuleInfo.FileName.EndsWith("coreclr.dll", true, null)).CreateRuntime().Heap;

            ClrType[] types = heap.EnumerateObjects().Select(obj => obj.Type).ToArray();

            ClrType collectibleType = types.Single(type => type?.Name == typeof(CollectibleUnmanagedStruct).FullName);

            Assert.False(collectibleType.ContainsPointers);
            Assert.True(collectibleType.IsCollectible);
            Assert.NotEqual(default, collectibleType.LoaderAllocatorHandle);
Esempio n. 26
0
        public void resolve()
        {
            requiredBundleList = new List <BundleImpl>();
            loadRequiredBundle();

            this.activatorClassName = null;
            unloadAssemblyLoadContext();
            bundleAssemblyLoadContext            = new CollectibleAssemblyLoadContext($"Bundle[Id:{getBundleId()}, Name:{getSymbolicName()}] AssemblyLoadContext");
            bundleAssemblyLoadContext.Resolving += BundleAssemblyLoadContext_Resolving;
            bundleAssemblyLoadContext.Unloading += BundleAssemblyLoadContext_Unloading;
            loadAssemblys();
            this.activatorClassName = FindBundleActivatorClassName();
            if (this.activatorClassName != null)
            {
                headerDictionary.Add("Activator", activatorClassName);
            }

            //解析Bundle完成
            this.state = Bundle_Const.RESOLVED;
            framework.fireBundleEvent(new BundleEvent(BundleEvent.RESOLVED, this));
        }
Esempio n. 27
0
        public void CollectibleTypeTest()
        {
            CollectibleAssemblyLoadContext context = new CollectibleAssemblyLoadContext();

            RuntimeHelpers.RunClassConstructor(context.LoadFromAssemblyPath(Assembly.GetExecutingAssembly().Location)
                                               .GetType(typeof(CollectibleUnmanagedStruct).FullName).TypeHandle);

            RuntimeHelpers.RunClassConstructor(Assembly.GetExecutingAssembly()
                                               .GetType(typeof(UncollectibleUnmanagedStruct).FullName).TypeHandle);

            using DataTarget dataTarget = DataTarget.AttachToProcess(Process.GetCurrentProcess().Id, uint.MaxValue, AttachFlag.Passive);

            ClrHeap heap = dataTarget.ClrVersions.Single().CreateRuntime().Heap;

            ClrType[] types = heap.EnumerateObjectAddresses().Select(addr => heap.GetObjectType(addr)).ToArray();

            ClrType collectibleType = types.Single(type => type?.Name == typeof(CollectibleUnmanagedStruct).FullName);

            Assert.False(collectibleType.ContainsPointers);
            Assert.True(collectibleType.IsCollectible);
            Assert.NotEqual(default, collectibleType.LoaderAllocatorObject);
Esempio n. 28
0
        public IActionResult Enable(Guid id)
        {
            var module = _pluginManager.GetPlugin(id);

            if (!PluginsLoadContexts.Any(module.Name))
            {
                var context = new CollectibleAssemblyLoadContext();

                _pluginManager.EnablePlugin(id);
                var moduleName = module.Name;

                var filePath = $"{AppDomain.CurrentDomain.BaseDirectory}Modules\\{moduleName}\\{moduleName}.dll";
                using (var fs = new FileStream(filePath, FileMode.Open))
                {
                    var assembly = context.LoadFromStream(fs);

                    var controllerAssemblyPart = new MyAssemblyPart(assembly);

                    AdditionalReferencePathHolder.AdditionalReferencePaths.Add(filePath);
                    _partManager.ApplicationParts.Add(controllerAssemblyPart);
                }

                MyActionDescriptorChangeProvider.Instance.HasChanged = true;
                MyActionDescriptorChangeProvider.Instance.TokenSource.Cancel();

                PluginsLoadContexts.AddPluginContext(module.Name, context);
            }
            else
            {
                var context = PluginsLoadContexts.GetContext(module.Name);
                var controllerAssemblyPart = new AssemblyPart(context.Assemblies.First());
                _partManager.ApplicationParts.Add(controllerAssemblyPart);
                _pluginManager.EnablePlugin(id);

                MyActionDescriptorChangeProvider.Instance.HasChanged = true;
                MyActionDescriptorChangeProvider.Instance.TokenSource.Cancel();
            }

            return(RedirectToAction("Index"));
        }
Esempio n. 29
0
        public void LoadStreamsIntoContext(CollectibleAssemblyLoadContext context, string moduleFolder, Assembly assembly)
        {
            var references = assembly.GetReferencedAssemblies();

            foreach (var item in references.Where(x => !SharedFrameworkConst.SharedFrameworkDLLs.Contains($"{x.Name}.dll")))
            {
                var name    = item.Name;
                var version = item.Version.ToString();
                var stream  = referenceContainer.GetStream(name, version);
                if (stream != null)
                {
                    logger.LogDebug($"Found the cached reference '{name}' v.{version}");
                    context.LoadFromStream(stream);
                    continue;
                }

                var filePath = Path.Combine(moduleFolder, $"{name}.dll");
                if (!File.Exists(filePath))
                {
                    logger.LogWarning($"The package '{name}.dll' is missing. {filePath} not exist");
                    continue;
                }

                using (var fs = new FileStream(filePath, FileMode.Open))
                {
                    var referenceAssembly = context.LoadFromStream(fs);
                    var memoryStream      = new MemoryStream();

                    fs.Position = 0;
                    fs.CopyTo(memoryStream);
                    fs.Position           = 0;
                    memoryStream.Position = 0;
                    referenceContainer.SaveStream(name, version, memoryStream);

                    LoadStreamsIntoContext(context, moduleFolder, referenceAssembly);
                }
            }
        }
Esempio n. 30
0
        public static List <PageRouteViewModel> GetPages(this CollectibleAssemblyLoadContext context)
        {
            var entryPointAssembly = context.GetEntryPointAssembly();
            var result             = new List <PageRouteViewModel>();

            if (entryPointAssembly == null)
            {
                return(result);
            }

            var areaName = context.PluginName;

            var types = entryPointAssembly.GetExportedTypes().Where(p => p.BaseType == typeof(Controller));

            if (types.Any())
            {
                foreach (var type in types)
                {
                    var controllerName = type.Name.Replace("Controller", "");

                    var actions = type.GetMethods().Where(p => p.GetCustomAttributes(false).Any(x => x.GetType() == typeof(Page))).ToList();

                    foreach (var action in actions)
                    {
                        var actionName = action.Name;

                        var pageAttribute = (Page)action.GetCustomAttributes(false).First(p => p.GetType() == typeof(Page));
                        result.Add(new PageRouteViewModel(pageAttribute.Name, areaName, controllerName, actionName));
                    }
                }

                return(result);
            }
            else
            {
                return(result);
            }
        }