public CompileAssemblyFromSource ( |
||
options | ||
return |
public static Assembly CompileScriptFromSource(string source, CodeDomProvider provider, ref string errors) { StringBuilder errorLog = new StringBuilder(); errors = ""; CompilerParameters compilerParameters = new CompilerParameters(); compilerParameters.GenerateExecutable = false; compilerParameters.GenerateInMemory = true; compilerParameters.IncludeDebugInformation = false; compilerParameters.ReferencedAssemblies.Add("System.dll"); compilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll"); compilerParameters.ReferencedAssemblies.Add("KedrahCore.dll"); compilerParameters.ReferencedAssemblies.Add("TibiaAPI.dll"); compilerParameters.ReferencedAssemblies.Add(System.Reflection.Assembly.GetExecutingAssembly().Location); CompilerResults results = provider.CompileAssemblyFromSource(compilerParameters, source); if (!results.Errors.HasErrors) { return results.CompiledAssembly; } else { foreach (CompilerError error in results.Errors) { errorLog.AppendLine(error.ErrorText); } } errors = errorLog.ToString(); return null; }
/// <summary> /// once the grammar compiles correctly, the code can be built. /// </summary> private void BuildCode() { string language = Grammar.Directives["TinyPG"]["Language"]; CodeDom.CompilerResults Result; CodeDom.CodeDomProvider provider = CodeGeneratorFactory.CreateCodeDomProvider(language); if (provider == null) { Errors.Add("Can't compile " + language + " project."); return; } System.CodeDom.Compiler.CompilerParameters compilerparams = new System.CodeDom.Compiler.CompilerParameters(); compilerparams.GenerateInMemory = true; compilerparams.GenerateExecutable = false; compilerparams.ReferencedAssemblies.Add("System.dll"); compilerparams.ReferencedAssemblies.Add("System.Windows.Forms.dll"); compilerparams.ReferencedAssemblies.Add("System.Drawing.dll"); compilerparams.ReferencedAssemblies.Add("System.Xml.dll"); // reference this assembly to share interfaces (for debugging only) string tinypgfile = Assembly.GetExecutingAssembly().Location; compilerparams.ReferencedAssemblies.Add(tinypgfile); // generate the code with debug interface enabled List <string> sources = new List <string>(); ICodeGenerator generator; foreach (Directive d in Grammar.Directives) { generator = CodeGeneratorFactory.CreateGenerator(d.Name, language); if (generator != null && d.ContainsKey("FileName")) { generator.FileName = d["FileName"]; } if (generator != null && d["Generate"].ToLower() == "true") { sources.Add(generator.Generate(Grammar, true)); } } if (sources.Count > 0) { Result = provider.CompileAssemblyFromSource(compilerparams, sources.ToArray()); if (Result.Errors.Count > 0) { foreach (CodeDom.CompilerError o in Result.Errors) { Errors.Add(o.ErrorText + " on line " + o.Line.ToString()); } } else { assembly = Result.CompiledAssembly; } } }
private void Compile(CodeDom.CodeDomProvider provider, string source) { CodeDom.CompilerParameters param = new CodeDom.CompilerParameters(); param.GenerateExecutable = false; param.IncludeDebugInformation = false; param.GenerateInMemory = true; CodeDom.CompilerResults cr = provider.CompileAssemblyFromSource(param, source); Specialized.StringCollection output = cr.Output; if (cr.Errors.Count != 0) { System.Console.WriteLine("Error invoking scripts."); CodeDom.CompilerErrorCollection es = cr.Errors; foreach (CodeDom.CompilerError s in es) { System.Console.WriteLine(s.ErrorText); } } else { object o = cr.CompiledAssembly.CreateInstance("Script"); System.Type type = o.GetType(); type.InvokeMember("ScriptExecute", Reflection.BindingFlags.InvokeMethod | Reflection.BindingFlags.Default, null, o, null); } }
public static Assembly CompileWithProvider(CodeDomProvider provider, params string[] input) { var param = new System.CodeDom.Compiler.CompilerParameters(); var result = provider.CompileAssemblyFromSource(param, input); foreach (var e in result.Errors) Console.WriteLine("Error occured during compilation {0}", e.ToString()); if (result.Errors.Count > 0) return null; else return result.CompiledAssembly; }
private static Type CreateCodeGeneratorType(System.CodeDom.Compiler.CodeDomProvider compilerProvider, string resourceName, string typeName) { string sourceCode = null; using (Stream sourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)) using (StreamReader reader = new StreamReader(sourceStream)) { sourceCode = reader.ReadToEnd(); } CompilerParameters compilerParams = new CompilerParameters(); compilerParams.CompilerOptions = "/d:PREPROCESSED_TEMPLATE"; compilerParams.GenerateInMemory = true; compilerParams.GenerateExecutable = false; // grab the assemblies by location so that we don't compile against one that we didn't reference compilerParams.ReferencedAssemblies.AddRange(new string[] { typeof(System.CodeDom.Compiler.CodeDomProvider).Assembly.Location, // System.dll typeof(System.Linq.Enumerable).Assembly.Location, // System.Core.dll typeof(System.Data.Objects.ObjectContext).Assembly.Location, // System.Data.Entity.dll typeof(System.Data.Entity.Design.EntityCodeGenerator).Assembly.Location, // System.Data.Entity.Design.dll typeof(System.Data.DbType).Assembly.Location, // System.Data.dll typeof(System.Xml.XmlAttribute).Assembly.Location, // System.Xml.dll typeof(System.Xml.Linq.XElement).Assembly.Location, // System.Xml.Linq.dll }); #if !ENABLE_TEMPLATE_DEBUGGING CompilerResults results = compilerProvider.CompileAssemblyFromSource(compilerParams, sourceCode); #else // enables debugging compilerParams.GenerateInMemory = false; compilerParams.IncludeDebugInformation = true; string baseName = Path.GetFileNameWithoutExtension(Path.GetTempFileName()) + "."; compilerParams.OutputAssembly = Path.Combine(Path.GetTempPath(), baseName + typeName + ".Assembly.dll"); string sourceFileName = Path.Combine(Path.GetTempPath(), baseName + typeName + ".Source." + compilerProvider.FileExtension); File.WriteAllText(sourceFileName, sourceCode); CompilerResults results = compilerProvider.CompileAssemblyFromFile(compilerParams, sourceFileName); #warning DO NOT CHECK IN LIKE THIS, Dynamic Assembly Debugging is enabled #endif if (results.Errors.HasErrors) { string message = results.Errors.OfType <CompilerError>().Aggregate(string.Empty, (accumulated, input) => accumulated == string.Empty ? input.ToString() : accumulated + Environment.NewLine + input.ToString()); throw EDesignUtil.InvalidOperation(message); } return(results.CompiledAssembly.GetType(typeName)); }
/// <summary> /// Compilation from a class file /// </summary> /// <param name="src">Class file</param> public bool LoadSource(string src) { try { cp = CodeDomProvider.CreateProvider("C#"); cpar = new CompilerParameters(); cpar.GenerateInMemory = true; cpar.GenerateExecutable = false; cpar.ReferencedAssemblies.Add("system.dll"); // Compilation and error managment cr = cp.CompileAssemblyFromSource(cpar, src); ObjType = cr.CompiledAssembly.GetType("CuttingTask"); myobj = Activator.CreateInstance(ObjType); calculate = myobj.GetType().GetMethod("CutTask"); return true; } catch { return false; } }
internal Assembly Compile(CodeDomProvider provider, string code) { CompilerParameters parameters = new CompilerParameters(); parameters.ReferencedAssemblies.Add("System.dll"); parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll"); parameters.GenerateInMemory = false; CompilerResults result = provider.CompileAssemblyFromSource(parameters, code); if(result.Errors.Count > 0) { Output.WriteLine("Compiler Errors"); foreach (CompilerError error in result.Errors) { Output.WriteLine(error.Line + "\t" + error.ErrorText); } return null; } return result.CompiledAssembly; }
/// <summary> /// Verifies that <paramref name="source"/> does not compile using the provided compiler. /// </summary> /// <param name="compiler"> /// <see cref="ICodeCompiler"/> instance.</param> /// <param name="options">Compilation options</param> /// <param name="source">Source to compile</param> public static void NotCompiles( CodeDomProvider provider, CompilerParameters options, string source) { if (provider == null) throw new ArgumentNullException("provider"); if (options == null) throw new ArgumentNullException("options"); CompilerResults results = provider.CompileAssemblyFromSource(options, source); if (!results.Errors.HasErrors) throw new CompilationException(provider, options, results, source); }
/// <summary> /// Verifies that <paramref name="source"/> compiles using the provided compiler. /// </summary> /// <param name="compiler"> /// <see cref="ICodeCompiler"/> instance.</param> /// <param name="options">Compilation options</param> /// <param name="source">Source to compile</param> /// <param name="throwOnWarning"> /// true if assertion should throw if any warning. /// </param> public static CompilerResults Compiles(CodeDomProvider provider, CompilerParameters options, string source, bool throwOnWarning) { Assert.IsNotNull(provider); Assert.IsNotNull(options); CompilerResults results = provider.CompileAssemblyFromSource(options, source); if (results.Errors.HasErrors) { DisplaySource(source); DisplayErrors(results, Console.Out); throw new CompilationException(provider, options, results, source); } if (throwOnWarning && results.Errors.HasWarnings) { DisplaySource(source); DisplayErrors(results, Console.Out); throw new CompilationException(provider, options, results, source); } return results; }
/// <summary> /// Compiles the code from the code string /// </summary> /// <param name="compiler"></param> /// <param name="parms"></param> /// <param name="source"></param> /// <returns></returns> public static CompilerResults CompileCode(CodeDomProvider compiler, CompilerParameters parms, string source) { //actually compile the code CompilerResults results = compiler.CompileAssemblyFromSource( parms, source); //Do we have any compiler errors? if (results.Errors.Count > 0) { foreach (CompilerError error in results.Errors) Console.WriteLine("Compile Error:" + error.ErrorText); return null; } return results; }
/// <summary> /// Function to compile .Net C#/VB source codes at runtime /// Adapted from: /// (http://www.digitalcoding.com/Code-Snippets/C-Sharp/C-Code-Snippet-Compile-C-or-VB-source-code-run-time.html) /// </summary> /// <param name="codeProvider">Base class for compiler provider</param> /// <param name="sourceCode">C# or VB source code as a string</param> /// <param name="sourceFile">External file containing C# or VB source code</param> /// <param name="exeFile">File path to create external executable file</param> /// <param name="assemblyName">File path to create external assembly file</param> /// <param name="resourceFiles">Required resource files to compile the code</param> /// /// <param name="errors">String variable to store any errors occurred during the process</param> /// <returns>Return TRUE if successfully compiled the code, else return FALSE</returns> public static bool CompileCode(CodeDomProvider codeProvider, string sourceCode, string sourceFile, string exeFile, string assemblyName, string[] resourceFiles, string[] referencedAssemblies, out string errors, out CompilerResults compilerResults) { // Define parameters to invoke a compiler CompilerParameters compilerParameters = new CompilerParameters(); if (exeFile != null) { // Set the assembly file name to generate. compilerParameters.OutputAssembly = exeFile; // Generate an executable instead of a class library. compilerParameters.GenerateExecutable = true; compilerParameters.GenerateInMemory = false; } else if (assemblyName != null) { // Set the assembly file name to generate. compilerParameters.OutputAssembly = assemblyName; // Generate a class library instead of an executable. compilerParameters.GenerateExecutable = false; compilerParameters.GenerateInMemory = false; } else { // Generate an in-memory class library instead of an executable. compilerParameters.GenerateExecutable = false; compilerParameters.GenerateInMemory = true; } // Generate debug information. compilerParameters.IncludeDebugInformation = true; // Should start displaying warnings. compilerParameters.WarningLevel = 2; // Set whether to treat all warnings as errors. compilerParameters.TreatWarningsAsErrors = false; // Set compiler argument to optimize output. compilerParameters.CompilerOptions = "/optimize"; // Add referenced assemblies if (referencedAssemblies != null) compilerParameters.ReferencedAssemblies.AddRange(referencedAssemblies); // Set a temporary files collection. // The TempFileCollection stores the temporary files // generated during a build in the current directory, // and does not delete them after compilation. //compilerParameters.TempFiles = new TempFileCollection(".", true); compilerParameters.TempFiles = new TempFileCollection(".", false); if (resourceFiles != null && resourceFiles.Length > 0) { foreach (string _ResourceFile in resourceFiles) { // Set the embedded resource file of the assembly. compilerParameters.EmbeddedResources.Add(_ResourceFile); } } try { // Invoke compilation if (sourceFile != null && System.IO.File.Exists(sourceFile)) // source code in external file compilerResults = codeProvider.CompileAssemblyFromFile(compilerParameters, sourceFile); else // source code pass as a string compilerResults = codeProvider.CompileAssemblyFromSource(compilerParameters, sourceCode); if (compilerResults.Errors.Count > 0) { // Return compilation errors errors = ""; foreach (CompilerError compErr in compilerResults.Errors) { errors += "Line number " + compErr.Line + ", Column number " + compErr.Column + ", Error Number: " + compErr.ErrorNumber + ", '" + compErr.ErrorText + ";\r\n\r\n"; } // Return the results of compilation - Failed return false; } else { // no compile errors errors = null; } } catch (Exception exception) { // Error occurred when trying to compile the code errors = exception.Message; compilerResults = null; return false; } // Return the results of compilation - Success return true; }
private void CompilePlugin(FileInfo pluginFile, string pluginClassName, CodeDomProvider pluginsCodeDomProvider, CompilerParameters parameters) { try { string outputAssembly = Path.Combine(this.PluginBaseDirectory, pluginClassName + ".dll"); if (File.Exists(outputAssembly) == false) { string fullPluginSource = File.ReadAllText(pluginFile.FullName); parameters.OutputAssembly = outputAssembly; // uncomment the following two lines for debugin plugins included in your VS project (taken from PapaCharlie9) // parameters.IncludeDebugInformation = true; // parameters.TempFiles = new TempFileCollection(Path.Combine(this.PluginBaseDirectory, "Temp"), true); fullPluginSource = this.PrecompileDirectives(fullPluginSource); fullPluginSource = fullPluginSource.Replace("using PRoCon.Plugin;", "using PRoCon.Core.Plugin;"); if (fullPluginSource.Contains("using PRoCon.Core;") == false) { fullPluginSource = fullPluginSource.Insert(fullPluginSource.IndexOf("using PRoCon.Core.Plugin;"), "\r\nusing PRoCon.Core;\r\n"); } if (fullPluginSource.Contains("using PRoCon.Core.Players;") == false) { fullPluginSource = fullPluginSource.Insert(fullPluginSource.IndexOf("using PRoCon.Core.Plugin;"), "\r\nusing PRoCon.Core.Players;\r\n"); } this.PrintPluginResults(pluginFile, pluginsCodeDomProvider.CompileAssemblyFromSource(parameters, fullPluginSource)); } else { this.WritePluginConsole("Compiling {0}... Skipping", pluginFile.Name); } } catch (Exception) { } }
bool Compile( CodeDomProvider provider, string dataContextCode, PadConfig config, String dllFile ) { if (!dllFile.EndsWith(".dll")) dllFile += ".dll"; dcAutoGenFile = dllFile; CompilerParameters cp = new CompilerParameters(); // Generate a class library. cp.GenerateExecutable = false; // Generate debug information. cp.IncludeDebugInformation = false; // Add assembly references. cp.ReferencedAssemblies.Add("System.dll"); cp.ReferencedAssemblies.Add("Iesi.Collections.dll"); // Save the assembly as a physical file. cp.GenerateInMemory = false; cp.OutputAssembly = dcAutoGenFile; // Set the level at which the compiler // should start displaying warnings. cp.WarningLevel = 3; // Set whether to treat all warnings as errors. cp.TreatWarningsAsErrors = false; // Set compiler argument to optimize output. cp.CompilerOptions = "/optimize"; string workDir = Path.Combine(Path.GetTempPath(), "SpoolPad$temp$" + config.Name); if (!Directory.Exists(workDir)) Directory.CreateDirectory(workDir); foreach (MapConfig map in config.Mappings) { if (map.IsValid) { if (provider.Supports(GeneratorSupport.Resources)) { if (!config.DataContext.AutoGen) { if (map.IsFile) cp.EmbeddedResources.Add(map.Map); else if (map.IsAssembly) { string tempFile = Path.Combine(workDir, Path.GetFileName(map.ResourceName)); TextReader tr = new StreamReader(Assembly.ReflectionOnlyLoadFrom(map.Assembly).GetManifestResourceStream(map.ResourceName)); File.WriteAllText(tempFile, tr.ReadToEnd()); cp.EmbeddedResources.Add(tempFile); } else continue; } else { XDocument doc = null; if (map.IsAssembly) { doc = XDocument.Load(new XmlTextReader(Assembly.ReflectionOnlyLoadFrom(map.Assembly).GetManifestResourceStream(map.ResourceName))); } else if (map.IsFile) { doc = XDocument.Load(map.Map); } else continue; var hibmap = doc.Root; if (hibmap != null) { hibmap.SetAttributeValue("assembly", config.Name); hibmap.SetAttributeValue("namespace", config.DataContextAutoGenNamespace); string tempFile = Path.Combine(workDir, Path.GetFileName(map.Map)); doc.Save(tempFile); cp.EmbeddedResources.Add(tempFile); } } } } } CompilerResults cr = provider.CompileAssemblyFromSource(cp, dataContextCode); Directory.Delete(workDir, true); if (cr.Errors.Count > 0) { // Display compilation errors. _log.ErrorFormat("Errors building {0}", cr.PathToAssembly); foreach (CompilerError ce in cr.Errors) { _log.DebugFormat(" {0}", ce.ToString()); } } else { _log.DebugFormat("Source built into {0} successfully.", cr.PathToAssembly); } // Return the results of compilation. if (cr.Errors.Count > 0) { return false; } else { return true; } }
private static Assembly CompileInternal(String outputAssembly, IEnumerable<String> references, CodeDomProvider provider, CompilerErrorCollection Errors, Template tmp) { var options = new CompilerParameters(); foreach (var str in references) { options.ReferencedAssemblies.Add(str); } options.WarningLevel = 4; CompilerResults results = null; if (Debug) { #region 调试状态,把生成的类文件和最终dll输出到XTemp目录下 var tempPath = XTrace.TempPath; //if (!String.IsNullOrEmpty(outputAssembly)) tempPath = Path.Combine(tempPath, Path.GetFileNameWithoutExtension(outputAssembly)); if (!String.IsNullOrEmpty(outputAssembly) && !outputAssembly.Equals(".dll")) tempPath = Path.Combine(tempPath, Path.GetFileNameWithoutExtension(outputAssembly)); if (!String.IsNullOrEmpty(tempPath) && !Directory.Exists(tempPath)) Directory.CreateDirectory(tempPath); var files = new List<String>(); foreach (var item in tmp.Templates) { if (item.Included) continue; String name = item.Name.EndsWith(".cs", StringComparison.OrdinalIgnoreCase) ? item.Name : item.ClassName; // 猜测后缀 Int32 p = name.LastIndexOf("_"); if (p > 0 && name.Length - p <= 5) name = name.Substring(0, p) + "." + name.Substring(p + 1, name.Length - p - 1); else if (!name.EndsWith(".cs", StringComparison.OrdinalIgnoreCase)) name += ".cs"; name = Path.Combine(tempPath, name); File.WriteAllText(name, item.Source, Encoding.UTF8); files.Add(name); } #endregion if (!String.IsNullOrEmpty(outputAssembly) && !outputAssembly.Equals(".dll")) { options.TempFiles = new TempFileCollection(tempPath, false); options.OutputAssembly = Path.Combine(tempPath, outputAssembly); options.GenerateInMemory = true; options.IncludeDebugInformation = true; } results = provider.CompileAssemblyFromFile(options, files.ToArray()); } else { List<String> sources = new List<String>(); foreach (var item in tmp.Templates) { sources.Add(item.Source); } options.GenerateInMemory = true; results = provider.CompileAssemblyFromSource(options, sources.ToArray()); } #region 编译错误处理 if (results.Errors.Count > 0) { Errors.AddRange(results.Errors); var sb = new StringBuilder(); CompilerError err = null; foreach (CompilerError error in results.Errors) { error.ErrorText = error.ErrorText; //if (String.IsNullOrEmpty(error.FileName)) error.FileName = inputFile; if (!error.IsWarning) { String msg = error.ToString(); if (sb.Length < 1) { String code = null; // 屏蔽因为计算错误行而导致的二次错误 try { code = tmp.FindBlockCode(error.FileName, error.Line); } catch { } if (code != null) { msg += Environment.NewLine; msg += code; } err = error; } else sb.AppendLine(); sb.Append(msg); } } if (sb.Length > 0) { TemplateException ex = new TemplateException(sb.ToString()); ex.Error = err; throw ex; } } else { try { options.TempFiles.Delete(); } catch { } } #endregion if (!results.Errors.HasErrors) { try { return results.CompiledAssembly; } catch { } } return null; }
private static Assembly Compile(CodeDomProvider provider, string sourceCode, out TempFileCollection temporaryFiles) { var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.dll", "System.Core.dll", "Microsoft.CSharp.dll", typeof(JSIL.Meta.JSIgnore).Assembly.Location }) { CompilerOptions = "/unsafe", GenerateExecutable = true, GenerateInMemory = false, IncludeDebugInformation = true, TempFiles = new TempFileCollection(TempPath, true) }; var results = provider.CompileAssemblyFromSource(parameters, sourceCode); if (results.Errors.Count > 0) { throw new Exception( String.Join(Environment.NewLine, results.Errors.Cast<CompilerError>().Select((ce) => ce.ToString()).ToArray()) ); } temporaryFiles = results.TempFiles; return results.CompiledAssembly; }
private CompilerResults _compileScript(string source, string reference, CodeDomProvider provider) { //ICodeCompiler compiler=provider.CreateCompiler(); CompilerParameters prams = new CompilerParameters(); CompilerResults results; /* set pramaters */ prams.GenerateExecutable = false; prams.IncludeDebugInformation = false; prams.GenerateInMemory = true; if(reference == null) { prams.ReferencedAssemblies.Add("System.Windows.Forms.dll"); prams.ReferencedAssemblies.Add("System.dll"); } /* compile */ results = provider.CompileAssemblyFromSource(prams, source); return null; }
private Assembly Compile(CodeDomProvider provider, string source) { m_sCompileErrors.Clear(); CompilerParameters param = new CompilerParameters(); param.GenerateExecutable = false; param.IncludeDebugInformation = false; param.GenerateInMemory = true; param.TreatWarningsAsErrors = false; param.WarningLevel = 2; foreach (string s in m_oAssemblies) param.ReferencedAssemblies.Add(s); CompilerResults cr = provider.CompileAssemblyFromSource(param, source); if (cr.Errors.Count != 0) { m_sCompileErrors.Add("Error Compiling the model:"); CompilerErrorCollection es = cr.Errors; foreach (CompilerError s in es) { m_sCompileErrors.Add(" Error at Line,Col: " + s.Line + "," + s.Column + " error number: " + s.ErrorNumber + " " + s.ErrorText); } return null; } return cr.CompiledAssembly; }
private void CompilePlugin(FileInfo pluginFile, string pluginClassName, CodeDomProvider pluginsCodeDomProvider, CompilerParameters parameters) { try { string outputAssembly = Path.Combine(this.PluginBaseDirectory, pluginClassName + ".dll"); if (File.Exists(outputAssembly) == false) { string fullPluginSource = File.ReadAllText(pluginFile.FullName); parameters.OutputAssembly = outputAssembly; fullPluginSource = this.PrecompileDirectives(fullPluginSource); fullPluginSource = fullPluginSource.Replace("using PRoCon.Plugin;", "using PRoCon.Core.Plugin;"); if (fullPluginSource.Contains("using PRoCon.Core;") == false) { fullPluginSource = fullPluginSource.Insert(fullPluginSource.IndexOf("using PRoCon.Core.Plugin;"), "\r\nusing PRoCon.Core;\r\n"); } if (fullPluginSource.Contains("using PRoCon.Core.Players;") == false) { fullPluginSource = fullPluginSource.Insert(fullPluginSource.IndexOf("using PRoCon.Core.Plugin;"), "\r\nusing PRoCon.Core.Players;\r\n"); } this.PrintPluginResults(pluginFile, pluginsCodeDomProvider.CompileAssemblyFromSource(parameters, fullPluginSource)); } else { this.WritePluginConsole("Compiling {0}... Skipping", pluginFile.Name); } } catch (Exception) { } }
private string CompileModule( CodeDomProvider codeProvider, string targetDirectory, List<AspViewFile> files, ReferencedAssembly[] references, bool createAssembly, string[] modulesToAdd) { string prefix = string.IsNullOrEmpty(options.GeneratedAssemblyNamePrefix) ? null : options.GeneratedAssemblyNamePrefix + "."; if (!createAssembly) { parameters.CompilerOptions = "/t:module"; parameters.OutputAssembly = Path.Combine(targetDirectory, string.Format("{0}CompiledViews.{1}.netmodule", prefix, codeProvider.FileExtension)); } else parameters.OutputAssembly = Path.Combine(targetDirectory, prefix + "CompiledViews.dll"); List<ReferencedAssembly> actualReferences = new List<ReferencedAssembly>(); if (options.References != null) actualReferences.AddRange(options.References); if (references != null) actualReferences.AddRange(references); foreach (ReferencedAssembly reference in actualReferences) { string assemblyName = reference.Name; if (reference.Source == ReferencedAssembly.AssemblySource.BinDirectory) assemblyName = Path.Combine(targetDirectory, assemblyName); parameters.CompilerOptions += " /r:\"" + assemblyName + "\""; } if (modulesToAdd != null && modulesToAdd.Length > 0) { StringBuilder sb = new StringBuilder(); sb.Append(" /addmodule: "); foreach (string moduleToAdd in modulesToAdd) sb.Append(Path.Combine(targetDirectory, moduleToAdd)); parameters.CompilerOptions += "\"" + sb.ToString() + "\""; } CompilerResults results; if (options.KeepTemporarySourceFiles) { string targetTemporarySourceFilesDirectory = Path.Combine(targetDirectory, options.TemporarySourceFilesDirectory); List<string> fileNames = new List<string>(files.Count); foreach (AspViewFile file in files) fileNames.Add(Path.Combine(targetTemporarySourceFilesDirectory, file.FileName)); results = codeProvider.CompileAssemblyFromFile(parameters, fileNames.ToArray()); } else { List<string> sources = new List<string>(files.Count); foreach (AspViewFile file in files) sources.Add(file.ConcreteClass); results = codeProvider.CompileAssemblyFromSource(parameters, sources.ToArray()); } if (results.Errors.Count > 0) { StringBuilder message = new StringBuilder(); foreach (CompilerError err in results.Errors) message.AppendLine(err.ToString()); throw new Exception(string.Format( "Error while compiling'':\r\n{0}", message.ToString())); } return results.PathToAssembly; }
public CompilerErrorCollection Compile() { if (!this.HtmlPage) { CodeCompiler = CodeDomProvider.CreateProvider("CSharp"); CodeParameters = new CompilerParameters(); CodeParameters.CompilerOptions = "/lib:C:\\inetpub\\wwwroot\\bin"; CodeParameters.GenerateInMemory = this.GenerateInMemory; CodeParameters.ReferencedAssemblies.AddRange(this.References); CodeParameters.WarningLevel = this.WarnLevel; /* Build the assembly */ string tmpcode = this.Code; BlazeGames_CodeCompiler BGxCodeCompiler = new BlazeGames_CodeCompiler(); tmpcode = BGxCodeCompiler.CompileToCSharp(tmpcode); CompilerResults CodeCompiled = CodeCompiler.CompileAssemblyFromSource(CodeParameters, tmpcode); /* Check for errors */ if (CodeCompiled.Errors.HasErrors) return CodeCompiled.Errors; this.CompiledCode = System.IO.File.ReadAllBytes(CodeCompiled.PathToAssembly); this.Compiled = true; this.Save(); } else this.Save(); return null; }
public bool Compile() { switch (Language) { case Languages.CSharp: source = "namespace UserScript\r\n{\r\nusing System;\r\nusing System.Dynamic;\r\n" + "public class RunScript" + count.ToString() + "\r\n{\r\n" + variables + "\r\npublic Object Eval()\r\n{\r\ndynamic Result;\r\n" + code + "\r\nreturn Result;\r\n}\r\n}\r\n}"; compiler = new CSharpCodeProvider(); break; case Languages.JScript: source = "package UserScript\r\n{\r\n" + "class RunScript" + count.ToString() + "\r\n{\r\n" + variables + "\r\npublic function Eval() : Object\r\n{\r\nvar Result;\r\n" + code + "\r\nreturn Result; \r\n}\r\n}\r\n}\r\n"; compiler = new JScriptCodeProvider(); break; case Languages.FSharp: throw new Exception("FSharp is not supportet"); /*source = "#light\r\nmodule UserScript\r\nopen System\r\n" + "type RunScript" + count.ToString() + "() =\r\n" + " let mutable Result = Double.NaN\r\n" + variables + "\r\n" + variables1 + " member this.Eval() =\r\n" + code + "\r\n Result\r\n"; compiler = new FSharpCodeProvider();*/ break; default: // VBasic source = "Imports System\r\nNamespace UserScript\r\nPublic Class RunScript" + count.ToString() + "\r\n" + variables + "Public Function Eval() As Object\r\nDim Result As Object\r\n" + code + "\r\nReturn Result\r\nEnd Function\r\nEnd Class\r\nEnd Namespace\r\n"; compiler = new VBCodeProvider(); break; } results = compiler.CompileAssemblyFromSource(this.Parameters, source); // Check for compile errors / warnings if (results.Errors.HasErrors || results.Errors.HasWarnings) { Messages = new string[results.Errors.Count]; for (int i = 0; i < results.Errors.Count; i++) Messages[i] = results.Errors[i].ToString(); return false; } else { Messages = null; assembly = results.CompiledAssembly; Type[] tt = assembly.GetTypes(); if (Language == Languages.FSharp) evaluatorType = assembly.GetType("UserScript+RunScript" + count.ToString()); else evaluatorType = assembly.GetType("UserScript.RunScript" + count.ToString()); evaluator = Activator.CreateInstance(evaluatorType); count++; return true; } }
/// <summary> /// Compiles the assembly from source. /// </summary> /// <param name="source">The source.</param> /// <param name="outputAssemblyName">Name of the output assembly.</param> /// <param name="provider">The provider.</param> /// <param name="referencedAssemblies">The referenced assemblies.</param> /// <returns></returns> public static CompilerResults CompileAssemblyFromSource( string[] sources, string outputAssemblyName, CodeDomProvider provider, string[] referencedAssemblies) { CompilerParameters parameters = new CompilerParameters(); parameters.GenerateExecutable = false; parameters.GenerateInMemory = string.IsNullOrEmpty(outputAssemblyName); parameters.IncludeDebugInformation = false; parameters.TreatWarningsAsErrors = true; parameters.CompilerOptions = "/optimize"; parameters.OutputAssembly = outputAssemblyName; if (referencedAssemblies != null && referencedAssemblies.Length > 0) { parameters.ReferencedAssemblies.AddRange(referencedAssemblies); } // Add referenced asms foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { try { string location = assembly.Location; if (!String.IsNullOrWhiteSpace(location) && !parameters.ReferencedAssemblies.Contains(Path.GetFileName(location))) { parameters.ReferencedAssemblies.Add(location); } } catch (NotSupportedException) { // this happens for dynamic assemblies, so just ignore it. } } CompilerResults results = provider.CompileAssemblyFromSource(parameters, sources); Assert.IsFalse(results.Errors.HasErrors, "Errors in CompileAssemblyFromSource: " + (results.Errors.HasErrors ? results.Errors[0].ErrorText : "")); return results; }
private void CompilePlugin(FileInfo pluginFile, string pluginClassName, CodeDomProvider pluginsCodeDomProvider, CompilerParameters parameters) { // 1. Grab the full source of this plugin String fullPluginSource = this.BuildPluginSource(pluginFile); // 2. Compute the hash of this plugin source. String pluginSourceHash = MD5.String(fullPluginSource); // 2. See if we require this plugin to be recompiled. bool requiresRecompiling = this.PluginCache.IsModified(pluginClassName, pluginSourceHash); String outputAssembly = Path.Combine(PluginBaseDirectory, pluginClassName + ".dll"); if (requiresRecompiling == true || File.Exists(outputAssembly) == false) { // 3. If a compiled plugin exists already, remove it now. if (File.Exists(outputAssembly) == true) { try { File.Delete(outputAssembly); } catch { WritePluginConsole("Error removing file {0}... Skipping", outputAssembly); } } try { parameters.OutputAssembly = outputAssembly; // 4. Now compile the plugin this.PrintPluginResults(pluginFile, pluginsCodeDomProvider.CompileAssemblyFromSource(parameters, fullPluginSource)); // 5. Add/Update the storage cache for this plugin. this.PluginCache.Cache(new PluginCacheEntry() { ClassName = pluginClassName, Hash = pluginSourceHash, SourcePath = pluginFile.FullName, DestinationPath = outputAssembly }); } catch (Exception e) { WritePluginConsole("Error compiling {0}: {1}", pluginClassName, e.Message); } } else { WritePluginConsole("Compiling {0}... ^2Using Cache", pluginFile.Name); } }
/// <summary> /// Creates the dynamic assembly. /// </summary> /// <param name="provider">The provider.</param> /// <param name="referencedAssemblies">The referenced assemblies.</param> /// <param name="namespace">The namespace.</param> /// <param name="usingNameSpaces">The using nameSpaces.</param> /// <param name="classCodesToCompile">The class codes to compile.</param> /// <returns>Assembly.</returns> /// <exception cref="OperationFailureException">CompileAssemblyFromSource;null</exception> public SandboxAssembly CreateDynamicAssembly(CodeDomProvider provider, List<string> referencedAssemblies, string @namespace, IEnumerable<string> usingNameSpaces, string classCodesToCompile) { try { provider.CheckNullObject("provider"); classCodesToCompile.CheckEmptyString("classCodesToCompile"); @namespace = @namespace.SafeToString("Beyova.DynamicCompile.Sandbox"); var objCompilerParameters = new CompilerParameters { GenerateExecutable = false, GenerateInMemory = true }; // Prepare references. var references = GetCommonAssemblyNameList(); if (referencedAssemblies.HasItem()) { references.AddRange(referencedAssemblies); } objCompilerParameters.ReferencedAssemblies.AddRange(references.ToArray()); // Prepare references done. // Prepare namespace var nameSpaces = GetCommonNamespaces(); if (usingNameSpaces.HasItem()) { nameSpaces.AddRange(usingNameSpaces); } // Prepare namespace done; StringBuilder builder = new StringBuilder(512); foreach (var one in nameSpaces) { builder.AppendLineWithFormat("using {0};", one); } builder.AppendLineWithFormat("namespace {0}", @namespace); //Namespace start builder.AppendLine("{"); builder.AppendLine(classCodesToCompile); //End of namespace builder.Append("}"); var compilerResult = provider.CompileAssemblyFromSource(objCompilerParameters, classCodesToCompile); if (compilerResult.Errors.HasErrors) { List<dynamic> errors = new List<dynamic>(); foreach (CompilerError one in compilerResult.Errors) { errors.Add(new { one.ErrorText, one.ErrorNumber, one.Line }); } throw new OperationFailureException("CompileAssemblyFromSource", null, errors); } return new SandboxAssembly(compilerResult.CompiledAssembly, @namespace); } catch (Exception ex) { throw ex.Handle("CreateDynamicAssembly"); } }
///<remarks>Brendan Ingram has greatly improved this method.</remarks> private static object LoadClass(CodeDomProvider codeProvider, string targetClassName, string source, bool sourceIsString) { CompilerParameters compilerParameters = new CompilerParameters(); compilerParameters.GenerateExecutable = false; compilerParameters.GenerateInMemory = Compilation.GenerateInMemoryAssembly; compilerParameters.IncludeDebugInformation = true; compilerParameters.TreatWarningsAsErrors = false; compilerParameters.CompilerOptions = compilerOptions; // Chuck Cross has vastly improved the loading of NxBRE DLL reference mechanism bool nxbreAssemblyLoaded = false; // Add all implicitly referenced assemblies if ((ReferenceLinkMode == ReferenceLinkModes.CurrentDomain) || (ReferenceLinkMode == ReferenceLinkModes.Full)) { foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { // do not add AssemblyBuilders (bug 1482753), thanks to Bob Brumfield // handle .NET4 dynamic assemblies correctly, thanks to Nich if (!(assembly is AssemblyBuilder) && (assembly.ManifestModule.GetType().Namespace != "System.Reflection.Emit")) { AddReferencedAssembly(compilerParameters, assembly.Location); if(assembly.ManifestModule.ScopeName.Equals(NXBRE_DLL)) nxbreAssemblyLoaded = true; } } } // Add NxBRE DLL reference only if not already added through implicit references. if (!nxbreAssemblyLoaded && ((ReferenceLinkMode == ReferenceLinkModes.NxBRE) || (ReferenceLinkMode == ReferenceLinkModes.Full))) { AddReferencedAssembly(compilerParameters, NxBREAssemblyLocation); } // Add any extra DLL listed in the application configuration String extraReferences = Parameter.GetString("extraReferences"); if (extraReferences != null) { foreach(String dllToReference in extraReferences.Split(';')) { AddReferencedAssembly(compilerParameters, dllToReference); } } CompilerResults cr; if (sourceIsString) { cr = codeProvider.CompileAssemblyFromSource(compilerParameters, source); } else { cr = codeProvider.CompileAssemblyFromFile(compilerParameters, source); } if (cr.Errors.Count != 0) { throw new BREException(GetCompilerErrors(cr)); } // Marcin Kielar - zorba128 // Under some (strange?) conditions, compilation finishes without errors, // but assembly cannot be loaded: // - any of Assembly's methods (here - GetTypes) throws exception // - CreateInstance returns null try { cr.CompiledAssembly.GetTypes(); } catch(Exception e) { throw new BREException("Unable to create evaluator class instance - assembly loading problem", e); } object evaluatorInstance = cr.CompiledAssembly.CreateInstance(targetClassName); if(evaluatorInstance == null) { throw new BREException("Unable to create evaluator class instance"); } return evaluatorInstance; }
public CompilerResults ToCompilerResults(CodeCompileUnit compileunit, CodeDomProvider provider, IDomainMap domainMap) { #if NET2 CompilerParameters cp = new CompilerParameters(); cp.ReferencedAssemblies.Add("System.dll"); cp.GenerateInMemory = true; string code = ToCode(compileunit, provider, domainMap); return provider.CompileAssemblyFromSource(cp, code); #else ICodeCompiler compiler = provider.CreateCompiler(); CompilerParameters cp = new CompilerParameters(); cp.ReferencedAssemblies.Add( "System.dll" ); cp.GenerateInMemory = true; string code = ToCode(compileunit, provider, domainMap); return compiler.CompileAssemblyFromSource(cp, code); #endif }