private void CompileScripts(string[] scripts) { CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters parameter = new CompilerParameters(); parameter.ReferencedAssemblies.Add("UniTTT.Logik.dll"); parameter.CompilerOptions = "/t:library"; parameter.GenerateInMemory = true; Type[] types = new Type[scripts.Length]; for (int i = 0; i < scripts.Length; i++) { if (File.Exists(scripts[i])) { CompilerResults result = provider.CompileAssemblyFromFile(parameter, scripts[i]); if (result.CompiledAssembly.GetTypes().Count(t => t.IsSubclassOf(typeof(KI.AbstractKI))) == 1) { types[i] = result.CompiledAssembly.GetTypes()[0]; } } } Array.Resize(ref KITypes, KITypes.Length + types.Length); Array.Copy(types, KITypes, types.Length); }
public Assembly Compile(FileInfo outputFile, IEnumerable <FileInfo> sourceFiles) { var sourceFilePaths = sourceFiles.Select(file => file.FullName).ToArray(); var compilerParameters = new CompilerParameters(referencedAssemblies.ToArray()) { #if DEBUG IncludeDebugInformation = true, #else IncludeDebugInformation = false, #endif GenerateExecutable = false, GenerateInMemory = false, WarningLevel = 2, CompilerOptions = string.Format($"/optimize /lib:{Path.Combine(".", "lib")}") }; compilerParameters.ReferencedAssemblies.Remove(outputFile.Name); compilerParameters.OutputAssembly = outputFile.FullName; var compilerResults = compiler.CompileAssemblyFromFile(compilerParameters, sourceFilePaths); lastCompilationErrors = compilerResults.Errors; GC.Collect(); if (HasErrors) { PrintErrorMessagesToConsole(); throw new ApplicationException("Scripts compilation was unsuccessful. Abort startup!"); } return(compilerResults.CompiledAssembly); }
public static CompilerResults CompileCodeFile(CodeDomProvider compiler, CompilerParameters parms, string filename) { //actually compile the code CompilerResults results = compiler.CompileAssemblyFromFile(parms, new string[] { filename }); //Do we have any compiler errors? if (results.Errors.Count > 0) { bool iserror = false; foreach (CompilerError error in results.Errors) { Console.WriteLine("Compile " + (error.IsWarning ? "Warning" : "Error") + ": Line: " + error.Line + ":" + error.Column + " " + error.ErrorText); if (!error.IsWarning) { iserror = true; } } if (iserror) { return(null); } } return(results); }
public static void CompileFromFile(string assemblyFName, Assembly[] references, params string[] sourceFiles) { using (CodeDomProvider provider = GetCSharpCodeDomProvider()) { CompilerParameters parameters = CreateDefaultCompilerParameters(); // TODO: run test cases in both modes (optimized and debug) parameters.IncludeDebugInformation = Debug.Value; parameters.OutputAssembly = assemblyFName; if (Unsafe.Value) { parameters.CompilerOptions = "/unsafe"; } if (KeyFile.Value != null) { parameters.CompilerOptions += " /keyfile:" + KeyFile.Value.KeyFile; parameters.CompilerOptions += " /delaysign" + (KeyFile.Value.DelaySign ? '+' : '-'); } parameters.CompilerOptions += " " + ExtraParameters.Value; foreach (Assembly reference in references) { parameters.ReferencedAssemblies.Add(reference.ManifestModule.FullyQualifiedName); } CompilerResults results = provider.CompileAssemblyFromFile(parameters, sourceFiles); if (ContainsErrors(results.Errors)) { throw new ApplicationException(GetErrorString(results.Errors)); } } }
public static Assembly CompileScript(string path, CodeDomProvider provider) { CompilerParameters compilerParameters = new CompilerParameters { GenerateExecutable = false, GenerateInMemory = true, IncludeDebugInformation = false }; compilerParameters.ReferencedAssemblies.Add("System.dll"); compilerParameters.ReferencedAssemblies.Add("System.Core.dll"); compilerParameters.ReferencedAssemblies.Add("System.Data.Linq.dll"); compilerParameters.ReferencedAssemblies.Add(System.Reflection.Assembly.GetExecutingAssembly().Location); CompilerResults results = provider.CompileAssemblyFromFile(compilerParameters, path); if (!results.Errors.HasErrors) { return(results.CompiledAssembly); } else { foreach (CompilerError error in results.Errors) { errorLog.AppendLine(error.ToString()); } } return(null); }
private Assembly CompileExecutable(FileInfo sourceFile) { CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters cp = new CompilerParameters(); cp.GenerateInMemory = true; cp.TreatWarningsAsErrors = false; cp.ReferencedAssemblies.Add("System.Core.dll"); var cr = provider.CompileAssemblyFromFile(cp, sourceFile.FullName); if (cr.Errors.Count > 0) { // Display compilation errors. Log.Write($"Errors building {sourceFile.FullName} into {cr.PathToAssembly}", Log.ERROR); foreach (CompilerError ce in cr.Errors) { Log.Write($" {ce}", Log.ERROR); } return(null); } return(cr.CompiledAssembly); }
Assembly CompileFromSource(CodeDomProvider provider, string searchPattern) { var sourceFiles = Directory.GetFiles(FileSystem.DataDirectory, searchPattern, SearchOption.AllDirectories); if (sourceFiles.Length == 0) { return(null); } using (provider) { var compilerParameters = new CompilerParameters(); compilerParameters.GenerateExecutable = false; // Necessary for stack trace line numbers etc compilerParameters.IncludeDebugInformation = true; compilerParameters.GenerateInMemory = false; #if RELEASE if (!compilationParameters.ForceDebugInformation) { compilerParameters.GenerateInMemory = true; compilerParameters.IncludeDebugInformation = false; } #endif if (!compilerParameters.GenerateInMemory) { compilerParameters.OutputAssembly = Path.GetTempFileName() + ".dll"; } AddReferencedAssembliesForSourceFiles(sourceFiles, ref compilerParameters); var results = provider.CompileAssemblyFromFile(compilerParameters, sourceFiles); if (results.Errors.HasErrors && results.CompiledAssembly != null) { return(results.CompiledAssembly); } string compilationError = string.Format("Compilation failed; {0} errors: ", results.Errors.Count); foreach (CompilerError error in results.Errors) { compilationError += Environment.NewLine; if (!error.ErrorText.Contains("(Location of the symbol related to previous error)")) { compilationError += string.Format("{0}({1},{2}): {3} {4}: {5}", error.FileName, error.Line, error.Column, error.IsWarning ? "warning" : "error", error.ErrorNumber, error.ErrorText); } else { compilationError += " " + error.ErrorText; } } throw new CompilationFailedException(compilationError); } }
/// <summary> /// Compiles a file to an assembly using specified compiler. /// </summary> Assembly Compile(PluginInfo pi, CodeDomProvider cdp) { // Compile //ICodeCompiler compiler = cdp.CreateCompiler(); if (cdp is Microsoft.JScript.JScriptCodeProvider) { // JSCript doesn't support unsafe code cp.CompilerOptions = ""; } else { cp.CompilerOptions = "/unsafe"; } // Add references cp.ReferencedAssemblies.Clear(); foreach (string reference in m_worldWindReferencesList) { cp.ReferencedAssemblies.Add(reference); } // Add reference to core functions for VB.Net users if (cdp is Microsoft.VisualBasic.VBCodeProvider) { cp.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll"); } // Add references specified in the plugin foreach (string reference in pi.References.Split(',')) { AddCompilerReference(pi.FullPath, reference.Trim()); } CompilerResults cr = cdp.CompileAssemblyFromFile(cp, pi.FullPath); if (cr.Errors.HasErrors || cr.Errors.HasWarnings) { // Handle compiler errors StringBuilder error = new StringBuilder(); foreach (CompilerError err in cr.Errors) { string type = (err.IsWarning ? "Warning" : "Error"); if (error.Length > 0) { error.Append(Environment.NewLine); } error.AppendFormat("{0} {1}: Line {2} Column {3}: {4}", type, err.ErrorNumber, err.Line, err.Column, err.ErrorText); } Log.Write(Log.Levels.Error, LogCategory, error.ToString()); if (cr.Errors.HasErrors) { throw new Exception(error.ToString()); } } // Success, return our new assembly return(cr.CompiledAssembly); }
public static bool CompileStage0(string host, int port) { string sourcePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string sourceFile = Path.Combine(sourcePath, @"Templates\Stage0Template.cs"); if (!File.Exists(sourceFile)) { Console.WriteLine("[-] Can't find the Stage0 template file. Is the \"Tempates\" " + "directory in the same directory as SHAPESHIFTER.exe?"); return(false); } // Replace placeholders with information for the callback string template = File.ReadAllText(sourceFile); string modified = template.Replace(@"[SHAPESHIFTER_HOST]", host); modified = modified.Replace(@"[SHAPESHIFTER_PORT]", port.ToString()); File.WriteAllText(sourcePath + @"\BuiltStages\Stage0.cs", modified); CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters cParams = new CompilerParameters { GenerateExecutable = true, OutputAssembly = Path.Combine(sourcePath, "stage0.exe"), IncludeDebugInformation = false, GenerateInMemory = false, WarningLevel = 0, // No warnings means no bugs, right? TreatWarningsAsErrors = false, CompilerOptions = "/unsafe", TempFiles = new TempFileCollection(".", false), MainClass = "Stage0.Program" }; cParams.ReferencedAssemblies.Add("System.dll"); cParams.ReferencedAssemblies.Add("System.Core.dll"); cParams.ReferencedAssemblies.Add("System.Data.dll"); cParams.ReferencedAssemblies.Add("System.Data.DatasetExtensions.dll"); cParams.ReferencedAssemblies.Add("System.Net.dll"); cParams.ReferencedAssemblies.Add("System.Xml.dll"); cParams.ReferencedAssemblies.Add("System.Xml.Linq.dll"); CompilerResults results = provider.CompileAssemblyFromFile(cParams, sourcePath + @"\BuiltStages\Stage0.cs"); if (results.Errors.Count == 0) { Console.WriteLine("[+] Stage0 compiled into {0}", results.PathToAssembly); } else { Console.WriteLine("[-] Error during Stage0 compilation"); foreach (CompilerError e in results.Errors) { Console.WriteLine(" {0}", e.ToString()); } return(false); } return(true); }
public void Compile() { var cp = new CompilerParameters(this.GetAllAssemblies().Select(i => i.FullName).ToArray(), this.Options.OutputDllFile, true); cp.GenerateExecutable = false; var cr = provider.CompileAssemblyFromFile(cp, this.Options.OutputFile); }
public static bool CompileExecutable(String sourceName) { FileInfo sourceFile = new FileInfo(sourceName); CodeDomProvider provider = null; bool compileOk = false; // Select the code provider based on the input file extension. provider = CodeDomProvider.CreateProvider("CSharp"); if (provider != null) { // Format the executable file name. // Build the output assembly path using the current directory // and _cs.exe or _vb.exe. String exeName = String.Format(@"{0}\{1}.exe", System.Environment.CurrentDirectory, sourceFile.Name.Replace(".", "_")); CompilerParameters cp = new CompilerParameters(); // Generate an executable instead of // a class library. cp.GenerateExecutable = true; // Specify the assembly file name to generate. cp.OutputAssembly = exeName; // Save the assembly as a physical file. cp.GenerateInMemory = true; // Set whether to treat all warnings as errors. cp.TreatWarningsAsErrors = false; // Invoke compilation of the source file. CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceName); if (cr.Errors.Count < 0) { // Display compilation errors. Console.WriteLine("Errors building {0} into {1}", sourceName, cr.PathToAssembly); foreach (CompilerError ce in cr.Errors) { Console.WriteLine(" {0}", ce.ToString()); Console.WriteLine(); } } else { // Display a successful compilation message. Console.WriteLine("Source {0} built into {1} successfully.", sourceName, cr.PathToAssembly); } // Return the results of the compilation. if (cr.Errors.Count < 0) { compileOk = false; } else { compileOk = true; } } return(compileOk); }
private CompilerResults Compile(CodeDomProvider provider, CompilerParameters cp) { if (sourceFiles != null) { return(provider.CompileAssemblyFromFile(cp, sourceFiles.ToArray())); } return(provider.CompileAssemblyFromDom(cp, compileUnits.ToArray())); }
static void Main(string[] args) { CodeDomProvider provider = CodeDomProvider.CreateProvider(providerName); // Create a code snippet to be used in the graph. GenCodeFromMember(provider, new CodeGeneratorOptions()); LogMessage("Building CodeDOM graph..."); CodeCompileUnit cu = new CodeCompileUnit(); cu = BuildClass1(); StringWriter sw = new StringWriter(); LogMessage("Generating code..."); provider.GenerateCodeFromCompileUnit(cu, sw, null); string output = sw.ToString(); LogMessage("Dumping source..."); LogMessage(output); LogMessage("Writing source to file..."); Stream s = File.Open(sourceFileName, FileMode.Create); StreamWriter t = new StreamWriter(s); t.Write(output); t.Close(); s.Close(); CompilerParameters opt = new CompilerParameters(new string[] { "System.dll" }); opt.GenerateExecutable = false; opt.OutputAssembly = "Sample.dll"; CompilerResults results; LogMessage("Compiling with " + providerName); results = provider.CompileAssemblyFromFile(opt, sourceFileName); OutputResults(results); if (results.NativeCompilerReturnValue != 0) { LogMessage(""); LogMessage("Compilation failed."); } else { LogMessage(""); LogMessage("Demo completed successfully."); } File.Delete(sourceFileName); }
public ClientPlugin CompileCode(String sourceFile) { CompilerParameters cp = new CompilerParameters(); cp.CompilerOptions = "-unsafe"; //cp.CompilerOptions.Insert(cp.CompilerOptions.Length, "-unsafe"); //CompilerParameters.Unsafe cp.GenerateInMemory = true; cp.TreatWarningsAsErrors = false; cp.GenerateExecutable = false; //cp.CompilerOptions = "/optimize"; cp.IncludeDebugInformation = true; cp.ReferencedAssemblies.Add("System.dll"); cp.ReferencedAssemblies.Add("Mogre.dll"); cp.ReferencedAssemblies.Add("ExtraMegaBlob.References.dll"); cp.ReferencedAssemblies.Add("MogreFramework.dll"); cp.ReferencedAssemblies.Add("System.Windows.Forms.dll"); cp.ReferencedAssemblies.Add("System.Drawing.dll"); //cp.ReferencedAssemblies.Add("MOIS_d.dll"); cp.ReferencedAssemblies.Add("MOIS.dll"); cp.ReferencedAssemblies.Add("eyecm.PhysX.dll"); //cp.OutputAssembly = Path.GetDirectoryName(sourceFile) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(sourceFile) + ".dll"; string srcFilExt = System.IO.Path.GetExtension(sourceFile); string srcFilNam_minuspath = System.IO.Path.GetFileName(sourceFile); CodeDomProvider provider = this.GetCurrentProvider(srcFilExt); DateTime dt_before = DateTime.Now; CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceFile); DateTime dt_after = DateTime.Now; TimeSpan ts_compiletime = new TimeSpan(dt_after.Ticks - dt_before.Ticks); log("compiled in: " + ts_compiletime.ToString() + ", File: " + srcFilNam_minuspath); foreach (CompilerError ce in cr.Errors) { string prefix = " [" + srcFilNam_minuspath + "] " + ((ce.IsWarning) ? "[Warning]" : "[Error]"); log(prefix + " Line: " + ce.Line + ", Number: " + ce.ErrorNumber + ", Text: " + ce.ErrorText); } if (cr.Errors.HasErrors) { return(null); } Assembly ClientClass = cr.CompiledAssembly; Type ClientClassType = ClientClass.GetType("ExtraMegaBlob.plugin"); if (!object.Equals(null, ClientClassType)) { BindingFlags bflags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; ClientPlugin o = (ClientPlugin)ClientClassType.InvokeMember("ExtraMegaBlob.plugin", bflags | BindingFlags.CreateInstance, null, null, null); return(o); } else { log("Compiled Plugin failed to initialize properly, source: \"" + sourceFile + "\""); return(null); } }
/// <summary> /// Method compiles all class files from "./classes/" folder generated by this process /// </summary> public void CompileCode(string fileName) { if (string.IsNullOrEmpty(fileName)) { OnMessage("\r\nWARNING: missing file name."); return; } if (Files.Count == 0) { OnMessage("\r\nWARNING: No classes generated! Nothing to compile."); return; } OnMessage("\r\n\t-------------Compiling code-------------"); List <string> paths = new List <string>(); foreach (CodeCompileUnit unit in Files) { if (unit != null) { String sourceFile = ".\\classes\\" + unit.Namespaces[0].Types[0].Name + ".cs"; paths.Add(sourceFile); } } CompilerParameters parameters = new CompilerParameters(); parameters.GenerateExecutable = false; parameters.GenerateInMemory = true; //parameters.OutputAssembly = ".\\DLL\\" + fileName + ".dll"; parameters.OutputAssembly = ".\\" + fileName + ".dll"; parameters.ReferencedAssemblies.Add("System.dll"); parameters.TreatWarningsAsErrors = false; if (!System.IO.Directory.Exists(".\\DLL\\")) { System.IO.Directory.CreateDirectory(".\\DLL\\"); } CompilerResults cr = provider.CompileAssemblyFromFile(parameters, paths.ToArray()); if (cr.Errors.Count > 0) { OnMessage("\r\n Errors encountered while building \r\n\r\n"); foreach (CompilerError ce in cr.Errors) { OnMessage(ce.ToString() + "\r\n"); } OnMessage("\r\nTotal errors: " + cr.Errors.Count); } else { OnMessage("\r\nSource built into with no errors."); } OnMessage("\r\n\t----------Done compiling code----------"); }
static void Main(string[] args) { Console.WriteLine("List IKSkeletonHuman Bones"); CSharpCodeProvider thisCSharpCodeProvider = new CSharpCodeProvider(); CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters cp = new CompilerParameters(); cp.GenerateExecutable = false; cp.GenerateInMemory = true; cp.TreatWarningsAsErrors = false; cp.ReferencedAssemblies.Add(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.2\PresentationCore.dll"); cp.ReferencedAssemblies.Add(@"C:\Users\alexis\Documents\Visual Studio 2015\Projects\EmitSkeleton\ClassLibrary2\bin\Debug\ClassLibrary2.dll"); CompilerResults cr = provider.CompileAssemblyFromFile(cp, new string[] { @"c:\users\alexis\documents\visual studio 2015\Projects\EmitSkeleton\IKSkeletons\IKSkeletonHuman1.cs", @"c:\users\alexis\documents\visual studio 2015\Projects\EmitSkeleton\IKBone.cs" } ); if (cr.Errors.Count > 0) { // Display compilation errors. foreach (CompilerError ce in cr.Errors) { Console.WriteLine(" {0}", ce.ToString()); Console.WriteLine(); } } else { // Display a successful compilation message. Console.WriteLine("Success"); } Type myType = cr.CompiledAssembly.GetType("EmitSkeleton.IKSkeletons.IKSkeletonHuman1"); Console.WriteLine(myType.Name); Console.WriteLine(myType.Namespace); foreach (PropertyInfo f in myType.GetProperties()) { Console.WriteLine(f.Name); } Console.ReadLine(); IKSkeleton thisIKSkeleton = (IKSkeleton)Activator.CreateInstance(myType); Console.WriteLine(thisIKSkeleton.ListBones()); Console.ReadLine(); }
/// <summary> /// Builds this project. /// </summary> /// <returns>Reference to assembly wrapper object.</returns> public override Assembly Build() { CompilerParameters compilationParameters = new CompilerParameters { #if DEBUG GenerateExecutable = false, IncludeDebugInformation = true, GenerateInMemory = false #endif #if RELEASE GenerateExecutable = false, IncludeDebugInformation = false, GenerateInMemory = false, CompilerOptions = "/optimize" #endif }; // Delete previous assembly. string assemblyFile = Path.Combine(this.BinaryPath, this.AssemblyName, ".dll"); if (File.Exists(assemblyFile)) { try { File.Delete(assemblyFile); } catch (Exception ex) { if (ex is UnauthorizedAccessException || ex is IOException) { throw new CodeCompilationException ( String.Format ( "Unable to compile the code: Assembly file {0} cannot be overwritten.", assemblyFile ) ); } throw; } } compilationParameters.OutputAssembly = assemblyFile; // Get list of referenced assemblies from the project file. compilationParameters.ReferencedAssemblies.AddRange(this.ReferencedAssemblies); // Find all code files. string[] codeFiles = this.GetCodeFiles; CompilerResults results; using (CodeDomProvider provider = this.Provider) { results = provider.CompileAssemblyFromFile(compilationParameters, codeFiles); } this.compiledAssembly = ValidateCompilation(results); return(this.compiledAssembly); }
// static public void BuildDLL_DotNet(string dataPath, string streamingAssetsPath, // string u3dDllPath1, string u3dDllPath2) // { // //编译项目的base.dll // Console.WriteLine("准备编译dll 10%"); // // //准备工作 // var path = streamingAssetsPath + "/hotfix"; // if (Directory.Exists(path)) // { // Directory.Delete(path, true); // } // // Directory.CreateDirectory(path); // // // string[] searchPath = new string[] {"3rdPlugins", "Code", "Plugins", "Resource"}; // // for (int i = 0; i < searchPath.Length; i++) // { // searchPath[i] = Path.Combine(dataPath, searchPath[i]); // } // // List<string> files = new List<string>(); // foreach (var s in searchPath) // { // var fs = Directory.GetFiles(s, "*.*", SearchOption.AllDirectories).ToList(); // var _fs = fs.FindAll(f => // { // var _f = f.ToLower(); // var exten = Path.GetExtension(_f); // if ((!_f.Contains("editor")) && // (exten.Equals(".dll") || exten.Equals(".cs"))) // { // return true; // } // // return false; // }); // // files.AddRange(_fs); // } // // files = files.Distinct().ToList(); // for (int i = 0; i < files.Count; i++) // { // files[i] = files[i].Replace('/', '\\').Trim('\\'); // } // // Console.WriteLine("开始整理script 20%"); // // var refDlls = files.FindAll(f => f.EndsWith(".dll")); // var baseCs = files.FindAll(f => !f.EndsWith(".dll") && !f.Contains("@hotfix")); // var hotfixCs = files.FindAll(f => !f.EndsWith(".dll") && f.Contains("@hotfix")); // // // var tempDirect = "c:/bd_temp"; // if (Directory.Exists(tempDirect)) // { // Directory.Delete(tempDirect, true); // } // // Directory.CreateDirectory(tempDirect); // // //除去不需要引用的dll // for (int i = refDlls.Count - 1; i >= 0; i--) // { // var str = refDlls[i]; // if (str.Contains("iOS") || str.Contains("Android")) // { // refDlls.RemoveAt(i); // } // } // // //去除同名 重复的dll // for (int i = 0; i < refDlls.Count; i++) // { // var copyto = Path.Combine(tempDirect, Path.GetFileName(refDlls[i])); // File.Copy(refDlls[i], copyto, true); // refDlls[i] = copyto; // } // // refDlls.Add("System.dll"); // refDlls.Add("System.Core.dll"); // refDlls.Add("System.XML.dll"); // refDlls.Add("System.Data.dll"); // //dll1 // var u3ddlls1 = Directory.GetFiles(u3dDllPath1, "*.dll", SearchOption.TopDirectoryOnly); // foreach (var d in u3ddlls1) // { // refDlls.Add(d); // } // // //dll2 // var u3ddlls2 = Directory.GetFiles(u3dDllPath2, "*.dll", SearchOption.AllDirectories); // foreach (var d in u3ddlls2) // { // refDlls.Add(d); // } // // // // var baseDllPath = streamingAssetsPath + "/hotfix/base.dll"; // // // Console.WriteLine("复制编译代码 30%"); // // //为解决mono.exe error: 文件名太长问题 // tempDirect = "c:/bd_temp"; // for (int i = 0; i < baseCs.Count; i++) // { // var copyto = Path.Combine(tempDirect, Path.GetFileName(baseCs[i])); // int count = 1; // while (File.Exists(copyto)) // { // copyto = copyto.Replace(".cs", "") + count + ".cs"; // count++; // } // // File.Copy(baseCs[i], copyto); // baseCs[i] = copyto; // } // // //建立目标目录 // var outDirectory = Path.GetDirectoryName(baseDllPath); // if (Directory.Exists(outDirectory)) // { // Directory.Delete(outDirectory, true); // } // // // Directory.CreateDirectory(outDirectory); // Console.WriteLine("[1/2]开始编译base.dll 40%"); // //编译 base.dll // try // { // Build(refDlls.ToArray(), baseCs.ToArray(), baseDllPath); // } // catch (Exception e) // { // Console.WriteLine(e); // throw; // } // // Console.WriteLine("[2/2]开始编译hotfix.dll 70%"); // // var dependent = outDirectory + "/dependent"; // Directory.CreateDirectory(dependent); // // //将base.dll加入 // refDlls.Add(baseDllPath); // //编译hotfix.dll // var outHotfixDirectory = streamingAssetsPath + "/hotfix/hotfix.dll"; // try // { // Build(refDlls.ToArray(), hotfixCs.ToArray(), outHotfixDirectory); // } // catch (Exception e) // { // Console.WriteLine(e); // throw; // } // // Console.WriteLine("清理临时文件 95%"); // Directory.Delete(tempDirect, true); // Console.WriteLine("编译成功!位于StreamingAssets下! 100%"); // //拷贝依赖的dll // // foreach (var f in refDlls) // // { // // if (File.Exists(f) == false) // // { // // continue; // // } // // var fn = Path.GetFileName(f); // // var outpath = Path.Combine(dependent, fn); // // File.Copy(f, outpath, true); // // } // } /// <summary> /// 编译dll /// </summary> /// <param name="rootpaths"></param> /// <param name="output"></param> static public BuildStatus Build(string[] refAssemblies, string[] codefiles, string output) { // 设定编译参数,DLL代表需要引入的Assemblies CompilerParameters cp = new CompilerParameters(); // cp.GenerateExecutable = false; //在内存中生成 cp.GenerateInMemory = true; //生成调试信息 cp.IncludeDebugInformation = true; cp.TempFiles = new TempFileCollection(".", true); cp.OutputAssembly = output; //warning和 error分开,不然各种warning当成error,改死你 cp.TreatWarningsAsErrors = false; cp.WarningLevel = 1; //编译选项 cp.CompilerOptions = "/optimize /unsafe"; if (refAssemblies != null) { foreach (var d in refAssemblies) { cp.ReferencedAssemblies.Add(d); } } // 编译代理 CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerResults cr = provider.CompileAssemblyFromFile(cp, codefiles); if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } #if !UNITY_EDITOR Console.WriteLine(sb); #else Debug.LogError(sb); #endif } else { return(BuildStatus.Success); } return(BuildStatus.Fail); }
static public void fun2() { // 文件路径 string srccodePath = @"demo.cs"; CodeDomProvider provider = CodeDomProvider.CreateProvider("cs"); // 编译参数 CompilerParameters p = new CompilerParameters(); // 输出文件 p.OutputAssembly = "DemoLib2.dll"; // 添加引用的程序集 // 其实我们这里用不上,只是作为演示 // mscorLib.dll是不用添加的,它是默认库 p.ReferencedAssemblies.Add("System.dll"); // 编译 CompilerResults res = provider.CompileAssemblyFromFile(p, srccodePath); // 检查编译结果 if (res.Errors.Count == 0) { // 没有出错 Console.WriteLine("编译成功。"); // 获取刚刚编译的程序集信息 Assembly outputAss = res.CompiledAssembly; // 全名 Console.WriteLine($"程序集全名:{outputAss.FullName}"); // 位置 Console.WriteLine($"程序集位置:{outputAss.Location}"); // 程序集中的类型 Type[] types = outputAss.GetTypes(); Console.WriteLine("----------------------\n类型列表:"); foreach (Type t in types) { Console.WriteLine(t.FullName); } Assembly assembly = res.CompiledAssembly; Type type = assembly.GetType("ConsoleApp2.a"); var v = type.GetMethod("fun"); Object obj = Activator.CreateInstance(type); v.Invoke(obj, null); } else { // 如果编译出错 Console.WriteLine("发生错误,详见以下内容:"); foreach (CompilerError er in res.Errors) { Console.WriteLine($"行{er.Line},列{er.Column},错误号{er.ErrorNumber},错误信息:{er.ErrorText}"); } } }
/// <summary> /// Creates new assembly, compiling the given files. /// </summary> /// <param name="scriptFilesList"></param> /// <returns></returns> private Assembly Compile(IEnumerable <string> scriptFilesList) { var filePaths = scriptFilesList.Select(a => a.Replace('\\', '/').Replace('/', Path.DirectorySeparatorChar)).ToArray(); // Prepare parameters var parameters = new CompilerParameters(); parameters.GenerateExecutable = false; parameters.GenerateInMemory = true; parameters.WarningLevel = 0; // Add default references foreach (var reference in _defaultReferences) { parameters.ReferencedAssemblies.Add(reference); } // Get assemblies referenced by application var entryAssembly = Assembly.GetEntryAssembly(); var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies(); var toReference = new HashSet <string>(); if (entryAssembly != null) { foreach (var assemblyName in entryAssembly.GetReferencedAssemblies()) { var assembly = Assembly.Load(assemblyName); toReference.Add(assembly.Location); } } foreach (var assembly in loadedAssemblies) { toReference.Add(assembly.Location); } foreach (var location in toReference) { parameters.ReferencedAssemblies.Add(location); } // Compile, throw if compilation failed var result = _compiler.CompileAssemblyFromFile(parameters, filePaths); var errors = result.Errors; if (errors.Count != 0) { throw new CompilerErrorException(errors); } return(result.CompiledAssembly); }
/// <summary> /// Compiles a parsed template in the form of a CodeBuilder object and returns the compiler results. /// </summary> /// <param name="code">A parsed template in the form of a CodeBuilder object</param> /// <returns>The results of compilation.</returns> internal static CompilerResults Compile(CodeBuilder code) { CompilerResults results = null; CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("C#"); CompilerParameters compilerParams = new CompilerParameters(); compilerParams.CompilerOptions = "/target:library /optimize"; string assembly = ""; foreach (string reference in code.References) { assembly = CompilerAssemblyPath + reference + ".dll"; if (File.Exists(assembly)) { compilerParams.ReferencedAssemblies.Add(assembly); } else { compilerParams.ReferencedAssemblies.Add(reference + ".dll"); } } if (code.CompileInMemory) { compilerParams.GenerateExecutable = false; compilerParams.IncludeDebugInformation = false; compilerParams.GenerateInMemory = true; results = codeProvider.CompileAssemblyFromSource(compilerParams, code.ToString()); } else { string baseName = "esCompiledTemplate_" + Guid.NewGuid().ToString().Replace("-", ""); string codeFileName = TemplateCachePath + baseName + ".cs"; string assemblyName = TemplateCachePath + baseName + ".dll"; File.WriteAllText(codeFileName, code.ToString()); string[] files = new string[] { codeFileName }; compilerParams.GenerateExecutable = false; compilerParams.IncludeDebugInformation = true; compilerParams.GenerateInMemory = false; compilerParams.OutputAssembly = assemblyName; results = codeProvider.CompileAssemblyFromFile(compilerParams, files); } return(results); }
private static bool Compile(string[] sourceFiles, CompilerParameters options) { CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerResults results = provider.CompileAssemblyFromFile(options, sourceFiles); if (results.Errors.Count > 0) { return(false); } return(true); }
//将源文件编译成程序 public static CompilerResults CompileCode(CodeDomProvider provider, string sourceFile, string exeFile) { string[] referenceAssemblies = { "System.dll" }; CompilerParameters cp = new CompilerParameters(referenceAssemblies, exeFile, false); cp.GenerateExecutable = true;// 生成一个可执行文件,而不是一个 DLL 文件 // 调用编译器 CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceFile); // 返回编译结果 return(cr); }
public static CompilerResults CompileCode(CodeDomProvider provider, String sourceFile, String exeFile) { // Configure a CompilerParameters that links System.dll and produces the specified executable file. String[] referenceAssemblies = { "System.dll" }; CompilerParameters cp = new CompilerParameters(referenceAssemblies, exeFile, false); cp.GenerateExecutable = true; // Generate an executable rather than a DLL file. CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceFile); // Invoke compilation. return(cr); // Return the results of compilation. }
private bool CompileExecutable(string sourceName, string exeName) { FileInfo sourceFile = new FileInfo(sourceName); CodeDomProvider provider = CodeDomProvider.CreateProvider("VisualBasic"); bool compileOk = false; CompilerParameters cp = new CompilerParameters(); // Generate an executable instead of // a class library. cp.GenerateExecutable = true; // Specify the assembly file name to generate. cp.OutputAssembly = exeName; // Save the assembly as a physical file. cp.GenerateInMemory = false; // Set whether to treat all warnings as errors. cp.TreatWarningsAsErrors = false; // Invoke compilation of the source file. CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceName); if (cr.Errors.Count > 0) { // Display compilation errors. ErrorFormat("Errors building {0} into {1}", sourceName, cr.PathToAssembly); foreach (CompilerError ce in cr.Errors) { ErrorFormat(" {0}", ce.ToString()); } } else { // Display a successful compilation message. InfoFormat("Source {0} built into {1} successfully.", sourceName, cr.PathToAssembly); } // Return the results of the compilation. if (cr.Errors.Count > 0) { compileOk = false; } else { compileOk = true; } return(compileOk); }
public static byte[] CompileStage1(string clientId) { string sourcePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string sourceFile = sourcePath + @"\BuiltStages\" + clientId + ".cs"; if (!File.Exists(sourceFile)) { Console.WriteLine(" [-] Can't find the generated Stage1 source file. Make sure that {0} exists", sourceFile); return(null); } string outputFileName = Helpers.GenerateRandomFileName(); CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters cParams = new CompilerParameters { GenerateExecutable = true, OutputAssembly = sourcePath + @"\BuiltStages\" + outputFileName, IncludeDebugInformation = false, GenerateInMemory = false, WarningLevel = 0, // No warnings means no bugs, right? TreatWarningsAsErrors = false, CompilerOptions = " /unsafe", TempFiles = new TempFileCollection(".", false), MainClass = "Stage1.Program" }; cParams.ReferencedAssemblies.Add("System.dll"); cParams.ReferencedAssemblies.Add("System.Core.dll"); cParams.ReferencedAssemblies.Add("System.Data.dll"); cParams.ReferencedAssemblies.Add("System.Net.dll"); cParams.ReferencedAssemblies.Add("System.Xml.dll"); cParams.ReferencedAssemblies.Add("System.Xml.Linq.dll"); CompilerResults results = provider.CompileAssemblyFromFile(cParams, sourceFile); if (results.Errors.Count == 0) { Console.WriteLine(" [>] Stage1 compiled into {0}", outputFileName); } else { Console.WriteLine(" [-] Error during Stage1 compilation"); foreach (CompilerError e in results.Errors) { Console.WriteLine(" {0}", e.ToString()); } return(null); } return(File.ReadAllBytes(sourcePath + @"\BuiltStages\" + outputFileName)); }
protected override Assembly GetAssembly(string fileName) { CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); string assemblyName = GetAssemblyName(fileName); var parameters = new CompilerParameters(); parameters.GenerateExecutable = false; // creating dll parameters.OutputAssembly = assemblyName; var results = provider.CompileAssemblyFromFile(parameters, fileName); return(Assembly.LoadFrom(results.PathToAssembly)); }
/// <summary> /// See: OutputExecutable and CompilerParameters /// </summary> static public bool CompileExecutable(String sourceName) { bool compileOk = false; FileInfo sourceFile = new FileInfo(sourceName); CodeDomProvider provider = GetProvider(sourceFile); if (provider != null) { // sets our static CompilerParams ExecutablePath String OutputExecutable = String.Format( @"{0}\{1}.exe", System.Environment.CurrentDirectory, sourceFile.Name.Replace(".", "_")); CompilerParameters cp = CompilerParams; CompilerResults cr = provider .CompileAssemblyFromFile(cp, sourceName); if (cr.Errors.Count > 0) { Console.WriteLine( "Errors building {0} into {1}", sourceName, cr.PathToAssembly); foreach (CompilerError ce in cr.Errors) { Console.WriteLine(" {0}", ce.ToString()); Console.WriteLine(); } } else { // Display a successful compilation message. Console.WriteLine( "Source {0} built into {1} successfully.", sourceName, cr.PathToAssembly); } // Return the results of the compilation. if (cr.Errors.Count > 0) { compileOk = false; } else { compileOk = true; } } return(compileOk); }
private static bool CompileExecutable(string sourceName) { FileInfo sourceFile = new FileInfo(sourceName); CodeDomProvider provider = null; bool compileOK = false; if (sourceFile.Extension.ToUpper(CultureInfo.InvariantCulture) == ".CS") { provider = CodeDomProvider.CreateProvider("CSharp"); } else { Console.WriteLine("Source file must have a .cs extension"); } if (provider != null) { string exeName = string.Format(@"{0}\{1}.exe", System.Environment.CurrentDirectory, sourceFile.Name.Replace(".", "_")); CompilerParameters cp = new CompilerParameters(); cp.GenerateExecutable = true; cp.OutputAssembly = exeName; cp.GenerateInMemory = false; cp.TreatWarningsAsErrors = true; cp.ReferencedAssemblies.Add("System.dll"); CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceName); if (cr.Errors.Count > 0) { Console.WriteLine("Errors building {0} into {1}", sourceName, cr.PathToAssembly); foreach (CompilerError ce in cr.Errors) { Console.WriteLine(" {0}", ce.ToString()); } } else { Console.WriteLine("Source {0} \nbuilt into {1} successfully.", sourceName, cr.PathToAssembly); } if (cr.Errors.Count > 0) { compileOK = false; } else { compileOK = true; } } return(compileOK); }
static void Main(string[] args) { CodeDomProvider provider = CodeDomProvider.CreateProvider(providerName); LogMessage("Building CodeDOM graph..."); CodeCompileUnit cu = new CodeCompileUnit(); cu = BuildHelloWorldGraph(); //<Snippet5> StreamWriter sourceFile = new StreamWriter(sourceFileName); provider.GenerateCodeFromCompileUnit(cu, sourceFile, null); sourceFile.Close(); //</Snippet5> //<Snippet6> CompilerParameters opt = new CompilerParameters(new string[] { "System.dll" }); opt.GenerateExecutable = true; opt.OutputAssembly = "HelloWorld.exe"; opt.TreatWarningsAsErrors = true; opt.IncludeDebugInformation = true; opt.GenerateInMemory = true; opt.CompilerOptions = "/doc:HelloWorldDoc.xml"; CompilerResults results; LogMessage("Compiling with " + providerName); results = provider.CompileAssemblyFromFile(opt, sourceFileName); //</Snippet6> OutputResults(results); if (results.NativeCompilerReturnValue != 0) { LogMessage(""); LogMessage("Compilation failed."); } else { LogMessage(""); LogMessage("Demo completed successfully."); } File.Delete(sourceFileName); }