public static void CreateAssemblyDefinition(string code) { Microsoft.CodeAnalysis.SyntaxTree syntaxTree = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(code); System.Collections.Generic.IReadOnlyCollection < Microsoft.CodeAnalysis.MetadataReference> _references = new[] { Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(typeof(System.Reflection.Binder).Assembly.Location), Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(typeof(System.ValueTuple <>).Assembly.Location) }; bool enableOptimisations = true; Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions options = new Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions( Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary, optimizationLevel: enableOptimisations ? Microsoft.CodeAnalysis.OptimizationLevel.Release : Microsoft.CodeAnalysis.OptimizationLevel.Debug, allowUnsafe: true ); Microsoft.CodeAnalysis.Compilation compilation = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create( assemblyName: "InMemoryAssembly", options: options) .AddReferences(_references) .AddSyntaxTrees(syntaxTree); System.IO.MemoryStream stream = new System.IO.MemoryStream(); Microsoft.CodeAnalysis.Emit.EmitResult emitResult = compilation.Emit(stream); if (emitResult.Success) { stream.Seek(0, System.IO.SeekOrigin.Begin); // System.Reflection.Metadata.AssemblyDefinition assembly = System.Reflection.Metadata.AssemblyDefinition.ReadAssembly(stream); } }
private Action SetupCompileAction() { string text = @"using RoslynTest; public class Evaluator { public static void Evaluate() { Watcher.Runner(""123""); Watcher.Runner(""123""); } }"; SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(text); CSharpCompilation compilation = CSharpCompilation.Create( "eval.dll", options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), syntaxTrees: new[] { tree }, references: new[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location), MetadataReference.CreateFromFile(typeof(Watcher).Assembly.Location) }); Assembly compiledAssembly; using (MemoryStream stream = new MemoryStream()) { Microsoft.CodeAnalysis.Emit.EmitResult compileResult = compilation.Emit(stream); compiledAssembly = Assembly.Load(stream.GetBuffer()); } Type evaluator = compiledAssembly.GetType("Evaluator"); return((Action)evaluator.GetMethod("Evaluate").CreateDelegate(typeof(Action))); }
public static bool CanCompile(string sourceCode, out CSharpCompilation compilation) { using (var compiledStream = new MemoryStream()) { compilation = GenerateCode(sourceCode); Microsoft.CodeAnalysis.Emit.EmitResult result = compilation.Emit(compiledStream); if (!result.Success) { //Console.WriteLine("You have a problem."); var problems = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error); foreach (var problem in problems) { //Console.Error.WriteLine("{0}: {1}: {2}", problem.Id, problem.GetMessage(), problem.Location.GetLineSpan().StartLinePosition); } return(false); } //Console.WriteLine("Compilation done without any error."); compiledStream.Seek(0, SeekOrigin.Begin); return(true); } }
} // End Sub Test // emit the compilation result into a byte array. // throw an exception with corresponding message // if there are errors private static byte[] EmitToArray ( this Microsoft.CodeAnalysis.Compilation compilation ) { using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) { // emit result into a stream Microsoft.CodeAnalysis.Emit.EmitResult emitResult = compilation.Emit(stream); if (!emitResult.Success) { // if not successful, throw an exception Microsoft.CodeAnalysis.Diagnostic firstError = emitResult .Diagnostics .FirstOrDefault ( diagnostic => diagnostic.Severity == Microsoft.CodeAnalysis.DiagnosticSeverity.Error ); throw new System.Exception(firstError?.GetMessage()); } // get the byte array from a stream return stream.ToArray(); } // End Using stream } // End Function EmitToArray
public void EndToEndCompileAndRun() { string expression = "6 * 7"; string text = @"public class Calculator { public static object Evaluate() { return $; } }".Replace("$", expression); SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(text); CSharpCompilation compilation = CSharpCompilation.Create( "calc.dll", options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), syntaxTrees: new[] { tree }, references: new[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location) }); Assembly compiledAssembly; using (MemoryStream stream = new MemoryStream()) { Microsoft.CodeAnalysis.Emit.EmitResult compileResult = compilation.Emit(stream); compiledAssembly = Assembly.Load(stream.GetBuffer()); } Type calculator = compiledAssembly.GetType("Calculator"); MethodInfo evaluate = calculator.GetMethod("Evaluate"); string answer = evaluate.Invoke(null, null).ToString(); Assert.Equal("42", answer); }
public bool CompilePlugin(string pluginPath, PluginInformation information) { var compiler = CSharpCompilation.Create($"{nameof(HunterPie)}{information.Name}", options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) .WithOptimizationLevel(OptimizationLevel.Release)); Type[] types = new[] { typeof(Hunterpie), // HunterPie typeof(JObject), // Newtonsoft.Json.dll typeof(Object), // mscorlib.dll typeof(UIElement), // PresentationCore.dll typeof(Window), // PresentationFramework.dll typeof(Uri), // System.dll typeof(Enumerable), // System.Core.dll typeof(DataSet), // System.Data.dll typeof(DataTableExtensions), // System.Data.DataSetExtensions.dll typeof(Bitmap), // System.Drawing.dll typeof(HttpClient), // System.Net.Http.dll typeof(BigInteger), // System.Numerics.dll typeof(Form), // System.Windows.Forms.dll typeof(XamlType), // System.Xaml.dll typeof(XmlNode), // System.Xml.dll typeof(XNode), // System.Xml.Linq.dll typeof(Rect), // WindowsBase.dll }; // Load all basic dependencies List <MetadataReference> references = types.Select(type => MetadataReference.CreateFromFile(type.Assembly.Location)).ToList <MetadataReference>(); if (information.Dependencies != null) { foreach (string extDependency in information.Dependencies) { references.Add(MetadataReference.CreateFromFile(Path.Combine(pluginPath, extDependency))); } } compiler = compiler.AddReferences(references); string code = File.ReadAllText(Path.Combine(pluginPath, information.EntryPoint)); CSharpParseOptions options = CSharpParseOptions.Default.WithLanguageVersion( LanguageVersion.CSharp7_3); SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(SourceText.From(code, Encoding.UTF8), options, Path.Combine(pluginPath, information.EntryPoint)); compiler = compiler.AddSyntaxTrees(syntaxTree); Microsoft.CodeAnalysis.Emit.EmitResult result = compiler.Emit(Path.Combine(pluginPath, information.Name) + ".dll"); if (result.Success) { return(true); } else { Debugger.Error($"Failed to compile plugin: {information.Name}"); foreach (var exception in result.Diagnostics) { Debugger.Error(exception); } return(false); } }
private string ReadCompilationErrors(Microsoft.CodeAnalysis.Emit.EmitResult compilationResult) { var sb = new StringBuilder(); foreach (Diagnostic codeIssue in compilationResult.Diagnostics) { sb.AppendLine($"ID: {codeIssue.Id}, Message: {codeIssue.GetMessage()}, Location: {codeIssue.Location.GetLineSpan().ToString()}, Severity: {codeIssue.Severity.ToString()}"); } return(sb.ToString()); }
private void Compile(FileInfo outputFile, IEnumerable <SyntaxTree> syntaxTrees) { var compilerParameters = new CSharpCompilationOptions( outputKind: OutputKind.DynamicallyLinkedLibrary, warningLevel: 2); compiler = CSharpCompilation.Create( outputFile.Name, options: compilerParameters, references: referencedAssemblies, syntaxTrees: syntaxTrees); var emitResult = compiler.Emit(outputFile.FullName); GC.Collect(); lastEmitResult = emitResult; }
public string CompileSource(string source) { SyntaxTree parsedSyntaxTree = Parse(source, "", CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Latest)); string outputFile = Path.GetTempFileName(); string outputFileName = Path.GetFileName(outputFile); CSharpCompilation compilation = CSharpCompilation.Create(outputFileName, new SyntaxTree[] { parsedSyntaxTree }, DefaultReferences, DefaultCompilationOptions); Microsoft.CodeAnalysis.Emit.EmitResult result = compilation.Emit(outputFile); if (!result.Success) { throw new Exception(); } return(outputFile); }
static Type[] compile(string typesDefinition, IEnumerable <MetadataReference> references = null, Assembly rootAssembly = null, string dllFile = null) { SyntaxTree st = SyntaxFactory.ParseSyntaxTree(typesDefinition); CSharpCompilation compilation = CSharpCompilation.Create("emitted.dll",//no file seems to be really created syntaxTrees: new SyntaxTree[] { st }, references: references != null ? references : GetAllReferences(rootAssembly), options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) ); Assembly assembly; void checkEmitResult(Microsoft.CodeAnalysis.Emit.EmitResult result) { if (!result.Success) { List <Error> compilationErrors = new List <Error>(); IEnumerable <Diagnostic> failures = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error); foreach (Diagnostic diagnostic in failures) { compilationErrors.Add(new Error { Message = diagnostic.GetMessage(), P1 = diagnostic.Location.SourceSpan.Start, P2 = diagnostic.Location.SourceSpan.End }); } throw new Exception(compilationErrors); } } if (dllFile == null) { using (var ms = new MemoryStream()) { Microsoft.CodeAnalysis.Emit.EmitResult result = compilation.Emit(ms); checkEmitResult(result); ms.Seek(0, SeekOrigin.Begin); assembly = Assembly.Load(ms.ToArray()); } } else { Microsoft.CodeAnalysis.Emit.EmitResult result = compilation.Emit(dllFile); checkEmitResult(result); assembly = Assembly.Load(dllFile); } return(assembly.GetTypes()); }
// https://gist.github.com/GeorgDangl/4a9982a3b520f056a9e890635b3695e0 private static void ThrowExceptionIfCompilationFailure(Microsoft.CodeAnalysis.Emit.EmitResult result) { if (!result.Success) { System.Collections.Generic.List <Microsoft.CodeAnalysis.Diagnostic> compilationErrors = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == Microsoft.CodeAnalysis.DiagnosticSeverity.Error) .ToList(); if (compilationErrors.Any()) { Microsoft.CodeAnalysis.Diagnostic firstError = compilationErrors.First(); string errorNumber = firstError.Id; string errorDescription = firstError.GetMessage(); string firstErrorMessage = $"{errorNumber}: {errorDescription};"; throw new System.Exception($"Compilation failed, first error is: {firstErrorMessage}"); } } }
public void DummyTest() { string vsName = "TestShaders.VeldridShaders.VertexAndFragment.VS"; string fsName = "TestShaders.VeldridShaders.VertexAndFragment.FS"; Compilation compilation = TestUtil.GetTestProjectCompilation(); using (TempFile fp = new TempFile()) { Microsoft.CodeAnalysis.Emit.EmitResult emitResult = compilation.Emit(fp); Assert.True(emitResult.Success); } LanguageBackend backend = new Glsl450Backend(compilation); ShaderGenerator sg = new ShaderGenerator( compilation, vsName, fsName, backend); ShaderGenerationResult result = sg.GenerateShaders(); IReadOnlyList <GeneratedShaderSet> sets = result.GetOutput(backend); Assert.Equal(1, sets.Count); GeneratedShaderSet set = sets[0]; ShaderModel shaderModel = set.Model; if (vsName != null) { ShaderFunction vsFunction = shaderModel.GetFunction(vsName); string vsCode = set.VertexShaderCode; File.WriteAllText(@"C:\Users\raver\Documents\forward-vertex.glsl", vsCode); GlsLangValidatorTool.AssertCompilesCode(vsCode, "vert", true); } if (fsName != null) { ShaderFunction fsFunction = shaderModel.GetFunction(fsName); string fsCode = set.FragmentShaderCode; File.WriteAllText(@"C:\Users\raver\Documents\forward-frag.glsl", fsCode); GlsLangValidatorTool.AssertCompilesCode(fsCode, "frag", true); } }
public bool OkOrPrintErrors() { MemoryStream ms = new MemoryStream(); Microsoft.CodeAnalysis.Emit.EmitResult ret = Compilation.Emit(ms); if (ret.Success) { return(true); } IEnumerable <Diagnostic> failures = ret.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error); foreach (Diagnostic diagnostic in failures) { WriteLine(diagnostic.ToString()); } return(false); }
/// <summary> /// Compile source files to assembly<br/> /// 编译源代码到程序集<br/> /// </summary> public void Compile(IList <string> sourceFiles, string assemblyName, string assemblyPath) { // Parse source files into syntax trees // Also define NETCORE for .Net Core var parseOptions = CSharpParseOptions.Default; parseOptions = parseOptions.WithPreprocessorSymbols("NETCORE"); var syntaxTrees = sourceFiles .Select(path => CSharpSyntaxTree.ParseText( File.ReadAllText(path), parseOptions, path, Encoding.UTF8)) .ToList(); LoadAssembliesFromUsings(syntaxTrees); // Add loaded assemblies to compile references var assemblyLoader = new NetAssemblyLoader(); var references = assemblyLoader.GetLoadedAssemblies() .Select(assembly => assembly.Location) .Select(path => MetadataReference.CreateFromFile(path)) .ToList(); var optimizationLevel = OptimizationLevel.Release; var compilationOptions = new CSharpCompilationOptions( OutputKind.DynamicallyLinkedLibrary, optimizationLevel: optimizationLevel); // Compile to assembly, throw exception if error occurred Microsoft.CodeAnalysis.CSharp.CSharpCompilation compilation = CSharpCompilation.Create(assemblyName) .WithOptions(compilationOptions) .AddReferences(references) .AddSyntaxTrees(syntaxTrees); Microsoft.CodeAnalysis.Emit.EmitResult emitResult = compilation.Emit(assemblyPath); if (!emitResult.Success) { throw new Exception(string.Join("\r\n", emitResult.Diagnostics.Where(d => d.WarningLevel == 0))); } }
private static void CreateCsCompilation(string code) { Microsoft.CodeAnalysis.SyntaxTree syntaxTree = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(code); string assemblyName = System.Guid.NewGuid().ToString(); System.Collections.Generic.IEnumerable <Microsoft.CodeAnalysis.MetadataReference> references = GetAssemblyReferences(); Microsoft.CodeAnalysis.Compilation compilation = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create( assemblyName, new[] { syntaxTree }, references, new Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions( Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary) ); // byte[] compilationResult = compilation.EmitToArray(); // System.Reflection.Assembly.Load(compilationResult); using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { Microsoft.CodeAnalysis.Emit.EmitResult result = compilation.Emit(ms); ThrowExceptionIfCompilationFailure(result); ms.Seek(0, System.IO.SeekOrigin.Begin); System.Reflection.Assembly assembly2 = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromStream(ms); #if NET46 // Different in full .Net framework System.Reflection.Assembly assembly3 = Assembly.Load(ms.ToArray()); #endif } // _compilation = compilation; }
} // End Sub CheckCompilationResult private static void CreateCompilation2(string code) { Microsoft.CodeAnalysis.SyntaxTree syntaxTree = Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.ParseText(code); string assemblyName = System.Guid.NewGuid().ToString(); System.Collections.Generic.IEnumerable <Microsoft.CodeAnalysis.MetadataReference> references = GetAssemblyReferences(); Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilationOptions co = new Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilationOptions ( Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary ); co.WithOptionStrict(Microsoft.CodeAnalysis.VisualBasic.OptionStrict.Off); co.WithOptionExplicit(false); co.WithOptionInfer(true); Microsoft.CodeAnalysis.Compilation compilation = Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilation.Create( assemblyName, new[] { syntaxTree }, references, co ); // WTF !!! // byte[] compilationResult = compilation.EmitToArray(); // Load the resulting assembly into the domain. // System.Reflection.Assembly assembly = System.Reflection.Assembly.Load(compilationResult); /* * // get the type Program from the assembly * System.Type programType = assembly.GetType("Program"); * * // Get the static Main() method info from the type * System.Reflection.MethodInfo method = programType.GetMethod("Main"); * * // invoke Program.Main() static method * method.Invoke(null, null); */ using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { Microsoft.CodeAnalysis.Emit.EmitResult result = compilation.Emit(ms); ThrowExceptionIfCompilationFailure(result); ms.Seek(0, System.IO.SeekOrigin.Begin); System.Reflection.Assembly assembly2 = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromStream(ms); #if NET46 // Different in full .Net framework System.Reflection.Assembly assembly3 = Assembly.Load(ms.ToArray()); #endif } }
// https://gist.github.com/GeorgDangl/4a9982a3b520f056a9e890635b3695e0 private static System.CodeDom.Compiler.CompilerResults CheckCompilationResult(Microsoft.CodeAnalysis.Emit.EmitResult emitResult) { System.CodeDom.Compiler.CompilerResults compilerResults = new System.CodeDom.Compiler.CompilerResults(null); compilerResults.NativeCompilerReturnValue = 0; if (!emitResult.Success) { foreach (Microsoft.CodeAnalysis.Diagnostic diagnostic in emitResult.Diagnostics) { // options.TreatWarningsAsErrors if (diagnostic.IsWarningAsError || diagnostic.Severity == Microsoft.CodeAnalysis.DiagnosticSeverity.Error) { compilerResults.NativeCompilerReturnValue = -1; string errorNumber = diagnostic.Id; string errorMessage = diagnostic.GetMessage(); string message = $"{errorNumber}: {errorMessage};"; Microsoft.CodeAnalysis.FileLinePositionSpan lineSpan = diagnostic.Location.GetLineSpan(); string fileName = lineSpan.Path; int line = lineSpan.StartLinePosition.Line; int col = lineSpan.StartLinePosition.Character; compilerResults.Errors.Add( new System.CodeDom.Compiler.CompilerError(fileName, line, col, errorNumber, errorMessage) ); throw new System.Exception($"Compilation failed, first error is: {message}"); } // End if } // Next diagnostic } // End if (!emitResult.Success) return(compilerResults); } // End Sub CheckCompilationResult
private static void CreateCompilationMultiFile(string[] filenames) { string assemblyName = System.Guid.NewGuid().ToString(); System.Collections.Generic.IEnumerable <Microsoft.CodeAnalysis.MetadataReference> references = GetAssemblyReferences(); Microsoft.CodeAnalysis.SyntaxTree[] syntaxTrees = new Microsoft.CodeAnalysis.SyntaxTree[filenames.Length]; Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions op = null; for (int i = 0; i < filenames.Length; ++i) { string fileContent = System.IO.File.ReadAllText(filenames[i], System.Text.Encoding.UTF8); syntaxTrees[i] = Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.ParseText( fileContent , op , filenames[i] , System.Text.Encoding.UTF8 ); } Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilationOptions co = new Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilationOptions ( Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary ); co.WithOptionStrict(Microsoft.CodeAnalysis.VisualBasic.OptionStrict.Off); co.WithOptionExplicit(false); co.WithOptionInfer(true); Microsoft.CodeAnalysis.Compilation compilation = Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilation.Create( assemblyName, syntaxTrees, references, co ); // byte[] compilationResult = compilation.EmitToArray(); using (System.IO.MemoryStream dllStream = new System.IO.MemoryStream()) { using (System.IO.MemoryStream pdbStream = new System.IO.MemoryStream()) { Microsoft.CodeAnalysis.Emit.EmitResult emitResult = compilation.Emit(dllStream, pdbStream); if (!emitResult.Success) { CheckCompilationResult(emitResult); } // End if (!emitResult.Success) } // End Using pdbStream } // End Using dllStream /* * // get the type Program from the assembly * System.Type programType = assembly.GetType("Program"); * * // Get the static Main() method info from the type * System.Reflection.MethodInfo method = programType.GetMethod("Main"); * * // invoke Program.Main() static method * method.Invoke(null, null); */ using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { Microsoft.CodeAnalysis.Emit.EmitResult result = compilation.Emit(ms); ThrowExceptionIfCompilationFailure(result); ms.Seek(0, System.IO.SeekOrigin.Begin); System.Reflection.Assembly assembly2 = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromStream(ms); #if NET46 // Different in full .Net framework System.Reflection.Assembly assembly3 = Assembly.Load(ms.ToArray()); #endif } // End Using ms }
public CodeGenerator(IEnumerable <Assembly> targetAssemblies, Aspect aspect, bool debugger, bool customMethod) { if (debugger) { _debugger = "true"; } ; if (customMethod) { _customMethod = "true"; } ; // HarmonyLib.Harmony.DEBUG = true; _options = new Options(aspect.ConstraintName, GetTypeByName(aspect.ContextName)[0], aspect.FunctionName, aspect.BeforeCode, aspect.AfterCode); var dd = typeof(Enumerable).GetTypeInfo().Assembly.Location; var coreDir = Directory.GetParent(dd); var refsNames = new[] { typeof(HarmonyLib.Harmony).Assembly.Location, typeof(object).Assembly.Location, typeof(System.Linq.Enumerable).Assembly.Location, typeof(System.Runtime.CompilerServices.DynamicAttribute).Assembly.Location, typeof(Console).GetTypeInfo().Assembly.Location, typeof(FormatterServices).GetTypeInfo().Assembly.Location, typeof(Stack).GetTypeInfo().Assembly.Location, typeof(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo).GetTypeInfo().Assembly.Location, coreDir.FullName + Path.DirectorySeparatorChar + "mscorlib.dll", coreDir.FullName + Path.DirectorySeparatorChar + "netstandard.dll", coreDir.FullName + Path.DirectorySeparatorChar + "System.Runtime.dll", coreDir.FullName + Path.DirectorySeparatorChar + "Microsoft.CSharp.dll", coreDir.FullName + Path.DirectorySeparatorChar + "System.Collections.dll", typeof(Newtonsoft.Json.JsonConvert).Assembly.Location, "OclAspectTest.dll" // "Microsoft.CSharp.dll" }; refsNames = targetAssemblies.Aggregate(refsNames, (current, assembly) => current.AddToArray(assembly.Location)); var refs = refsNames.Select(x => MetadataReference.CreateFromFile(x)); // param.ReferencedAssemblies.Add("System.dll"); // param.ReferencedAssemblies.Add("System.Xml.dll"); // param.ReferencedAssemblies.Add("System.Data.dll"); // param.ReferencedAssemblies.Add("System.Core.dll"); // param.ReferencedAssemblies.Add("System.Xml.Linq.dll"); // param.ReferencedAssemblies.Add("0Harmony.dll"); // param.ReferencedAssemblies.Add(typeof(HarmonyInstance).Assembly.Location); // param.ReferencedAssemblies.Add(typeof(Operation).Assembly.Location); // param.ReferencedAssemblies.Add("Microsoft.CSharp.dll"); // // param.ReferencedAssemblies.Add("Designer.dll"); // new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath); // var codeProvider = new CSharpCodeProvider(); var code = GenerateCodeString(); // var results = codeProvider.CompileAssemblyFromSource(param, code); System.IO.File.WriteAllText(_options.Context.Namespace + "-" + _options.ClassName + "_generated.cs", code); var typeName = "HookClass_" + _options.Context.Assembly.GetName().Name + "." + _options.ClassName; SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(code); CSharpCompilation compilation = CSharpCompilation.Create( typeName + ".dll", options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), syntaxTrees: new[] { tree }, references: refs); //new[] {MetadataReference.CreateFromFile(typeof(object).Assembly.Location)}); using (MemoryStream stream = new MemoryStream()) { Microsoft.CodeAnalysis.Emit.EmitResult compileResult = compilation.Emit(stream); if (!compileResult.Success) { throw new Exception(compileResult.Diagnostics.Join(x => x.ToString())); } _assembly = Assembly.Load(stream.GetBuffer()); } // Type calculator = _assembly.GetType(typeName); // MethodInfo evaluate = calculator.GetMethod("Evaluate"); // string answer = evaluate.Invoke(null, null).ToString(); _instance = _assembly.CreateInstance(typeName); _runtimeCode = _instance.GetType(); // throw new Exception("CodeGen failed!"); }
public void PopulateFeature(IEnumerable <ApplicationPart> parts, ControllerFeature feature) { IEnumerable <Assembly> all = AppDomain.CurrentDomain.GetAssemblies().Where(c => !c.FullName.Contains("DynamicMethods")); IEnumerable <Assembly> allSdk = all; IEnumerable <Assembly> modulesAssemblies = all.Where(c => c.FullName.Contains(".Module") && !c.FullName.Contains("Contract")); foreach (Assembly module in modulesAssemblies) { string moduleName = module.FullName.Split(",")[0]; StringBuilder sb = new StringBuilder(); sb.AppendLine("using System;"); //sb.AppendLine("using ACoreX.Core;"); //sb.AppendLine("using ACoreX.Core.Injector;"); sb.AppendLine("using Microsoft.AspNetCore.Mvc;"); sb.AppendLine("using ACoreX.Authentication.Core;"); //sb.AppendLine("using CRM.Module.Contexts;"); //sb.AppendLine("using Microsoft.AspNetCore.Authorization;"); //sb.AppendLine("using ACoreX.Infrastructure.Authentication;"); sb.AppendLine("using System.Threading.Tasks;"); //sb.AppendLine("using ACoreX.Core.WepApi;"); //sb.AppendLine("using ACoreX.Core.Authentication;"); sb.AppendLine(); sb.AppendFormat("namespace {0}.Controllers {{", moduleName); IEnumerable <global::System.Reflection.TypeInfo> controllers = module.DefinedTypes.Where(c => c.GetMethods().Where(m => m.GetCustomAttributes <WebApiAttribute>().Count() > 0).Count() > 0); foreach (global::System.Reflection.TypeInfo ct in controllers) { string interfaceName = ct.GetInterfaces()[0].FullName; sb.AppendLine(); sb.AppendLine("[ApiController]"); sb.AppendFormat("public class {0}Controller : ControllerBase {{", ct.Name); sb.AppendLine(); sb.AppendFormat(" private {0} context;", interfaceName); sb.AppendLine(); sb.AppendFormat("public {0}Controller({1} context) {{ ", ct.Name, interfaceName); sb.AppendFormat("this.context = context;", interfaceName); sb.AppendLine("}"); IEnumerable <MethodInfo> actions = ct.GetMethods().Where(m => m.GetCustomAttributes <WebApiAttribute>().Count() > 0); foreach (MethodInfo a in actions) { WebApiAttribute attr = a.GetCustomAttribute <WebApiAttribute>(); if (attr.Authorized) { sb.AppendLine("[Authentication]"); } //else //{ // sb.AppendLine("[AllowAnonymous]"); //} switch (attr.Method) { case WebApiMethod.Get: sb.AppendFormat(@"[HttpGet(""{0}"")]", attr.Route); break; case WebApiMethod.Post: sb.AppendFormat(@"[HttpPost(""{0}"")]", attr.Route); break; case WebApiMethod.Put: sb.AppendFormat(@"[HttpPut(""{0}"")]", attr.Route); break; case WebApiMethod.Delete: sb.AppendFormat(@"[HttpDelete(""{0}"")]", attr.Route); break; case WebApiMethod.Head: sb.AppendFormat(@"[HttpHead(""{0}"")]", attr.Route); break; case WebApiMethod.Patch: sb.AppendFormat(@"[HttpPatch(""{0}"")]", attr.Route); break; default: sb.AppendFormat(@"[HttpGet(""{0}"")]", attr.Route); break; } sb.AppendLine(); var routeAttributes = Regex.Matches(attr.Route, @"\{(.*?)\}"); List <string> paramsList = new List <string>(); List <string> paramsValue = new List <string>(); bool hasFile = false; bool isRoute = false; foreach (ParameterInfo p in a.GetParameters()) { //paramsList.Add(String.Format("[FromBody]{0} {1}",p.ParameterType.PrettyName(),p.Name)); foreach (var item in p.ParameterType.GetRuntimeFields()) { if (item.FieldType.Name == "Byte[]") { hasFile = true; } } foreach (var item in routeAttributes) { if (item.ToString().Replace("{", "").Replace("}", "") == p.Name) { isRoute = true; paramsList.Add(string.Format("[FromRoute]{0} {1}{2}", p.ParameterType.GetFriendlyName(), p.Name, p.HasDefaultValue && p.ParameterType.GetFriendlyName() == "string" ? "=" + @"""" + p.DefaultValue + @"""" : p.HasDefaultValue ? "=" + p.DefaultValue.ToString() : "")); } } if (!isRoute) { paramsList.Add(string.Format("{0} {1}{2}", p.ParameterType.GetFriendlyName(), p.Name, p.HasDefaultValue && p.ParameterType.GetFriendlyName() == "string" ? "=" + @"""" + p.DefaultValue + @"""" : p.HasDefaultValue ? "=" + p.DefaultValue.ToString() : "")); } paramsValue.Add(string.Format("{0}", p.Name)); isRoute = false; } string paramsStr = ""; if (hasFile) { paramsStr = "[FromForm] "; } paramsStr += string.Join(",", paramsList); string valueStr = string.Join(",", paramsValue); sb.AppendFormat("public {3} {1} {0}({2}){{", a.Name, a.ReturnType.GetFriendlyName() == "System.Void" ? "void" : a.ReturnType.GetFriendlyName(), paramsStr, a.ReturnType.BaseType == typeof(Task) ? "async" : ""); sb.AppendFormat("{0} {3} context.{1}({2});", a.ReturnType != typeof(void) ? "return" : "", a.Name, valueStr, a.ReturnType.BaseType == typeof(Task) ? "await" : ""); sb.AppendLine("}"); // sb.AppendLine(); } sb.AppendLine("}"); } sb.AppendLine("}"); Debug.WriteLine(sb.ToString()); SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(sb.ToString()); string assemblyName = $"{moduleName}.Controllers"; List <MetadataReference> references = new List <MetadataReference>(); foreach (Assembly r in allSdk) { references.Add(MetadataReference.CreateFromFile(r.Location)); } references.Add(MetadataReference.CreateFromFile(module.Location)); // CSharpCompilation compilation = CSharpCompilation.Create( assemblyName, syntaxTrees: new[] { syntaxTree }, references: references, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); using (MemoryStream ms = new MemoryStream()) { Microsoft.CodeAnalysis.Emit.EmitResult result = compilation.Emit(ms); if (!result.Success) { IEnumerable <Diagnostic> failures = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error); foreach (Diagnostic diagnostic in failures) { Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage()); throw new Exception(string.Format("{0}: {1}", diagnostic.Id, diagnostic.GetMessage())); } } else { ms.Seek(0, SeekOrigin.Begin); Assembly assembly = AssemblyLoadContext.Default.LoadFromStream(ms); Type[] candidates = assembly.GetExportedTypes(); foreach (Type candidate in candidates) { feature.Controllers.Add(candidate.GetTypeInfo()); } } } } }
public SoftmakeAll.SDK.OperationResult <System.Text.Json.JsonElement> CompileTo(System.IO.Stream Stream) { if (Stream == null) { throw new System.Exception(System.String.Format(SoftmakeAll.SDK.NetReflector.Compiler.NullOrEmptyMessage, "Stream")); } if (System.String.IsNullOrWhiteSpace(this.OutputFileName)) { throw new System.Exception(System.String.Format(SoftmakeAll.SDK.NetReflector.Compiler.NullOrEmptyMessage, "OutputFileName")); } if ((this.CodeFiles == null) || (!(this.CodeFiles.Any()))) { throw new System.Exception(System.String.Format(SoftmakeAll.SDK.NetReflector.Compiler.NullOrEmptyMessage, "Code")); } System.Collections.Generic.List <Microsoft.CodeAnalysis.SyntaxTree> SyntaxTrees = new System.Collections.Generic.List <Microsoft.CodeAnalysis.SyntaxTree>(); foreach (System.Collections.Generic.KeyValuePair <System.String, System.String> CodeFile in this.CodeFiles.Where(c => (!(System.String.IsNullOrWhiteSpace(c.Value))))) { SyntaxTrees.Add(Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(CodeFile.Value.Trim()).GetRoot().NormalizeWhitespace(new System.String(' ', this.IndentSize), System.Environment.NewLine, false).ToFullString(), null, CodeFile.Key)); } if (!(SyntaxTrees.Any())) { throw new System.Exception(System.String.Format(SoftmakeAll.SDK.NetReflector.Compiler.NullOrEmptyMessage, "Code")); } SoftmakeAll.SDK.OperationResult <System.Text.Json.JsonElement> CompileResult = new SoftmakeAll.SDK.OperationResult <System.Text.Json.JsonElement>(); System.Collections.Generic.List <Microsoft.CodeAnalysis.MetadataReference> CurrentReferences = new System.Collections.Generic.List <Microsoft.CodeAnalysis.MetadataReference>(); if (!(System.String.IsNullOrWhiteSpace(this.DefaultReferencesDirectoryPath))) { if (!(System.IO.Directory.Exists(this.DefaultReferencesDirectoryPath))) { throw new System.IO.DirectoryNotFoundException(); } else { foreach (System.String ReferencedFile in System.IO.Directory.GetFiles(this.DefaultReferencesDirectoryPath, "*.*", System.IO.SearchOption.AllDirectories)) { CurrentReferences.Add(Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(ReferencedFile)); } } } if ((this.AdditionalReferences != null) && (this.AdditionalReferences.Any())) { foreach (System.String ReferencedFile in this.AdditionalReferences) { CurrentReferences.Add(Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(ReferencedFile)); } } Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions CSharpCompilationOptions = new Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions ( optimizationLevel: Microsoft.CodeAnalysis.OptimizationLevel.Release, outputKind: (Microsoft.CodeAnalysis.OutputKind) this.OutputKind, platform: (Microsoft.CodeAnalysis.Platform) this.Platform ); System.IO.FileInfo OutputFileNameInfo = new System.IO.FileInfo(this.OutputFileName); System.String AssemblyName = OutputFileNameInfo.Name.Substring(0, OutputFileNameInfo.Name.Length - OutputFileNameInfo.Extension.Length); Microsoft.CodeAnalysis.CSharp.CSharpCompilation CSharpCompilation = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create(AssemblyName, SyntaxTrees, CurrentReferences, CSharpCompilationOptions); Microsoft.CodeAnalysis.Emit.EmitResult EmitResult = CSharpCompilation.Emit(Stream); if (EmitResult.Diagnostics.Length > 0) { System.Collections.Generic.List <System.Text.Json.JsonElement> Diagnostics = new System.Collections.Generic.List <System.Text.Json.JsonElement>(); foreach (Microsoft.CodeAnalysis.Diagnostic Diagnostic in EmitResult.Diagnostics) { if ((this.OmitCompilationHiddenSeverity) && (Diagnostic.Descriptor.DefaultSeverity == Microsoft.CodeAnalysis.DiagnosticSeverity.Hidden)) { continue; } if ((this.OmitCompilationInfoSeverity) && (Diagnostic.Descriptor.DefaultSeverity == Microsoft.CodeAnalysis.DiagnosticSeverity.Info)) { continue; } if ((this.OmitCompilationWarningSeverity) && (Diagnostic.Descriptor.DefaultSeverity == Microsoft.CodeAnalysis.DiagnosticSeverity.Warning)) { continue; } System.String ID = Diagnostic.Descriptor.Id; if (ID == "CS8019") // CS8019 = using directives { continue; } System.String Severity = Diagnostic.Descriptor.DefaultSeverity.ToString(); System.String Category = Diagnostic.Descriptor.Category; System.String Message = Diagnostic.GetMessage(); System.Text.Json.JsonElement Location = new System.Text.Json.JsonElement(); if ((Diagnostic.Location != null) && (Diagnostic.Location.SourceSpan != null) && (!(Diagnostic.Location.SourceSpan.IsEmpty))) { Microsoft.CodeAnalysis.FileLinePositionSpan FileLinePositionSpan = Diagnostic.Location.GetMappedLineSpan(); System.Nullable <System.Int32> Line = null; System.Nullable <System.Int32> Character = null; if (FileLinePositionSpan.IsValid) { Line = FileLinePositionSpan.StartLinePosition.Line; Character = FileLinePositionSpan.StartLinePosition.Character; } Location = new { Diagnostic.Location.SourceTree.FilePath, Line, Character, Code = Diagnostic.Location.SourceTree.ToString().Substring(Diagnostic.Location.SourceSpan.Start, Diagnostic.Location.SourceSpan.End - Diagnostic.Location.SourceSpan.Start) }.ToJsonElement(); } Diagnostics.Add(new { Severity, Category, ID, Message, Location }.ToJsonElement()); } CompileResult.Data = Diagnostics.ToJsonElement(); } CompileResult.ExitCode = System.Convert.ToInt16((!(EmitResult.Success)) ? -1 : CompileResult.Data.IsValid() ? 1 : 0); return(CompileResult); }
public static void CreateEditorInstance() { lock (instanceCreateLocked) { if (instance == null) { instance = new ScriptEditor(); instance.FormClosing += (form, e) => { e.Cancel = true; ((Form)form).Visible = false; //if (editor.DialogResult == DialogResult.OK) //{ // try // { // string code = editor.Code; // //string code = editor.roslynHost.GetDocument(editor.docId).GetTextAsync().Result.ToString(); // //ret = codeFunc(code); // //var scrOpt = scriptOptions // // //.WithReferences(typeof(ScriptEditor).Assembly, typeof(MainController).Assembly) // // .WithReferences( // // editor.roslynHost.DefaultReferences // // .Concat(scriptOptions.MetadataReferences)) // // //.Concat( // // // scriptOptions.MetadataResolver)) // // //typeof(Enumerable).Assembly.GetReferencedAssemblies())) // // .WithImports(editor.roslynHost.DefaultImports); // var script = CSharpScript.Create( // code, // scriptOptions.WithImports(roslynHost.DefaultImports), // globalContext.GetType()); // var task = script.RunAsync(globalContext); // task.Wait(); // var ret = task.Result; // task.Dispose(); // File.WriteAllText("Code\\_last", editor.Code); // GC.Collect(); // } // catch (Exception ex) // { // if (exceptionHandler != null) // { // exceptionHandler(ex); // e.Cancel = true; // } // else throw; // } //} }; instance.button1.Click += (_, __) => { instance.button1.Enabled = false; cancellationTokenSource = new CancellationTokenSource(); Context.Reset(cancellationTokenSource); new Thread(() => { try { Guid guid = Guid.NewGuid(); string code = Code; File.WriteAllText("Code\\_last", code); //var script = CSharpScript.Create( // code, // scriptOptions // .WithImports(roslynHost.DefaultImports) // .WithEmitDebugInformation(true), // typeof(GlobalContext)); //var task = script.RunAsync(Context, Context.CancellationToken); //task.Wait(); //ScriptState scriptState = task.Result; //task.Dispose(); //GC.Collect(); //ScriptFinished?.Invoke(scriptState); //System.Diagnostics.Debug.WriteLine(scriptState.ReturnValue); InteractiveAssemblyLoader ial = new InteractiveAssemblyLoader(); //RoslynPad.Roslyn.Scripting.ScriptRunner scriptRunner = new RoslynPad.Roslyn.Scripting.ScriptRunner( // Code, // references: roslynHost.DefaultReferences, // usings: roslynHost.DefaultImports, // workingDirectory: $"{Environment.CurrentDirectory}\\Plugins", // assemblyLoader: ial // ); CSharpParseOptions parseOptions = CSharpParseOptions.Default .WithKind(SourceCodeKind.Script); //CSharpParseOptions parseOptions = new CSharpParseOptions( // documentationMode: DocumentationMode.Diagnose, // kind: SourceCodeKind.Script); string path = $"{Environment.CurrentDirectory}\\AsmTmp\\{guid.ToString().Substring(0, 8)}-{guid.GetHashCode()}"; string plugins = $"{Environment.CurrentDirectory}\\Plugins"; string className = "Submission"; string codePath = $"{path}\\{guid}.csx"; Directory.CreateDirectory(path); File.WriteAllText(codePath, Code); CSharpCompilationOptions compilationOptions = new CSharpCompilationOptions( OutputKind.DynamicallyLinkedLibrary, mainTypeName: null, scriptClassName: className, usings: roslynHost.DefaultImports, allowUnsafe: true, sourceReferenceResolver: new SourceFileResolver(new[] { Environment.CurrentDirectory, plugins, path }, Environment.CurrentDirectory), metadataReferenceResolver: ScriptMetadataResolver .Default .WithBaseDirectory(Environment.CurrentDirectory) .WithSearchPaths(plugins, Environment.CurrentDirectory, path), assemblyIdentityComparer: AssemblyIdentityComparer.Default ); SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText( Code, options: parseOptions, path: codePath, encoding: Encoding.Unicode, cancellationToken: cancellationTokenSource.Token); CSharpCompilation compilation = CSharpCompilation.CreateScriptCompilation( guid.ToString(), syntaxTree, roslynHost.DefaultReferences, options: compilationOptions, //previousScriptCompilation: previous, globalsType: typeof(GlobalContext)); //compilation = compilation.AddReferences(compilation.DirectiveReferences); foreach (MetadataReference item in compilation.DirectiveReferences) { string asmName = item.Display.Substring(item.Display.LastIndexOf('\\') + 1); asmName = asmName.Substring(0, asmName.Length - 4); //var asmid = // new AssemblyIdentity(asmName); //ial.RegisterDependency(asmid, item.Display); //Assembly.LoadFrom(item.Display); } Microsoft.CodeAnalysis.Emit.EmitResult emit = compilation.Emit($"{path}\\{guid}.dll", $"{path}\\{guid}.pdb", $"{path}\\{guid}.xml", cancellationToken: cancellationTokenSource.Token); previous = compilation; IMethodSymbol entryPoint = compilation.GetEntryPoint(cancellationTokenSource.Token); assemblyLoadContext?.Unload(); assemblyLoadContext = new AssemblyLoadContext(guid.ToString(), true); using FileStream fs = new FileStream($"{path}\\{guid}.dll", FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); assemblyLoadContext.LoadFromStream(fs); Assembly asm = assemblyLoadContext.LoadFromAssemblyPath($"{path}\\{guid}.dll"); assemblyLoadContext.Resolving += AssemblyLoadContext_Resolving; //Assembly asm = Assembly.LoadFrom($"{path}\\{guid}.dll"); //ial.RegisterDependency(asm); string BuildQualifiedName( string qualifier, string name) => !string.IsNullOrEmpty(qualifier) ? string.Concat(qualifier, ".", name) : name; var entryPointTypeName = BuildQualifiedName( entryPoint.ContainingNamespace.MetadataName, entryPoint.ContainingType.MetadataName); var entryPointMethodName = entryPoint.MetadataName; var entryPointType = asm.GetType(entryPointTypeName, throwOnError: true, ignoreCase: false); var runtimeEntryPoint = entryPointType.GetTypeInfo().GetDeclaredMethod(entryPointMethodName); var executor = (Func <object[], Task <object> >)runtimeEntryPoint.CreateDelegate(typeof(Func <object[], Task <object> >)); object[] vs = new object[3]; vs[0] = Context; var result = executor.Invoke(vs); if (result.IsFaulted) { SctiptException?.Invoke(result.Exception.InnerException); instance.Invoke((Action)(() => instance.propertyGrid.SelectedObject = new ScriptResult(Context, vs[1], result.Exception))); } else { System.Diagnostics.Debug.WriteLine(result.Result); instance.Invoke((Action)(() => instance.propertyGrid.SelectedObject = new ScriptResult(Context, vs[1], result.Result))); } //var compilation = script.GetCompilation() // .WithAssemblyName(guid.ToString()) // .WithOptions(compilation.Options.); //compilation.Options. //Directory.CreateDirectory("AsmTmp"); ////compilation.WithAssemblyName(); //var emit = compilation.Emit($"AsmTmp\\{guid}.dll", $"AsmTmp\\{guid}.pdb", $"AsmTmp\\{guid}.xml", cancellationToken: cancellationTokenSource.Token); } catch (Exception ex) { SctiptException?.Invoke(ex); } finally { // Выполнение в UI потоке instance.Invoke((Action)(() => instance.button1.Enabled = true)); GC.Collect(); } }) { Name = "ScriptThread" }.Start(); }; instance.button2.Click += (_, __) => { cancellationTokenSource?.Cancel(true); }; } }