private Tuple <CompilerResults, string> Compile(TypeContext context, string name) { var key = Common.StrToMD5(name); string className = "C" + key; var assemblyPath = CatchPath + className + ".dll"; if (_disposed) { throw new ObjectDisposedException(GetType().Name); } var compileUnit = GetCodeCompileUnit(context.ClassName, context.TemplateContent, context.Namespaces, context.TemplateType, context.ModelType); var @params = new CompilerParameters { GenerateInMemory = true, OutputAssembly = @assemblyPath, GenerateExecutable = false, IncludeDebugInformation = false, CompilerOptions = "/target:library /optimize" }; var assemblies = CompilerServicesUtility .GetLoadedAssemblies() .Where(a => !a.IsDynamic) .Select(a => a.Location); var includeAssemblies = (IncludeAssemblies() ?? Enumerable.Empty <string>()); assemblies = assemblies.Concat(includeAssemblies) .Select(a => a.ToUpperInvariant()) .Where(a => !string.IsNullOrWhiteSpace(a)) .Distinct(); @params.ReferencedAssemblies.AddRange(assemblies.ToArray()); string sourceCode = null; // if (Debug) // { var builder = new StringBuilder(); using (var writer = new StringWriter(builder, CultureInfo.InvariantCulture)) { _codeDomProvider.GenerateCodeFromCompileUnit(compileUnit, writer, new CodeGeneratorOptions()); sourceCode = builder.ToString(); } // CompileType(context.ClassName, sourceCode); // } CompilerResults r = _codeDomProvider.CompileAssemblyFromDom(@params, compileUnit); return(Tuple.Create(r, sourceCode)); }
private Tuple <CompilerResults, string> Compile(TypeContext context) { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } var compileUnit = GetCodeCompileUnit(context.ClassName, context.TemplateContent, context.Namespaces, context.TemplateType, context.ModelType); var @params = new CompilerParameters { GenerateInMemory = true, GenerateExecutable = false, IncludeDebugInformation = false, CompilerOptions = "/target:library /optimize" }; var assemblies = CompilerServicesUtility .GetLoadedAssemblies() .Where(a => !a.IsDynamic) .Select(a => a.Location); var includeAssemblies = (IncludeAssemblies() ?? Enumerable.Empty <string>()); assemblies = assemblies.Concat(includeAssemblies) .Select(a => a) .Where(a => !string.IsNullOrWhiteSpace(a)) .Distinct(); //@params.ReferencedAssemblies.AddRange(assemblies.ToArray()); @params.ReferencedAssemblies.Add("mscorlib.dll"); @params.ReferencedAssemblies.Add("System.dll"); @params.ReferencedAssemblies.Add("System.Web.Razor.dll"); @params.ReferencedAssemblies.Add("DWServer.exe"); @params.ReferencedAssemblies.Add("System.Core.dll"); string sourceCode = null; if (Debug) { var builder = new StringBuilder(); using (var writer = new StringWriter(builder, CultureInfo.InvariantCulture)) { _codeDomProvider.GenerateCodeFromCompileUnit(compileUnit, writer, new CodeGeneratorOptions()); sourceCode = builder.ToString(); } sourceCode += string.Join("\n", assemblies.ToArray()); } return(Tuple.Create(_codeDomProvider.CompileAssemblyFromDom(@params, compileUnit), sourceCode)); }
private Tuple <CompilerResults, string> Compile(TypeContext context) { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } var compileUnit = GetCodeCompileUnit(context.ClassName, context.TemplateContent, context.Namespaces, context.TemplateType, context.ModelType); var @params = new CompilerParameters { GenerateInMemory = true, GenerateExecutable = false, IncludeDebugInformation = false, CompilerOptions = "/target:library /optimize /define:RAZORENGINE" }; var assemblies = CompilerServicesUtility .GetLoadedAssemblies() .Where(a => !a.IsDynamic && File.Exists(a.Location)) .GroupBy(a => a.GetName().Name).Select(grp => grp.First(y => y.GetName().Version == grp.Max(x => x.GetName().Version))) // only select distinct assemblies based on FullName to avoid loading duplicate assemblies .Select(a => a.Location); var includeAssemblies = (IncludeAssemblies() ?? Enumerable.Empty <string>()); assemblies = assemblies.Concat(includeAssemblies) .Where(a => !string.IsNullOrWhiteSpace(a)) .Distinct(StringComparer.InvariantCultureIgnoreCase); @params.ReferencedAssemblies.AddRange(assemblies.ToArray()); string sourceCode = null; if (Debug) { var builder = new StringBuilder(); using (var writer = new StringWriter(builder, CultureInfo.InvariantCulture)) { _codeDomProvider.GenerateCodeFromCompileUnit(compileUnit, writer, new CodeGeneratorOptions()); sourceCode = builder.ToString(); } } return(Tuple.Create(_codeDomProvider.CompileAssemblyFromDom(@params, compileUnit), sourceCode)); }
private byte[] CompileByte(string originalClassName, string originalText) { Console.WriteLine(assemblieslist); if (assemblieslist == null) { string replstr = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "file:///" : "file://"; var assemblies = CompilerServicesUtility .GetLoadedAssemblies() .Where(a => !a.IsDynamic && File.Exists(a.CodeBase.Replace(replstr, ""))) .Select(a => (a.CodeBase.Replace(replstr, ""))); int c = assemblies.Count(); assemblieslist = new MetadataReference[c]; int i = 0; foreach (string item in assemblies) { assemblieslist[i] = (MetadataReference.CreateFromFile(item)); i++; } } CSharpCompilation compilation = null; var syntaxTree = CSharpSyntaxTree.ParseText(originalText); // 指定编译选项。 var assemblyName = $"{originalClassName}.g"; compilation = CSharpCompilation.Create(assemblyName, new[] { syntaxTree }, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) .AddReferences( // 这算是偷懒了吗?我把 .NET Core 运行时用到的那些引用都加入到引用了。 // 加入引用是必要的,不然连 object 类型都是没有的,肯定编译不通过。 //AppDomain.CurrentDomain.GetAssemblies().Select(x => MetadataReference.CreateFromFile(x.Location)) assemblieslist ); // 编译到内存流中。 byte [] buff = null; using (var ms = new MemoryStream()) { var result = compilation.Emit(ms); if (result.Success) { ms.Seek(0, SeekOrigin.Begin); buff = ms.ToArray(); } else { string errmsg = ""; for (int i1 = 0; i1 < result.Diagnostics.Length; i1++) { errmsg += result.Diagnostics[i1] + "\r\n"; } throw new Exception(errmsg); } ms.Close(); } /* * for (int i1=0;i1< list.Length;i1++) * { * list[i1] = null; * } */ return(buff); // } //catch (Exception e) //{ //} return(null); }