Example #1
0
        private static Assembly LoadCore(AssemblyLoadContext ctx, string path)
        {
            using (FileStream fs = File.OpenRead(path))
            {
                // Load from a stream instead of loading from path, in order
                // to avoid locking the file.
                string pdbFile = Path.ChangeExtension(path, ".pdb");

                if (!File.Exists(pdbFile))
                {
                    return(ctx.LoadFromStream(fs));
                }

                FileStream pdbFs = null;

                try
                {
                    pdbFs = File.OpenRead(pdbFile);

                    return(ctx.LoadFromStream(fs, pdbFs));
                }
                catch
                {
                    return(ctx.LoadFromStream(fs));
                }
                finally
                {
                    pdbFs?.Dispose();
                }
            }
        }
Example #2
0
 public Assembly LoadInAssemblyLoadContext(AssemblyLoadContext loadContext)
 {
     if (DebugSymbols != null)
     {
         return(loadContext.LoadFromStream(new MemoryStream(Assembly), new MemoryStream(DebugSymbols)));
     }
     else
     {
         return(loadContext.LoadFromStream(new MemoryStream(Assembly)));
     }
 }
        /// <summary>
        /// Evaluates (compiles) C# code (script). The C# code is a typical C# code containing a single or multiple class definition(s).
        /// </summary>
        /// <example>
        ///<code>
        /// Assembly asm = CSScript.RoslynEvaluator
        ///                        .CompileCode(@"using System;
        ///                                       public class Script
        ///                                       {
        ///                                           public int Sum(int a, int b)
        ///                                           {
        ///                                               return a+b;
        ///                                           }
        ///                                       }");
        ///
        /// dynamic script =  asm.CreateObject("*");
        /// var result = script.Sum(7, 3);
        /// </code>
        /// </example>
        /// <param name="scriptText">The C# script text.</param>
        /// <returns>The compiled assembly.</returns>
        public Assembly CompileCode(string scriptText)
        {
            if (!DisableReferencingFromCode)
            {
                ReferenceAssembliesFromCode(scriptText);
            }

            //http://www.strathweb.com/2016/03/roslyn-scripting-on-coreclr-net-cli-and-dnx-and-in-memory-assemblies/
            //http://stackoverflow.com/questions/37526165/compiling-and-running-code-at-runtime-in-net-core-1-0
            //https://daveaglick.com/posts/compiler-platform-scripting
            //var hookCode = @" class EntryPoint{}; return typeof(EntryPoint).Assembly;";
            //return (Assembly)CSharpScript.EvaluateAsync(scriptText + hookCode).Result;

            var compilation = CSharpScript.Create(scriptText, CompilerSettings)
                              .RunAsync()
                              .Result
                              .Script
                              .GetCompilation();

            using (var ms = new MemoryStream())
            {
                EmitResult result = compilation.Emit(ms);

                if (!result.Success)
                {
                    IEnumerable <Diagnostic> failures = result.Diagnostics.Where(d => d.IsWarningAsError ||
                                                                                 d.Severity == DiagnosticSeverity.Error);

                    var message = new StringBuilder();
                    foreach (Diagnostic diagnostic in failures)
                    {
                        message.AppendFormat($"{diagnostic.Id}: {diagnostic.GetMessage()}");
                    }
                    throw new Exception("Compile error(s): " + message);
                }
                else
                {
                    ms.Seek(0, SeekOrigin.Begin);

#if NET451
                    Assembly assembly = Assembly.Load(ms.ToArray());
#else
                    AssemblyLoadContext context  = AssemblyLoadContext.Default;
                    Assembly            assembly = context.LoadFromStream(ms);
                    return(assembly);
#endif
                }
            }

            //var asmName = CSharpScript.Create(scriptText, CompilerSettings)
            //                          .RunAsync()
            //                          .Result
            //                          .Script
            //                          .GetCompilation()
            //                          .AssemblyName;

            //var asms = AppDomain.CurrentDomain.GetAssemblies().Select(a => a.FullName).ToArray();
            //Assembly result = AssemblyLoader.LoadByName(asmName);
            //return result;
        }
Example #4
0
        public bool Load(byte[] IL)
        {
            if (Loaded)
            {
                return(true);
            }

            Context = new ScriptModuleAssemblyLoadContext(null);
            using (var stream = new MemoryStream())
            {
                stream.Write(IL);
                stream.Seek(0, SeekOrigin.Begin);

                try
                {
                    Assembly = Context.LoadFromStream(stream);
                }
                catch (BadImageFormatException)
                {
                    return(false);
                }
            }

            return(true);
        }
Example #5
0
        public void LoadFile()
        {
            //先卸载老的
            //todo 这里应该是先加载更新的,出了异常就还是用老的,加载成功则用新的,并卸载老的
            UnLoad();
            try
            {
                resolver                        = new AssemblyDependencyResolver(filepath);
                _AssemblyLoadContext            = new AssemblyLoadContext(Guid.NewGuid().ToString("N"), true);
                _AssemblyLoadContext.Resolving += _AssemblyLoadContext_Resolving;

                using (var fs = new FileStream(filepath, FileMode.Open, FileAccess.Read))
                {
                    _Assembly = _AssemblyLoadContext.LoadFromStream(fs);
                    var types = _Assembly.GetTypes();
                    for (int i = 0; i < types.Length; i++)
                    {
                        Type item = types[i];
                        if (item.GetInterface(typeName) != null && item.IsClass)
                        {
                            var ins = (T)Activator.CreateInstance(item);
                            ins.Load();
                            _instances.Add(ins);
                        }
                    }
                }
            }
            catch (Exception ex) { Console.WriteLine(ex.Message); };
        }
Example #6
0
        public override async Task <IGenesisExecutionResult> Execute(GenesisContext genesis, string[] args)
        {
            var result = new BlankGenesisExecutionResult();

            var alc = new AssemblyLoadContext("DotNetAssembly", true);

            using var stream = File.OpenRead(Config.AssemblyPath);

            var asm = alc.LoadFromStream(stream);

            if (Config.OnlyGenesisDecorations)
            {
                foreach (var t in asm.DefinedTypes.Where(w => // pull objects with GenesisObject attribute
                                                         w.CustomAttributes.SingleOrDefault(ca => ca.AttributeType == typeof(GenesisObjectAttribute)) != null))
                {
                    InsertGraphFromType(genesis, t);
                }
            }
            else // use all public objects
            {
                foreach (var t in asm.DefinedTypes)
                {
                    InsertGraphFromType(genesis, t);
                }
            }

            return(await Task.FromResult(result));
        }
Example #7
0
        public void ExternalStaticMethodPreloadedFromAssembly()
        {
            var currentDirectory = Path.GetDirectoryName(typeof(ExternalAssemblyBugTests).Assembly.Location);
            var searchPath       = Path.GetFullPath(currentDirectory + @"\..\..\..\..\");

            var assemblyFilePath = Directory.GetFiles(
                searchPath, "ExternalMethods.dll", SearchOption.AllDirectories).First();

            var loadContext = new AssemblyLoadContext(name: Guid.NewGuid().ToString(), isCollectible: true);

            {
                // read the file and release it immediately (do not keep handle)
                var stream = new FileStream(assemblyFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                // alternatively can be used the line below:
                //using var stream = new MemoryStream(File.ReadAllBytes(assemblyFilePath));
                var loadedAssembly = loadContext.LoadFromStream(stream);

                Assert.AreEqual("<Unknown>", loadedAssembly.ManifestModule.FullyQualifiedName);
                Assert.AreEqual("<Unknown>", loadedAssembly.ManifestModule.Name);
                Assert.AreEqual("ExternalMethods.dll", loadedAssembly.ManifestModule.ScopeName);
                // it seems that ScopeName is only reliable information in this case
            }
            const string input       = "{ }";
            const string transformer = "{ \"result\": \"#StaticMethod()\" }";

            _context.RegisterCustomFunction("ExternalMethods", "ExternalMethods.ExternalClass", "StaticMethod");
            var result = new JsonTransformer(_context).Transform(transformer, input);

            Assert.AreEqual("{\"result\":\"External Static\"}", result);

            _context.ClearCustomFunctionRegistrations();
            loadContext.Unload();
        }
        private static TemplateDescriptor Compile(
            string source,
            IReadOnlyList <MetadataReference> references,
            AssemblyLoadContext assemblyLoadContext)
        {
            var csharpCode        = ToCSharp(source);
            var csharpDocumentAst = CSharpSyntaxTree.ParseText(csharpCode);

            var csharpDocumentCompilation = CSharpCompilation.Create(
                $"MiniRazor_Assembly_{Guid.NewGuid()}",
                new[] { csharpDocumentAst },
                references,
                new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                );

            using var assemblyStream = new MemoryStream();
            var csharpDocumentCompilationResult = csharpDocumentCompilation.Emit(assemblyStream);

            if (!csharpDocumentCompilationResult.Success)
            {
                throw MiniRazorException.CompilationFailed(
                          csharpCode,
                          csharpDocumentCompilationResult.Diagnostics
                          );
            }

            assemblyStream.Seek(0, SeekOrigin.Begin);
            var templateAssembly = assemblyLoadContext.LoadFromStream(assemblyStream);

            var templateType =
                templateAssembly.GetTypes().FirstOrDefault(t => t.Implements(typeof(ITemplate))) ??
                throw new InvalidOperationException("Could not locate compiled template in the generated assembly.");

            return(new TemplateDescriptor(templateType));
        }
Example #9
0
        public Assembly Generate(string code)
        {
            var assemblyName = Path.GetRandomFileName();
            var syntaxTree   = CSharpSyntaxTree.ParseText(code);

            var references  = _references.ToArray();
            var compilation = CSharpCompilation.Create(assemblyName, new[] { syntaxTree }, references,
                                                       new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));


            using (var stream = new MemoryStream())
            {
                var result = compilation.Emit(stream);
                if (!result.Success)
                {
                    var failures = result.Diagnostics.Where(diagnostic =>
                                                            diagnostic.IsWarningAsError ||
                                                            diagnostic.Severity == DiagnosticSeverity.Error);


                    var message = failures.Select(x => $"{x.Id}: {x.GetMessage()}").Join("\n");


                    throw new InvalidOperationException("Compilation failures!\n\n" + message + "\n\nCode:\n\n" + code);
                }

                stream.Seek(0, SeekOrigin.Begin);

                return(_context.LoadFromStream(stream));
            }
        }
Example #10
0
        private async ValueTask <Assembly?> TryCompileProject(
            string outputDirectory,
            bool outputCSharp,
            AssemblyLoadContext assemblyLoadContext,
            IAssembly project,
            CancellationToken cancellationToken)
        {
            var compilationResult = project.CompileAssembly(
                out var assemblyBytes,
                out var csharpBytes,
                out _);

            if (!ValidateCompilationResult(compilationResult, project))
            {
                return(null);
            }

            var assembly = assemblyLoadContext.LoadFromStream(assemblyBytes.ToStream());

            await WriteOutput(
                outputDirectory,
                outputCSharp,
                project,
                csharpBytes,
                cancellationToken);

            return(assembly);
        }
Example #11
0
        //todo 需要watch
        private void Load()
        {
            //先卸载老的
            //todo 这里应该是先加载更新的,出了异常就还是用老的,加载成功则用新的,并卸载老的
            UnLoad();
            try
            {
                resolver                        = new AssemblyDependencyResolver(filepath);
                _AssemblyLoadContext            = new AssemblyLoadContext(Guid.NewGuid().ToString("N"), true);
                _AssemblyLoadContext.Resolving += _AssemblyLoadContext_Resolving;

                using (var fs = new FileStream(filepath, FileMode.Open, FileAccess.Read))
                {
                    _Assembly = _AssemblyLoadContext.LoadFromStream(fs);
                    var types = _Assembly.GetTypes();
                    for (int i = 0; i < types.Length; i++)
                    {
                        Type item = types[i];
                        if (typeof(Service.Service).FullName == item.GetTypeInfo().FullName&& item.IsClass)
                        {
                            service = (IService)Activator.CreateInstance(item);
                        }
                    }
                }
                if (service == null)
                {
                    throw new Exception("not found class Service");
                }
            }
            catch (Exception ex) { throw new Exception(ex.Message); };
        }
        private void CheckGetStreamResult(Stream stream)
        {
            var loader   = new AssemblyLoadContext(null);
            var assembly = loader.LoadFromStream(stream);

            assembly.FullName.ShouldBe("AElf.Runtime.CSharp.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
        }
Example #13
0
        private static T Compile <T>(string source, IEnumerable <Assembly> references)
        {
            var options = CSharpParseOptions.Default
                          .WithLanguageVersion(LanguageVersion.Latest);

            var compileOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                                 .WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default);

            var compilation = CSharpCompilation.Create("Dynamic",
                                                       new[] { SyntaxFactory.ParseSyntaxTree(source, options) },
                                                       references.Select(a => MetadataReference.CreateFromFile(a.Location)),
                                                       compileOptions
                                                       );

            using var ms = new MemoryStream();
            var e = compilation.Emit(ms);

            if (!e.Success)
            {
                throw new Exception("Compilation failed");
            }
            ms.Seek(0, SeekOrigin.Begin);

            var context  = new AssemblyLoadContext(null, true);
            var assembly = context.LoadFromStream(ms);

            var modelType = assembly.DefinedTypes.Where(t => typeof(T).IsAssignableFrom(t)).Single();

            return((T)Activator.CreateInstance(modelType));
        }
Example #14
0
 public ValueTask <AssemblyLoadResult?> TryLoadAssemblyAsync(AssemblyLoadContext assemblyLoadContext, Dependency dependency, CancellationToken cancellationToken = default)
 {
     return(new ValueTask <AssemblyLoadResult?>(
                new AssemblyLoadResult(
                    assemblyLoadContext.LoadFromStream(_bytes.ToStream()),
                    _bytes)));
 }
        public async Task GenerateStruct_Parse_ReadOnlySpan()
        {
            var sourceCode = @"
[StronglyTypedIdAttribute(typeof(int))]
public partial struct Test {}
";
            var result     = await GenerateFiles(sourceCode);

            Assert.Empty(result.GeneratorResult.Diagnostics);
            Assert.Equal(2, result.GeneratorResult.GeneratedTrees.Length);

            var alc = new AssemblyLoadContext("test", isCollectible: true);

            try
            {
                alc.LoadFromStream(new MemoryStream(result.Assembly));
                foreach (var a in alc.Assemblies)
                {
                    var type  = a.GetType("Test");
                    var parse = type.GetMember("Parse").Length;
                    Assert.Equal(2, parse);
                }
            }
            finally
            {
                alc.Unload();
            }
        }
        public async Task GenerateStruct_ToString()
        {
            var sourceCode = @"
[StronglyTypedIdAttribute(typeof(int))]
public partial struct Test {}
";
            var result     = await GenerateFiles(sourceCode);

            Assert.Empty(result.GeneratorResult.Diagnostics);
            Assert.Equal(2, result.GeneratorResult.GeneratedTrees.Length);

            var alc = new AssemblyLoadContext("test", isCollectible: true);

            try
            {
                alc.LoadFromStream(new MemoryStream(result.Assembly));
                foreach (var a in alc.Assemblies)
                {
                    CultureInfoUtilities.UseCulture("sv-SE", () =>
                    {
                        var type     = a.GetType("Test");
                        var from     = (MethodInfo)type.GetMember("FromInt32").Single();
                        var instance = from.Invoke(null, new object[] { -42 });
                        var str      = instance.ToString();

                        Assert.Equal("Test { Value = -42 }", str);
                    });
                }
            }
            finally
            {
                alc.Unload();
            }
        }
        public async Task GenerateStruct_Guid_New()
        {
            var sourceCode = @"
[StronglyTypedIdAttribute(typeof(System.Guid))]
public partial struct Test {}
";
            var result     = await GenerateFiles(sourceCode);

            Assert.Empty(result.GeneratorResult.Diagnostics);
            Assert.Equal(2, result.GeneratorResult.GeneratedTrees.Length);

            var alc = new AssemblyLoadContext("test", isCollectible: true);

            try
            {
                alc.LoadFromStream(new MemoryStream(result.Assembly));
                foreach (var a in alc.Assemblies)
                {
                    var guid          = Guid.NewGuid();
                    var type          = a.GetType("Test");
                    var from          = (MethodInfo)type.GetMember("FromGuid").Single();
                    var newMethod     = (MethodInfo)type.GetMember("New").Single();
                    var emptyInstance = from.Invoke(null, new object[] { Guid.Empty });
                    var instance      = from.Invoke(null, new object[] { guid });
                    var newInstance   = newMethod.Invoke(null, null);
                    Assert.NotEqual(instance, newInstance);
                    Assert.NotEqual(emptyInstance, newInstance);
                }
            }
            finally
            {
                alc.Unload();
            }
        }
        private Assembly CompileRazorCode(string assemblyName, RazorCodeDocument codeDocument)
        {
            var csharpDocument    = codeDocument.GetCSharpDocument();
            var csharpDocumentAst = CSharpSyntaxTree.ParseText(csharpDocument.GeneratedCode);

            var csharpDocumentCompilation = CSharpCompilation.Create(
                assemblyName,
                new[] { csharpDocumentAst },
                _metadataReferencesLazy.Value,
                new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                );

            using var assemblyStream = new MemoryStream();
            var csharpDocumentCompilationResult = csharpDocumentCompilation.Emit(assemblyStream);

            if (!csharpDocumentCompilationResult.Success)
            {
                throw MiniRazorException.CompilationFailed(
                          csharpDocument.GeneratedCode,
                          csharpDocumentCompilationResult.Diagnostics
                          );
            }

            assemblyStream.Seek(0, SeekOrigin.Begin);
            return(_assemblyLoadContext.LoadFromStream(assemblyStream));
        }
Example #19
0
        private static Assembly CreateAssembly(string sourceCode, bool debug)
        {
            lineOffset   = CalculateLineOffset(sourceCode);
            exceptionMsg = null;
            errors       = null;

            string assemblyName = Path.GetRandomFileName();
            IEnumerable <SyntaxTree> syntaxTree = new[] { CSharpSyntaxTree.ParseText(sourceCode, options: debug ? parseOptions.WithPreprocessorSymbols("DEBUG") : parseOptions) };

            CSharpCompilation compilation = CSharpCompilation.Create(
                assemblyName, syntaxTree, references,
                compilationOptions.WithOptimizationLevel(debug ? OptimizationLevel.Debug : OptimizationLevel.Release));

            using (MemoryStream ms = new MemoryStream())
            {
                EmitResult result = compilation.Emit(ms);

                errors = result.Diagnostics.Where(ErrorFilter);

                if (!result.Success)
                {
                    return(null);
                }

                AssemblyLoadContext loadContext = new AssemblyLoadContext(null, true);
                ms.Seek(0, SeekOrigin.Begin);
                Assembly assembly = loadContext.LoadFromStream(ms);
                return(assembly);
            }
        }
Example #20
0
        private static bool IsFileAPlugin(string path)
        {
            try
            {
                AssemblyLoadContext context = new AssemblyLoadContext("cached_check_" + path, true);
                bool flag = false;
                using (FileStream stream = File.OpenRead(path))
                {
                    Assembly assembly = context.LoadFromStream(stream);
                    foreach (Type type in assembly.ExportedTypes)
                    {
                        if (typeof(Plugin).IsAssignableFrom(type))
                        {
                            flag = true;
                            break;
                        }
                    }
                }

                context.Unload();
                return(flag);
            }
            catch
            {
                return(false);
            }
        }
Example #21
0
        public Assembly CreateInMemory(string assemblyName, string code, params Assembly[] dependencies)
        {
            var compilation = CreateCompilation(assemblyName, code, dependencies);

            using (var peStream = new MemoryStream())
            {
                using (var pdbStream = new MemoryStream())
                {
                    var result = compilation.Emit(peStream, pdbStream);
                    MaybeLogWarningsAndErrors(result);

                    peStream.Seek(0, SeekOrigin.Begin);
                    var assembly = _context.LoadFromStream(peStream, pdbStream);
                    return(assembly);
                }
            }
        }
 internal Type AddDynaClass(string fullyQualifiedClassName, byte[] byteCode)
 {
     using (var stream = new MemoryStream(byteCode, false))
     {
         var loadedAssembly = context.LoadFromStream(stream);
         return(loadedAssembly.GetType(fullyQualifiedClassName));
     }
 }
Example #23
0
 public Assembly ReadBytes(byte[] assemblyBytes, byte[] assemblySymbols = null)
 {
     using (MemoryStream ms = new MemoryStream(assemblyBytes))
     {
         if (assemblySymbols.IsNullOrEmpty())
         {
             return(_context.LoadFromStream(ms));
         }
         else
         {
             using (MemoryStream bms = new MemoryStream(assemblySymbols))
             {
                 return(_context.LoadFromStream(ms, bms));
             }
         }
     }
 }
Example #24
0
        private static Assembly LoadMainDllWithDeps(AssemblyLoadContext context, string mainAsmPath)
        {
            using var stream = File.OpenRead(mainAsmPath);
            var asm = context.LoadFromStream(stream);

            var dirPath = Path.GetDirectoryName(mainAsmPath) !;
            var refs    = asm.GetReferencedAssemblies()
                          .Select(r => Path.Combine(dirPath, r.Name + ".dll"))
                          .Where(File.Exists);

            foreach (var dllPath in refs)
            {
                using var depStream = File.OpenRead(dllPath);
                context.LoadFromStream(depStream);
            }
            return(asm);
        }
Example #25
0
        private bool loadModule(string name, bool isInit)
        {
            if (!ConfigUtils.isModule(name))
            {
                return(false);
            }

            unloadModule(name, true); //we dont need to pass isinit to here, since we are initializing

            AssemblyLoadContext _moduleLoadContext = new AssemblyLoadContext(name, true);
            string   modulePath = ConfigUtils.getModulePath(name);
            Assembly assembly;
            List <ModuleInstance> instances = new List <ModuleInstance>();

            using (var file = File.OpenRead(modulePath))
            {
                assembly = _moduleLoadContext.LoadFromStream(file);
                foreach (Type moduleType in assembly.GetTypes())
                {
                    //_sawmill.Debug("Found module {0}", moduleType);
                    if (moduleType.GetCustomAttribute(typeof(LogModule)) != null)
                    {
                        Console.WriteLine($"Loaded module {moduleType}");
                    }
                    if (moduleType.BaseType == typeof(ModuleInstance))
                    {
                        ModuleInstance t_module = (ModuleInstance)Activator.CreateInstance(moduleType);

                        HasDataFileAttribute hdfa = moduleType.GetCustomAttribute <HasDataFileAttribute>();
                        if (hdfa != null && File.Exists($"{datadir}/{hdfa.datafile}.json"))
                        {
                            string path = $"{datadir}/{hdfa.datafile}.json";

                            if (!Directory.Exists(datadir))
                            {
                                Directory.CreateDirectory(datadir);
                            }

                            string text = File.ReadAllText(path);
                            t_module.load_jobject(JsonConvert.DeserializeObject <JObject>(text));
                        }

                        t_module.mainAsync().GetAwaiter(); //this should never fail cause moduleType NEEDS to have been inherited from CrabModule
                        instances.Add(t_module);
                    }
                }
            }
            _modules.Add(name, new LoadedModule(_moduleLoadContext, instances));

            foreach (Assembly ass in _moduleLoadContext.Assemblies)
            {
                ModuleEventArgs args = new ModuleEventArgs();
                args.name     = name;
                args.assembly = ass;
                ModuleEvents.moduleLoaded(this, args);
            }
            return(true);
        }
Example #26
0
        static void test()
        {
            var path  = @"E:\Galos\Projects\CS-Script\GitHub\cs-script\Source\.NET Core\CSScriptLib\src\CSScriptLib\bin\Debug\netstandard2.0\script.txt";
            var lines = File.ReadAllLines(path);
            var sb    = new StringBuilder();

            sb.AppendLine($"#line 1 \"{path}\"");
            foreach (var l in lines)
            {
                if (l.StartsWith("write"))
                {
                    var res = l.Substring(l.IndexOf(" ", StringComparison.Ordinal)).Trim();
                    sb.AppendLine($"System.Console.WriteLine(\"{res}\");");
                }
                else
                {
                    sb.AppendLine(l);
                }
            }

            var script       = sb.ToString();
            var options      = Microsoft.CodeAnalysis.Scripting.ScriptOptions.Default;
            var roslynScript = CSharpScript.Create(script, options);
            var compilation  = roslynScript.GetCompilation();

            compilation = compilation.WithOptions(compilation.Options
                                                  .WithOptimizationLevel(OptimizationLevel.Debug)
                                                  .WithOutputKind(OutputKind.DynamicallyLinkedLibrary));

            using (var assemblyStream = new MemoryStream())
            {
                using (var symbolStream = new MemoryStream())
                {
                    var emitOptions = new EmitOptions(false, DebugInformationFormat.PortablePdb);
                    var result      = compilation.Emit(assemblyStream, symbolStream, options: emitOptions);
                    if (!result.Success)
                    {
                        var errors = string.Join(Environment.NewLine, result.Diagnostics.Select(x => x));
                        Console.WriteLine(errors);
                        return;
                    }

                    //Execute the script
                    assemblyStream.Seek(0, SeekOrigin.Begin);
                    symbolStream.Seek(0, SeekOrigin.Begin);

                    AssemblyLoadContext context  = AssemblyLoadContext.Default;
                    Assembly            assembly = context.LoadFromStream(assemblyStream, symbolStream);

                    // var assembly = Assembly.Load(assemblyStream.ToArray(), symbolStream.ToArray());
                    var type   = assembly.GetType("Submission#0");
                    var method = type.GetMethod("<Factory>", BindingFlags.Static | BindingFlags.Public);

                    method.Invoke(null, new object[] { new object[2] });
                }
            }
        }
Example #27
0
        public void FullyQualifiedNameOfAssemblyLoadedFromStream()
        {
            AssemblyLoadContext testAlc = new AssemblyLoadContext(nameof(FullyQualifiedNameOfAssemblyLoadedFromStream));

            using var fileStream = File.OpenRead(Path.Join(DeploymentUtilities.ExecutableLocation, "PluginLibrary.dll"));
            Assembly assembly = testAlc.LoadFromStream(fileStream);

            ValidateUnknownModuleFullyQualifiedName(assembly.GetModules()[0]);
        }
        public void GetFilesOnAssemblyLoadedFromStream()
        {
            AssemblyLoadContext testAlc = new AssemblyLoadContext(nameof(GetFilesOnAssemblyLoadedFromStream));

            using var fileStream = File.OpenRead(Path.Join(DeploymentUtilities.ExecutableLocation, "PluginLibrary.dll"));
            Assembly assembly = testAlc.LoadFromStream(fileStream);

            ValidateInMemoryGetFiles(assembly);
        }
        public Assembly LoadPlugin(AssemblyLoadContext assemblyLoadContext, Guid fileGuid)
        {
            var path = Path.Combine("Upload", $"{fileGuid}.dll");

            using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                return(assemblyLoadContext.LoadFromStream(fs));
            }
        }
Example #30
0
        private Assembly Compile(string name, List <string> codes)
        {
            if (codes == null)
            {
                throw new ArgumentNullException("code");
            }

            if (!codes.Any())
            {
                throw new ArgumentException("No code given!");
            }

            var trees  = new List <SyntaxTree>();
            var usings = _usings.Select(s => SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(s))).ToArray();

            foreach (var code in codes)
            {
                // Parse the script to a SyntaxTree
                var syntaxTree = CSharpSyntaxTree.ParseText(code);
                var root       = (CompilationUnitSyntax)syntaxTree.GetRoot();

                if (usings.Any())
                {
                    root = root.AddUsings(usings);
                }

                trees.Add(SyntaxFactory.SyntaxTree(root));
            }


            // Compile the SyntaxTree to an in memory assembly
            var compilation = CSharpCompilation.Create(
                name,
                trees,
                _references,
                new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                );

            using (var outputStream = new MemoryStream())
            {
                using (var pdbStream = new MemoryStream())
                {
                    var result = compilation.Emit(outputStream);
                    if (result.Success)
                    {
                        outputStream.Position = 0;
                        return(_context.LoadFromStream(outputStream));
                    }
                    else
                    {
                        result.Diagnostics.ForEach(x => Console.WriteLine(x.ToString()));
                        return(null);
                    }
                }
            }
        }