public List <QueryResult> CompileAndRun(string code, string mode, TextWriter textWriter) { SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(code); var compilation = CodeAnalysisService.CreateCompilation(syntaxTree); using (var stream = new MemoryStream()) { EmitResult result = compilation.Emit(stream); if (result.Success) { var assembly = Assembly.Load(stream.GetBuffer()); Module module = assembly.GetModules()[0]; if (module == null) { throw new Exception("Module is null"); } Type mt = module.GetType("MongoSharp.Query.QueryExecutor"); if (mt == null) { throw new Exception("Type is null"); } MethodInfo methInfo = mt.GetMethod("RunQuery"); if (methInfo == null) { throw new Exception("MethodInfo is null"); } var results = (List <QueryResult>)methInfo.Invoke(null, new[] { textWriter }); return(results); } int lineNbr = GetCodeStartLineNumber(code) - 1; var errors = (from x in result.Diagnostics where x.Severity == DiagnosticSeverity.Error select x).ToList(); string text = errors.Aggregate("Compile error: ", (current, ce) => current + ("\r\n" + GetErrorText(ce, lineNbr))); throw new Exception(text); } }
public List <Type> CompileModelCode(string code, string theNamespace) { var sb = new StringBuilder(); sb.AppendLine("using System;"); sb.AppendLine("using System.Linq;"); sb.AppendLine("using MongoDB.Bson;"); sb.AppendLine("using MongoDB.Bson.Serialization.Attributes;"); sb.AppendLine("using MongoDB.Driver;"); sb.AppendLine("using MongoDB.Driver.Linq;"); sb.AppendLine("using System.Collections.Generic;"); sb.AppendLine("using MongoSharp.Model;"); code = sb.ToString() + "namespace " + theNamespace + " {\r\n" + code + "\r\n}"; SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(code); var compilation = CodeAnalysisService.CreateCompilation(syntaxTree); using (var stream = new MemoryStream()) { EmitResult result = compilation.Emit(stream); if (result.Success) { var assembly = Assembly.Load(stream.GetBuffer()); Module module = assembly.GetModules()[0]; if (module == null) { throw new Exception("Module is null"); } List <Type> types = (from t in module.GetTypes() where t.IsClass && t.Namespace == theNamespace select t).ToList(); return(types); } else { var errors = (from x in result.Diagnostics where x.Severity == DiagnosticSeverity.Error select x).ToList(); string text = errors.Aggregate("Compile error: ", (current, ce) => current + ("\r\n" + ce.GetMessage())); throw new Exception(text); } } }