public static void Main () { CompilerParameters options = new CompilerParameters (); options.WarningLevel = 4; CodeDomProvider provider = new CSharpCodeProvider (); #if NET_2_0 CompilerResults result = provider.CompileAssemblyFromDom ( options, new CodeSnippetCompileUnit (src)); #else ICodeCompiler compiler = provider.CreateCompiler (); CompilerResults result = compiler.CompileAssemblyFromDom ( options, new CodeSnippetCompileUnit (src)); #endif Assert.IsFalse (result.Errors.HasErrors, "#1"); #if ONLY_1_0 Assert.IsFalse (result.Errors.HasWarnings, "#2"); Assert.AreEqual (0, result.Errors.Count, "#3"); #else Assert.IsTrue (result.Errors.HasWarnings, "#2"); #if MONO Assert.AreEqual (2, result.Errors.Count, "#3"); Assert.AreEqual ("CS0108", result.Errors [0].ErrorNumber, "#4"); Assert.IsTrue (result.Errors [0].IsWarning, "#5"); Assert.AreEqual ("CS0169", result.Errors [1].ErrorNumber, "#6"); Assert.IsTrue (result.Errors [1].IsWarning, "#7"); #else Assert.AreEqual (1, result.Errors.Count, "#3"); Assert.AreEqual ("CS0108", result.Errors [0].ErrorNumber, "#4"); Assert.IsTrue (result.Errors [0].IsWarning, "#5"); #endif #endif }
public void CreateCompiler_ReturnsSame() { CSharpCodeProvider provider = new CSharpCodeProvider(); #pragma warning disable 0618 Assert.Same(provider.CreateCompiler(), provider.CreateCompiler()); #pragma warning restore 0618 }
private IReflectionOptimizer Build(string code) { CodeDomProvider provider = new CSharpCodeProvider(); CompilerResults res; if (FluorineConfiguration.Instance.OptimizerSettings.Debug) { string file = Path.Combine(Path.GetTempPath(), _mappedClass.FullName.Replace('.', '_').Replace("+", "__")) + ".cs"; StreamWriter sw = File.CreateText(file); sw.Write(code); sw.Close(); #if LOGGING log.Debug(__Res.GetString(__Res.Optimizer_FileLocation, _mappedClass.FullName, file)); #endif _cp.TempFiles = new TempFileCollection(Path.GetTempPath()); _cp.TempFiles.KeepFiles = true; #if !(NET_1_1) res = provider.CompileAssemblyFromFile(_cp, file); #else ICodeCompiler compiler = provider.CreateCompiler(); res = compiler.CompileAssemblyFromFile(_cp, file); #endif } else { #if !(NET_1_1) res = provider.CompileAssemblyFromSource(_cp, new string[] { code }); #else ICodeCompiler compiler = provider.CreateCompiler(); res = compiler.CompileAssemblyFromSource(_cp, code); #endif } if (res.Errors.HasErrors) { foreach (CompilerError e in res.Errors) { #if LOGGING log.Error(__Res.GetString(__Res.Compiler_Error, e.Line, e.Column, e.ErrorText)); #endif } throw new InvalidOperationException(res.Errors[0].ErrorText); } Assembly assembly = res.CompiledAssembly; System.Type[] types = assembly.GetTypes(); IReflectionOptimizer optimizer = (IReflectionOptimizer)assembly.CreateInstance(types[0].FullName, false, BindingFlags.CreateInstance, null, null, null, null); return(optimizer); }
private bool init(string generateCode, params string[] referenceAssemblies) { bool flag = false; result = null; using (CSharpCodeProvider provider = new CSharpCodeProvider()) { ICodeCompiler objICodeCompiler = provider.CreateCompiler(); CompilerParameters objCompilerParameters = new CompilerParameters(); if (referenceAssemblies != null) { objCompilerParameters.ReferencedAssemblies.AddRange(referenceAssemblies); } objCompilerParameters.GenerateExecutable = false; objCompilerParameters.GenerateInMemory = true; result = objICodeCompiler.CompileAssemblyFromSource(objCompilerParameters, generateCode); } if (result != null) { if (result.Errors.Count > 0 && ErrorHandler != null) { ErrorHandler(result.Errors); } else { flag = true; } } return(flag); }
public static object CodeToObject(string code) { // 1.CSharpCodePrivoder var objCSharpCodePrivoder = new CSharpCodeProvider(); // 2.ICodeComplier var objICodeCompiler = objCSharpCodePrivoder.CreateCompiler(); // 3.CompilerParameters var objCompilerParameters = new CompilerParameters(); objCompilerParameters.ReferencedAssemblies.Add("System.dll"); objCompilerParameters.GenerateExecutable = false; objCompilerParameters.GenerateInMemory = true; // 4.CompilerResults var cr = objICodeCompiler.CompileAssemblyFromSource(objCompilerParameters, GenerateCode(code)); if (cr.Errors.HasErrors) { return(new object()); } else { Assembly objAssembly = cr.CompiledAssembly; object objHelloWorld = objAssembly.CreateInstance("CodeHelper.CodeHelper"); MethodInfo objMI = objHelloWorld.GetType().GetMethod("OutPut"); var obj = objMI.Invoke(objHelloWorld, null); return(objMI.Invoke(objHelloWorld, null)); } }
public void Submit(Problem problem) { string sourcePath = view.ReadString("Программаның файлы орналасқан адресті жазыңыз немесе тышқанмен сүйреп әкеліңіз\n", ConsoleColor.Green); if (!File.Exists(sourcePath)) { view.ShowError("Файл табылмады!"); return; } string sourceText = File.ReadAllText(sourcePath); CSharpCodeProvider codeProvider = new CSharpCodeProvider(); ICodeCompiler icc = codeProvider.CreateCompiler(); CompilerParameters parameters = new CompilerParameters(); parameters.GenerateExecutable = true; parameters.OutputAssembly = "test.exe"; CompilerResults results = icc.CompileAssemblyFromSource(parameters, sourceText); Attempt attempt = model.AddAttemption(CurrentUser, problem); if (results.Errors.HasErrors) { view.Print("Компиляция барысында қате шықты!\n", ConsoleColor.Red); attempt.Verdict = Verdict.Complation_error; } else { RunSolution(problem, results.PathToAssembly, ref attempt); } model.Attempts.Add(attempt); ReadKey(); }
private Assembly BuildAssembly() { Microsoft.CSharp.CSharpCodeProvider provider = new CSharpCodeProvider(); ICodeCompiler compiler = provider.CreateCompiler(); CompilerParameters compilerparams = new CompilerParameters() { GenerateExecutable = false, GenerateInMemory = true }; compilerparams.ReferencedAssemblies.Add("TES30-API.dll"); CompilerResults results = compiler.CompileAssemblyFromSource(compilerparams, Header + code); if (results.Errors.HasErrors) { StringBuilder errors = new StringBuilder("Compiler Errors :\r\n"); foreach (CompilerError error in results.Errors) { errors.AppendFormat("Line {0},{1}\t: {2}\n", error.Line, error.Column, error.ErrorText); } throw new Exception(errors.ToString()); } else { return(results.CompiledAssembly); } }
static public CompilerResults Compile(string Code, string DestFileName, string ReferenceRoot) { CSharpCodeProvider cp = new CSharpCodeProvider(); #if (!vs2005) ICodeCompiler ic = cp.CreateCompiler(); #endif CompilerParameters cpar = new CompilerParameters(); cpar.GenerateExecutable = false; cpar.IncludeDebugInformation = false; if (DestFileName != null && DestFileName != "") { cpar.OutputAssembly = DestFileName; } else { cpar.GenerateInMemory = true; } cpar.ReferencedAssemblies.Add(ReferenceRoot + "Easychart.Finance.dll"); #if (vs2005) CompilerResults cr = cp.CompileAssemblyFromSource(cpar, Code); #else CompilerResults cr = ic.CompileAssemblyFromSource(cpar, Code); #endif return(cr); }
public void RunTest() { CSharpCodeProvider objcsp = new CSharpCodeProvider(); ICodeCompiler objICodeCompiler = objcsp.CreateCompiler(); CompilerParameters objCompilerParameters = new CompilerParameters(); objCompilerParameters.ReferencedAssemblies.Add("System.dll"); //是否生成可执行文件 objCompilerParameters.GenerateExecutable = false; //是否生成在内存中 objCompilerParameters.GenerateInMemory = true; string code = "using System.Windows.Forms; public class Test { public void Hello(){ } }"; //编译代码 CompilerResults cr = objICodeCompiler.CompileAssemblyFromSource(objCompilerParameters, code); if (cr.Errors.HasErrors) { var msg = string.Join(Environment.NewLine, cr.Errors.Cast <CompilerError>().Select(err => err.ErrorText)); Console.WriteLine("编译错误"); } else { Assembly objAssembly = cr.CompiledAssembly; object objHelloWorld = objAssembly.CreateInstance("Test"); MethodInfo objMI = objHelloWorld.GetType().GetMethod("Hello"); objMI.Invoke(objHelloWorld, null); } }
static Generic() { CodeDomProvider provider = new CSharpCodeProvider(); m_Compiler = provider.CreateCompiler(); m_CompilerParams = new CompilerParameters(new string[] { "System.dll" }, m_Path); }
private static void compileCode(CodeCompileUnit compileUnit) { //Specify how we want our code compiled CompilerParameters parameters = new CompilerParameters(); parameters.GenerateExecutable = true; parameters.GenerateInMemory = false; parameters.OutputAssembly = "CodeDOMDemoOutput.exe"; //Compile the code CodeDomProvider provider = new CSharpCodeProvider(); ICodeCompiler compiler = provider.CreateCompiler(); CompilerResults results = compiler.CompileAssemblyFromDom(parameters, compileUnit); //Signal completion and display any compiler output Console.WriteLine("\nAssembly created and saved to: {0}", results.PathToAssembly); if (results.Output.Count > 0) { Console.WriteLine("Compiler output was"); foreach (string output in results.Output) { Console.WriteLine("\t{0}", output); } } }
public void Deny_Unrestricted() { CSharpCodeProvider csprov = new CSharpCodeProvider(); Assert.AreEqual("cs", csprov.FileExtension, "FileExtension"); Assert.IsNotNull(csprov.CreateCompiler(), "CreateCompiler"); Assert.IsNotNull(csprov.CreateGenerator(), "CreateGenerator"); try { Assert.IsNotNull(csprov.GetConverter(typeof(string)), "GetConverter"); } catch (NotImplementedException) { // mono } #if NET_2_0 CodeTypeMember ctm = new CodeTypeMember(); StringWriter sw = new StringWriter(); CodeGeneratorOptions cgo = new CodeGeneratorOptions(); try { csprov.GenerateCodeFromMember(ctm, sw, cgo); } catch (NotImplementedException) { // mono } #endif }
public static object CSEval(string CSCode, string Output, List <string> Assemblies) { CSharpCodeProvider codeProvider = new CSharpCodeProvider(); ICodeCompiler icc = codeProvider.CreateCompiler(); System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters(); parameters.GenerateExecutable = true; foreach (string s in Assemblies) { parameters.ReferencedAssemblies.Add(s); } parameters.OutputAssembly = Output; CompilerResults results = icc.CompileAssemblyFromSource(parameters, CSCode); if (results.Errors.Count > 0) { string Errors = string.Empty; foreach (CompilerError CompErr in results.Errors) { Errors += "Line number " + CompErr.Line + ", Error Number: " + CompErr.ErrorNumber + ", '" + CompErr.ErrorText + ";" + Environment.NewLine + Environment.NewLine; } return(Errors); } else { Process.Start(Output); return("Succes!"); } }
static void loadFile(string fileName) { string SourceString = System.IO.File.ReadAllText(fileName); CSharpCodeProvider codeProvider = new CSharpCodeProvider(); ICodeCompiler icc = codeProvider.CreateCompiler(); System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters(); parameters.GenerateInMemory = true; CompilerResults results = icc.CompileAssemblyFromSource(parameters, SourceString); if (results.Errors.Count > 0) { string error = ""; foreach (CompilerError CompErr in results.Errors) { error = "Line number " + CompErr.Line + ", Error Number: " + CompErr.ErrorNumber + ", '" + CompErr.ErrorText + ";" + Environment.NewLine + Environment.NewLine; } Console.Write(error); } execute(results.CompiledAssembly); }
void BuildCode(string code, string output, string ico, params string[] resources) { CSharpCodeProvider codeProvider = new CSharpCodeProvider(new Dictionary <string, string>() { { "CompilerVersion", "v4.0" } }); ICodeCompiler icc = codeProvider.CreateCompiler(); System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.dll", "System.Core.dll", "System.Windows.Forms.dll", "System.Xml.dll", "System.Xml.Linq.dll" });//, parameters.GenerateExecutable = true; parameters.OutputAssembly = output; parameters.CompilerOptions = "/platform:X86 /target:winexe"; parameters.CompilerOptions += string.Format(" /win32icon:\"{0}\"", ico); foreach (string res in resources) { parameters.EmbeddedResources.Add(res); } CompilerResults results = icc.CompileAssemblyFromSource(parameters, code); if (results.Errors.Count > 0) { foreach (CompilerError CompErr in results.Errors) { BuildLog.Text = BuildLog.Text + "Line number " + CompErr.Line + ", Error Number: " + CompErr.ErrorNumber + ", '" + CompErr.ErrorText + ";" + Environment.NewLine + Environment.NewLine; } } else { BuildLog.Text += "Successfull build.\n"; } }
private void Form1_Click(object sender, EventArgs e) { CSharpCodeProvider objCSharpCodePrivoder = new CSharpCodeProvider(); // 2.ICodeComplier ICodeCompiler objICodeCompiler = objCSharpCodePrivoder.CreateCompiler(); // 3.CompilerParameters CompilerParameters objCompilerParameters = new CompilerParameters(); objCompilerParameters.ReferencedAssemblies.Add("System.dll"); objCompilerParameters.GenerateExecutable = false; objCompilerParameters.GenerateInMemory = true; // 4.CompilerResults CompilerResults cr = objICodeCompiler.CompileAssemblyFromSource(objCompilerParameters, GenerateCode()); if (cr.Errors.HasErrors) { Console.WriteLine("编译错误:"); foreach (CompilerError err in cr.Errors) { Console.WriteLine(err.ErrorText); } } else { // 通过反射,调用HelloWorld的实例 Assembly objAssembly = cr.CompiledAssembly; object bb = objAssembly.CreateInstance("AA.BB"); this.propertyGrid1.SelectedObject = bb; } }
public static Type readIn() { int counter = 0; string line; // Read the file and display it line by line. var csc = new CSharpCodeProvider(); var cc = csc.CreateCompiler(); CompilerParameters cp = new CompilerParameters(); cp.ReferencedAssemblies.Add("mscorlib.dll"); cp.ReferencedAssemblies.Add("System.dll"); StringBuilder sb = new StringBuilder(); System.IO.StreamReader file = new System.IO.StreamReader(@"d:\Server\Visual_studio\GeneratedClasses\GeneratedClasses\PersonPersistentPreProcessed.cs"); while ((line = file.ReadLine()) != null) { sb.Append(line); counter++; } // The string can contain any valid c# code // "results" will usually contain very detailed error messages var results = csc.CompileAssemblyFromSource(cp, sb.ToString()); System.Reflection.Assembly _assembly = results.CompiledAssembly; Type[] _types = _assembly.GetTypes(); Type eType = _assembly.GetType("Foo.MyClass"); file.Close(); return(eType); }
public static void Compile(string filename, string source) { CSharpCodeProvider codeProvider = new CSharpCodeProvider(); ICodeCompiler icc = codeProvider.CreateCompiler(); CompilerParameters parameters = new CompilerParameters(); parameters.GenerateExecutable = true; parameters.OutputAssembly = filename; CompilerResults results = icc.CompileAssemblyFromSource(parameters, source); if (results.Errors.Count > 0) { Console.ForegroundColor = ConsoleColor.Red; foreach (CompilerError CompErr in results.Errors) { Console.WriteLine($"Line number: {CompErr.Line}\n" + $"Error Number: {CompErr.ErrorNumber}\n" + $"'{CompErr.ErrorText};\n"); } } else { Process.Start(filename); } }
/// <summary> /// Метод для определения количества итераций цикла /// </summary> /// <returns></returns> public int CheckCount() { int result = 0; string programText = Modify(Phrase); CSharpCodeProvider codeProvider = new CSharpCodeProvider(); ICodeCompiler icc = codeProvider.CreateCompiler(); CompilerParameters parameters = new CompilerParameters { GenerateExecutable = true, OutputAssembly = $"temp_{Guid.NewGuid()}.exe", }; CompilerResults results = icc.CompileAssemblyFromSource(parameters, programText); if (results.Errors.Count == 0) { using (Process pr = new Process()) { pr.StartInfo.FileName = parameters.OutputAssembly; pr.StartInfo.UseShellExecute = false; pr.Start(); pr.WaitForExit(2000); if (!pr.HasExited) { pr.Kill(); } result = pr.ExitCode; } } else { throw new Infrastructure.CompilationException(results.Errors[0]); } return(result); }
private void Run() { CSharpCodeProvider provider = new CSharpCodeProvider(); ICodeCompiler compiler = provider.CreateCompiler(); CompilerParameters parameter = new CompilerParameters(); //添加需要引用的DLL parameter.ReferencedAssemblies.Add("System.dll"); parameter.ReferencedAssemblies.Add("System.Windows.Forms.dll"); //是否生成可执行文件 parameter.GenerateExecutable = false; //是否生成在内存中 parameter.GenerateInMemory = true; CompilerResults cr = compiler.CompileAssemblyFromSource(parameter, txbCode.Text); if (cr.Errors.HasErrors) { var msg = string.Join(Environment.NewLine, cr.Errors.Cast <CompilerError>().Select(err => err.ErrorText)); MessageBox.Show(msg, "编译错误"); } else { Assembly assembly = cr.CompiledAssembly; object obj = assembly.CreateInstance("Test"); MethodInfo mi = obj.GetType().GetMethod("Hello"); mi.Invoke(obj, null); } }
/// <summary> /// 编译源码 /// </summary> /// <param name="sourceCode">源码</param> /// <param name="references"></param> /// <returns>返回错误集合</returns> public static string Compile(string[] sourceCode, List <string> references) { CSharpCodeProvider objCSharpCodePrivoder = new CSharpCodeProvider(); ICodeCompiler objICodeCompiler = objCSharpCodePrivoder.CreateCompiler(); CompilerParameters objCompilerParameters = new CompilerParameters(); objCompilerParameters.ReferencedAssemblies.Add("System.dll"); objCompilerParameters.ReferencedAssemblies.Add("System.Core.dll"); objCompilerParameters.ReferencedAssemblies.Add("System.Data.dll"); objCompilerParameters.ReferencedAssemblies.Add("Iveely.Database.dll"); if (references != null) { foreach (var reference in references) { objCompilerParameters.ReferencedAssemblies.Add(reference); } } objCompilerParameters.GenerateExecutable = false; objCompilerParameters.GenerateInMemory = true; CompilerResults cr = objICodeCompiler.CompileAssemblyFromSource(objCompilerParameters, GenerateCode(sourceCode)); if (cr.Errors.HasErrors) { StringBuilder errors = new StringBuilder(); foreach (CompilerError err in cr.Errors) { string errorInformation = string.Format("line:{0},Cloumn:{1},error:{2}", err.Line, err.Column, err.ErrorText); errors.AppendLine(errorInformation); } return(errors.ToString()); } return(string.Empty); }
static void Main () { const string source = @" public class Scriptefaa4ad0a85c49519cad6a19fbb93caf { string PadRight (string str, int padding) { return str.PadRight(padding); } }"; CompilerParameters parameters = new CompilerParameters (); parameters.GenerateInMemory = true; CodeDomProvider provider = new CSharpCodeProvider (); #if NET_2_0 CompilerResults results = provider.CompileAssemblyFromSource ( parameters, source); #else ICodeCompiler compiler = provider.CreateCompiler (); CompilerResults results = compiler.CompileAssemblyFromSource ( parameters, source); #endif Assert.AreEqual (1, results.Errors.Count, "#1"); Assert.IsFalse (results.Errors.HasErrors, "#2"); Assert.IsTrue (results.Errors.HasWarnings, "#3"); foreach (CompilerError error in results.Errors) Assert.IsTrue (error.IsWarning, "#4"); Assert.IsNotNull (results.CompiledAssembly, "#5"); }
public void ProcessRequest(HttpContext ctx) { // Code for calculating tax is provided as unvalidated user input string taxFormula = ctx.Request.QueryString["tax_formula"]; // Used to create C# StringBuilder sourceCode = new StringBuilder(""); sourceCode.Append("public class TaxCalc {\n"); sourceCode.Append("\tpublic int CalculateTax(int value){\n"); sourceCode.Append("\t\treturn " + taxFormula + "; \n"); sourceCode.Append("\t}\n"); sourceCode.Append("}\n"); // BAD: This compiles the sourceCode, containing unvalidated user input CSharpCodeProvider c = new CSharpCodeProvider(); ICodeCompiler icc = c.CreateCompiler(); CompilerParameters cp = new CompilerParameters(); CompilerResults cr = icc.CompileAssemblyFromSource(cp, sourceCode.ToString()); // Compiled input is loaded, and an instance of the class is constructed System.Reflection.Assembly a = cr.CompiledAssembly; object taxCalc = a.CreateInstance("TaxCalc"); // Unsafe code is executed Type taxCalcType = o.GetType(); MethodInfo mi = type.GetMethod("CalculateTax"); int value = int.Parse(ctx.Request.QueryString["value"]); int s = (int)mi.Invoke(o, new object[] { value }); // Result is returned to the user ctx.Response.Write("Tax value is: " + s); }
public static object Eval(string sCSCode) { CSharpCodeProvider c = new CSharpCodeProvider(); ICodeCompiler icc = (ICodeCompiler)c.CreateCompiler(); CompilerParameters cp = new CompilerParameters(); cp.ReferencedAssemblies.Add("system.dll"); cp.ReferencedAssemblies.Add("system.xml.dll"); cp.ReferencedAssemblies.Add("system.data.dll"); cp.ReferencedAssemblies.Add("system.windows.forms.dll"); cp.ReferencedAssemblies.Add("system.drawing.dll"); cp.CompilerOptions = "/t:library"; cp.GenerateInMemory = true; StringBuilder sb = new StringBuilder(""); sb.Append(sCSCode); CompilerResults cr = icc.CompileAssemblyFromSource(cp, sb.ToString()); if (cr.Errors.Count > 0) { Console.Write("ERROR: " + cr.Errors[0].ErrorText, "Error evaluating cs code"); return(null); } System.Reflection.Assembly a = cr.CompiledAssembly; object o = a.CreateInstance("Cgi.Cgi"); Type t = o.GetType(); MethodInfo mi = t.GetMethod("main"); object s = mi.Invoke(o, null); return(s); }
public ExtensionLoader(LayerFactory _layerFactory, GeometryFactory _geometryFactory) { codeProvider = new CSharpCodeProvider(); compiler = codeProvider.CreateCompiler(); layerFactory = _layerFactory; geometryFactory = _geometryFactory; }
/// <summary> /// 编译cs文件为dll文件集合到指定目录 返回错误信息集合 /// </summary> /// <param name="outPath">dll输出目录</param> /// <param name="files">要编译到dll文件的路径集合</param> /// <returns>错误信息集合</returns> public static List <string> CompileFromFiles(string outPath, params string[] files) { // 1.CSharpCodePrivoder CSharpCodeProvider objCSharpCodePrivoder = new CSharpCodeProvider(); // 2.ICodeComplier ICodeCompiler objICodeCompiler = objCSharpCodePrivoder.CreateCompiler(); // 3.CompilerParameters CompilerParameters objCompilerParameters = new CompilerParameters(); objCompilerParameters.ReferencedAssemblies.Add("System.dll"); objCompilerParameters.GenerateExecutable = true; objCompilerParameters.GenerateInMemory = false; objCompilerParameters.OutputAssembly = outPath; objCompilerParameters.TreatWarningsAsErrors = false; CompilerResults cr = objICodeCompiler.CompileAssemblyFromFileBatch(objCompilerParameters, files); // 4.CompilerResults //CompilerResults cr = objICodeCompiler.CompileAssemblyFromSource(objCompilerParameters, "code"); //CompilerResults cr = objCSharpCodePrivoder.CompileAssemblyFromFile(objCompilerParameters, files); List <string> erros = null; if (cr.Errors.HasErrors) { erros = new List <string>(); foreach (CompilerError err in cr.Errors) { erros.Add(err.ErrorText); } } return(erros); }
public TypedDataSetGeneratorTest() { CodeDomProvider p = new CSharpCodeProvider(); gen = p.CreateGenerator(); compiler = p.CreateCompiler(); }
public string CompileAssemblyFromDomBatch(string tempDir) { CompilerParameters options = new CompilerParameters(); options.GenerateExecutable = false; options.GenerateInMemory = false; options.TempFiles = new TempFileCollection(tempDir); CSharpCodeProvider codeProvider = new CSharpCodeProvider(); ICodeCompiler compiler = codeProvider.CreateCompiler(); CompilerResults results = compiler.CompileAssemblyFromDomBatch(options, new CodeCompileUnit[] { new CodeCompileUnit(), new CodeCompileUnit() }); // verify compilation was successful AssertCompileResults(results, true); if (results.CompiledAssembly.Location.Length == 0) { throw new Exception("Location should not be empty string"); } if (results.PathToAssembly == null) { throw new Exception("PathToAssembly should not be null"); } return(results.PathToAssembly); }
public CompileResult CompileFromCSharpCode() { CSharpCodeProvider codeProvider = new CSharpCodeProvider(); ICodeCompiler icc = codeProvider.CreateCompiler(); System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters(); foreach (var item in CustomReferences) { parameters.ReferencedAssemblies.Add(item.ToString()); } parameters.GenerateExecutable = true; parameters.GenerateInMemory = false; parameters.OutputAssembly = OutputName; CompilerResults results = icc.CompileAssemblyFromSource(parameters, Code); if (results.Errors.Count > 0) { //Console.WriteLine(""); CompileResult res = new CompileResult(); res.IsSuccess = false; return(res); } else { CompileResult res = new CompileResult(); res.IsSuccess = true; return(res); } }
static void Main(string[] args) { string baseCode = File.ReadAllText("test.cs"); CSharpCodeProvider codeProvider = new CSharpCodeProvider(); ICodeCompiler icc = codeProvider.CreateCompiler(); System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters(); parameters.GenerateExecutable = true; parameters.OutputAssembly = "test.exe"; // parameters.ReferencedAssemblies.Add("lib/System.IO.FileSystem.dll"); if (File.Exists("test.exe")) { File.Delete("test.exe"); } CompilerResults results = icc.CompileAssemblyFromSource(parameters, baseCode); if (results.Errors.Count > 0) { foreach (CompilerError CompErr in results.Errors) { Console.WriteLine("Line number " + CompErr.Line + ", Error Number: " + CompErr.ErrorNumber + ", '" + CompErr.ErrorText + ";" + Environment.NewLine + Environment.NewLine); } } else { Console.WriteLine("Votre application a été généré"); } Console.ReadKey(); }
private void CompileAssembly(string csFile, string outputName, bool forBraille, List <Ref> refs, List <string> errors) { var codeProvider = new CSharpCodeProvider(); var icc = codeProvider.CreateCompiler(); var parameters = new CompilerParameters(); parameters.GenerateExecutable = outputName.EndsWith("exe"); parameters.OutputAssembly = outputName; if (forBraille) { parameters.CoreAssemblyFileName = GetCorlibPath(); } if (refs != null) { parameters.ReferencedAssemblies.AddRange(refs.Select(r => r.path).ToArray()); } var results = icc.CompileAssemblyFromFileBatch(parameters, new[] { Path.Combine(workingDir, "TestInclude.cs"), csFile }); if (results.Errors.Count > 0) { errors.AddRange( results .Errors .OfType <CompilerError>() .Select( error => string.Format("Line number {0}, Error Number: {1}, '{2};", error.Line, error.ErrorNumber, error.ErrorText))); } }
static void Main(string[] args) { // 1.CSharpCodePrivoder CSharpCodeProvider objCSharpCodePrivoder = new CSharpCodeProvider(); // 2.ICodeComplier ICodeCompiler objICodeCompiler = objCSharpCodePrivoder.CreateCompiler(); // 3.CompilerParameters CompilerParameters objCompilerParameters = new CompilerParameters(); objCompilerParameters.ReferencedAssemblies.Add("System.dll"); objCompilerParameters.GenerateExecutable = false; objCompilerParameters.GenerateInMemory = true; // 4.CompilerResults CompilerResults cr = objICodeCompiler.CompileAssemblyFromSource(objCompilerParameters, GenerateCode()); if (cr.Errors.HasErrors) { Console.WriteLine("编译错误:"); foreach (CompilerError err in cr.Errors) { Console.WriteLine(err.ErrorText); } } else { // 通过反射,调用HelloWorld的实例 Assembly objAssembly = cr.CompiledAssembly; object objHelloWorld = objAssembly.CreateInstance("DynamicCodeGenerate.HelloWorld"); MethodInfo objMI = objHelloWorld.GetType().GetMethod("OutPut"); Console.WriteLine(objMI.Invoke(objHelloWorld, null)); } Console.ReadLine(); }
private static void CreateResourceFile( string csFile, string resFile, string outputDir, out string sourceHash, out int viewCount) { viewCount = -1; sourceHash = string.Empty; var codeProvider = new CSharpCodeProvider(); var inMemoryCodeCompiler = codeProvider.CreateCompiler(); var parameters = new CompilerParameters(); parameters.ReferencedAssemblies.Add("System.Data.Entity.dll"); parameters.GenerateInMemory = true; CompilerResults results = inMemoryCodeCompiler.CompileAssemblyFromFile(parameters, csFile); if (results.Errors.Count == 0) { Assembly resultingAssembly = results.CompiledAssembly; Type[] typeList = resultingAssembly.GetTypes(); foreach (Type type in typeList) { if (type.BaseType == typeof(EntityViewContainer)) { MethodInfo[] methodInfo = type.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance); var instance = (EntityViewContainer)Activator.CreateInstance(type); sourceHash = instance.HashOverAllExtentViews; viewCount = instance.ViewCount; using (var resWriter = new ResourceWriter(Path.Combine(outputDir, resFile))) { foreach (MethodInfo method in methodInfo) { if (char.IsDigit(method.Name, method.Name.Length - 1)) { var result = (KeyValuePair<string, string>)method.Invoke(instance, null); resWriter.AddResource(method.Name.Replace("GetView", string.Empty), result); } } resWriter.Generate(); resWriter.Close(); } } } } else { Console.WriteLine("Unable to Generate Resource File"); } }