/// <summary> /// Returns the results of the compilation /// </summary> /// <param name="Source"></param> /// <param name="Reference"></param> /// <param name="Provider"></param> /// <returns></returns> public static CompilerResults CompileScript(string Source, string Reference, CodeDomProvider Provider) { ICodeCompiler compiler = Provider.CreateCompiler(); CompilerParameters parms = new CompilerParameters(); CompilerResults results; // Configure parameters parms.MainClass = "Script"; parms.GenerateExecutable = false; parms.GenerateInMemory = true; parms.TempFiles = new TempFileCollection(Path.GetTempPath(), false); //parms.OutputAssembly="scripter_"+Assembly.GetCallingAssembly().GetName().Version.Build; parms.IncludeDebugInformation = false; if (Reference != null && Reference.Length != 0) { parms.ReferencedAssemblies.Add(Reference); } foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) { parms.ReferencedAssemblies.Add(asm.Location); } parms.ReferencedAssemblies.Add("System.Windows.Forms.dll"); parms.ReferencedAssemblies.Add("System.dll"); // Compile results = compiler.CompileAssemblyFromSource(parms, Source); return(results); }
/// <summary> /// Verifies that <paramref name="source"/> compiles using the provided compiler. /// </summary> /// <param name="compiler">Compiler instance</param> /// <param name="source">Source code to compile</param> public static void Compiles(ICodeCompiler compiler, Stream source) { Assert.IsNotNull(compiler); Assert.IsNotNull(source); CompilerParameters ps = new CompilerParameters(); Compiles(compiler, ps, source); }
static Generic() { CodeDomProvider provider = new CSharpCodeProvider(); m_Compiler = provider.CreateCompiler(); m_CompilerParams = new CompilerParameters(new string[] { "System.dll" }, m_Path); }
/// <summary> /// スクリプトをコンパイルする /// </summary> /// <exception cref="CompileErrorException"> /// コンパイルエラーが発生した場合はこの例外を投げる /// </exception> public void Compile() { ICodeCompiler compiler = provider.CreateCompiler(); CompilerParameters compilerParams = new CompilerParameters(); foreach (string assembly in referenceAssemblies) { compilerParams.ReferencedAssemblies.Add(assembly); } compilerParams.GenerateInMemory = true; compilerParams.GenerateExecutable = false; compilerParams.IncludeDebugInformation = generateDebugInfo; CompilerResults result = compiler.CompileAssemblyFromSourceBatch (compilerParams, (string[])scriptCode.ToArray(typeof(string))); foreach (CompilerError error in result.Errors) { if (!error.IsWarning) { throw new CodeDomCompileErrorException(result); } } scriptAssembly = result.CompiledAssembly; }
public CompetitionService(ICodeCompiler codeCompiler, IChallengeService challengeService, IPlayerService playerService, ISolutionService solutionService) { _codeCompiler = codeCompiler; _challengeService = challengeService; _playerService = playerService; _solutionService = solutionService; }
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"); // 这里和下面的具体的代码里的namespace和class对应 MethodInfo objMI = objHelloWorld.GetType().GetMethod("OutPut"); //获得指定的方法 Console.WriteLine("执行结果:" + objMI.Invoke(objHelloWorld, null)); //调用Invoke执行 } Console.ReadLine(); }
// 加载".cs"文件 public static Assembly CompileFiles(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 = false; objCompilerParameters.GenerateInMemory = true; // 4.CompilerResults CompilerResults cr = objICodeCompiler.CompileAssemblyFromFileBatch(objCompilerParameters, files); if (cr.Errors.HasErrors) { Console.WriteLine("编译错误:"); foreach (CompilerError err in cr.Errors) { Console.WriteLine(err.ErrorText); } return(null); } 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.WriteLine("编译成功!"); return(cr.CompiledAssembly); } }
static void testVb() { try { var baseDir = @"C:\Program Files (x86)\Notepad++\plugins\CSScriptNpp\Roslyn\"; //baseDir = @"E:\Galos\Projects\CS-Script.Npp\CSScript.Npp\src\CSScriptNpp\CSScriptNpp\Roslyn\"; CSSCodeProvider.CompilerPath = baseDir + "vbc.exe"; CSSCodeProvider.ProviderPath = baseDir + "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.dll"; CSSCodeProvider.CompilerServerTimeToLive = 600; CSSCodeProvider.CompilerServerTimeToLive = 6; ICodeCompiler compiler = CSSCodeProvider.CreateCompiler("code.vb"); var compilerParams = new CompilerParameters(); //var file = @"E:\cs-script\samples\Hello.vb"; //compilerParams.ReferencedAssemblies.Add(@"System.Net.Http.Formatting.dll"); //compilerParams.ReferencedAssemblies.Add(@"System.dll"); //var result = compiler.CompileAssemblyFromFile(compilerParams, file); var result = compiler.CompileAssemblyFromSource(compilerParams, @" Imports System Imports System.Windows.Forms Module Module1 Sub Main() Console.WriteLine(""Hello World!(VB)"") End Sub End Module"); bool success = !result.Errors.HasErrors; } catch { } Console.WriteLine("done"); }
private static CompilerResults CompileAssemblyFromSource(string source) { CompilerParameters parameters = new CompilerParameters(); Assembly oCurrentAssembly = typeof(Program).Assembly; foreach (AssemblyName oName in oCurrentAssembly.GetReferencedAssemblies()) { var strLocation = Assembly.ReflectionOnlyLoad(oName.FullName).Location; parameters.ReferencedAssemblies.Add(strLocation); } string exeName = Assembly.GetEntryAssembly().Location; parameters.ReferencedAssemblies.Add(exeName); parameters.GenerateExecutable = false; CSharpCodeProvider codeProvider = new CSharpCodeProvider(); ICodeCompiler icc = codeProvider.CreateCompiler(); CompilerResults results = icc.CompileAssemblyFromSource(parameters, source); return(results); }
public static bool Transform(List <string> fileList, string outPutFilePath) { StringBuilder errors = new StringBuilder(); try { string xml = LoadFilesAsXml(fileList); string code = ApplyTransform(new XsltArgumentList(), xml); CSharpCodeProvider objProvider = new CSharpCodeProvider(); ICodeCompiler objCompiler = objProvider.CreateCompiler(); CompilerParameters objCompilerParameters = new CompilerParameters(); objCompilerParameters.ReferencedAssemblies.Add("System.dll"); objCompilerParameters.ReferencedAssemblies.Add("protobuf-net.dll"); objCompilerParameters.GenerateExecutable = false; objCompilerParameters.GenerateInMemory = false; objCompilerParameters.OutputAssembly = Path.GetFileName(outPutFilePath); CompilerResults result = objCompiler.CompileAssemblyFromSource(objCompilerParameters, code); if (result.Errors.HasErrors) { Console.WriteLine("编译错误:"); foreach (CompilerError err in result.Errors) { Console.WriteLine(err.ErrorText); } } return(true); } catch { return(false); } }
/// <summary> /// 实例化WebServices /// </summary> /// <param name="url">WebServices地址</param> /// <param name="methodname">调用的方法</param> /// <param name="args">参数</param> /// <returns></returns> public static object InvokeWebService(string url, string methodname, object[] args) { //这里的namespace是需引用的webservices的命名空间,在这里是写死的,大家可以加一个参数从外面传进来。 string @namespace = "client"; try { //获取WSDL WebClient wc = new WebClient(); // wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//POST //wc. Stream stream = wc.OpenRead(url + "?WSDL"); ServiceDescription sd = ServiceDescription.Read(stream); string classname = sd.Services[0].Name; ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); CodeNamespace cn = new CodeNamespace(@namespace); //生成客户端代理类代码 CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); CSharpCodeProvider csc = new CSharpCodeProvider(); ICodeCompiler icc = csc.CreateCompiler(); //设定编译参数 CompilerParameters cplist = new CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); //编译代理类 CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu); 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); } throw new Exception(sb.ToString()); } //生成代理实例,并调用方法 System.Reflection.Assembly assembly = cr.CompiledAssembly; Type t = assembly.GetType(@namespace + "." + classname, true, true); object obj = Activator.CreateInstance(t); System.Reflection.MethodInfo mi = t.GetMethod(methodname); return(mi.Invoke(obj, args)); } catch (Exception exception) { return(exception.InnerException); } }
static void Main(string[] args) { Console.WriteLine("What string do you want the custom program to display?"); string message = Console.ReadLine(); Console.WriteLine("How many times do you want the program to display this message?"); int nDisplays = int.Parse(Console.ReadLine()); CodeCompileUnit unit = GenerateProgram(message, nDisplays); // Set up options for source code style CodeGeneratorOptions opts = new CodeGeneratorOptions(); opts.BracingStyle = "C"; opts.IndentString = "\t"; // Create code generator and write code file CSharpCodeProvider cscp = new CSharpCodeProvider(); ICodeGenerator gen = cscp.CreateGenerator(); StreamWriter sw = new StreamWriter("MyCode.cs"); gen.GenerateCodeFromCompileUnit(unit, sw, opts); sw.Close(); CompilerParameters compilerParams = new CompilerParameters(); compilerParams.GenerateExecutable = true; compilerParams.OutputAssembly = "MyCode.exe"; ICodeCompiler compiler = cscp.CreateCompiler(); compiler.CompileAssemblyFromFile(compilerParams, "MyCode.cs"); }
public bool Build() { try { CSharpCodeProvider codeProvider = new CSharpCodeProvider( ); ICodeCompiler icc = codeProvider.CreateCompiler( ); System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters( ); parameters.GenerateExecutable = false; parameters.OutputAssembly = dllname; CompilerResults results = icc.CompileAssemblyFromSourceBatch(parameters, filenames); foreach (var result in results.Output) { logger.Append(result.ToString( ) + "\n"); } return(true); } catch (Exception ex) { Console.Write("\n {0}", ex.Message); return(false); } }
public CompilerResults Compile() { if (string.IsNullOrWhiteSpace(Script)) { throw new Exception("Script is empty."); } CSharpCodeProvider codeProvider = new CSharpCodeProvider(); ICodeCompiler compiler = codeProvider.CreateCompiler(); CompilerParameters parameters = new CompilerParameters(); parameters.GenerateExecutable = false; parameters.GenerateInMemory = true; parameters.MainClass = $"{EntryClass}.{EntryMethod}"; parameters.IncludeDebugInformation = false; parameters.WarningLevel = WarningLevel; parameters.TreatWarningsAsErrors = WarningsAsErrors; parameters.CompilerOptions = CompilerOptions; foreach (var referenceName in _references) { parameters.ReferencedAssemblies.Add(referenceName); } return(compiler.CompileAssemblyFromSource(parameters, Script)); }
public static object VBEval(string VBCode, string Output, List <string> Assemblies) { VBCodeProvider codeProvider = new VBCodeProvider(); 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, VBCode); 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!"); } }
private void GenerateAssembly() { ICodeCompiler compiler = codeProvider.CreateCompiler(); string location = ""; if ((WsdlProperties.ProxyBaseType != null) && (WsdlProperties.ProxyBaseType.Length > 0)) { location = Type.GetType(WsdlProperties.ProxyBaseType, true).Assembly.Location; } string[] assemblyNames = { "System.Xml.dll", "System.dll", "System.Web.Services.dll", "System.Data.dll", Assembly.GetExecutingAssembly().Location, location }; var options = new CompilerParameters(assemblyNames); options.WarningLevel = 0; options.GenerateInMemory = false; CompilerResults results = compiler.CompileAssemblyFromSource(options, proxyCode); if (results.Errors.HasErrors) { foreach (CompilerError error in results.Errors) { CheckPoint(MessageType.Error, error.ToString()); } throw new Exception("CompilationErrors"); } proxyAssembly = results.CompiledAssembly; }
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 TypedDataSetGeneratorTest() { CodeDomProvider p = new CSharpCodeProvider(); gen = p.CreateGenerator(); compiler = p.CreateCompiler(); }
public object Eval(CodeDomProvider cdp, string scriptCode) { ICodeCompiler cc = cdp.CreateCompiler(); CompilerParameters args = new CompilerParameters(); args.GenerateExecutable = false; args.GenerateInMemory = true; foreach (string s in ReferencedAssemblies) { args.ReferencedAssemblies.Add(s); } args.CompilerOptions = CompilerOptions; fileCount++; string guidStr = Guid.NewGuid().ToString("N"); string assemblyName = "DynamicAssembly" + guidStr; string className = "DynamicClass" + guidStr; CompilerResults res = cc.CompileAssemblyFromSource(args, templateCode.Replace("#ASSEMBLYNAME#", assemblyName).Replace("#CLASSNAME#", className).Replace("#SCRIPTCODE#", scriptCode)); Results.Clear(); foreach (string s in res.Output) { Results.Add(s); } if (res.Output.Count > 0) { return(null); } return(res.CompiledAssembly.CreateInstance(assemblyName + "." + className)); }
public object LoadCode(CodeDomProvider cdp, string scriptCode, string assemblyName, string className) { ICodeCompiler cc = cdp.CreateCompiler(); CompilerParameters args = new CompilerParameters(); args.GenerateExecutable = false; args.GenerateInMemory = true; foreach (string s in ReferencedAssemblies) { args.ReferencedAssemblies.Add(s); } args.CompilerOptions = CompilerOptions; CompilerResults res = cc.CompileAssemblyFromSource(args, scriptCode); Results.Clear(); foreach (string s in res.Output) { Results.Add(s); } if (res.Output.Count > 0) { return(null); } return(res.CompiledAssembly.CreateInstance(assemblyName + "." + className)); }
public void SaveAssembly() { myassembly = new CodeCompileUnit(); myassembly.Namespaces.Add(mynamespace); CompilerParameters comparam = new CompilerParameters(new string[] { "mscorlib.dll" }); comparam.ReferencedAssemblies.Add("System.dll"); comparam.GenerateInMemory = false; comparam.GenerateExecutable = true; comparam.MainClass = "mynamespace.Myclass"; comparam.OutputAssembly = @"c:\temp\HelloWorld.exe"; Microsoft.CSharp.CSharpCodeProvider ccp = new Microsoft.CSharp.CSharpCodeProvider(); StreamWriter sw = new StreamWriter(@"c:\temp\HelloWorld.cs"); // ez is jo: // IndentedTextWriter // ??? IndentedTextWriter idt = new IndentedTextWriter(sw, " "); idt.Indent = 1; ICodeGenerator cscg = ccp.CreateGenerator(idt); ICodeCompiler icc = ccp.CreateCompiler(); CompilerResults compres = icc.CompileAssemblyFromDom(comparam, myassembly); cscg.GenerateCodeFromNamespace(mynamespace, idt, new CodeGeneratorOptions()); idt.Close(); if (compres == null || compres.Errors.Count > 0) { for (int i = 0; i < compres.Errors.Count; i++) { Console.WriteLine(compres.Errors[i]); } } }
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); }
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); }
public string DoCompilation(string code, string name) { CodeDomProvider provider = CodeDomProvider.CreateProvider("C#"); ICodeCompiler compiler = provider.CreateCompiler(); CompilerParameters parameters = new CompilerParameters(); parameters.OutputAssembly = @name; parameters.GenerateExecutable = true; CompilerResults results = compiler.CompileAssemblyFromSource(parameters, code); System.Threading.Thread.Sleep(10000); if (results.Output.Count == 0) { return("success"); } else { CompilerErrorCollection CErros = results.Errors; foreach (CompilerError err in CErros) { string msg = string.Format("Erro:{0} on line{1} file name:{2}", err.Line, err.ErrorText, err.FileName); return(msg); } } return("not working"); }
public void CompileFromDomBatch_InMemory() { // create a file in temp directory to ensure that compiler is not removing // too much (temporary) files string tempFile = Path.Combine(_tempDir, "file." + _codeProvider.FileExtension); using (FileStream fs = File.Create(tempFile)) { fs.Close(); } CompilerParameters options = new CompilerParameters(); options.GenerateExecutable = false; options.GenerateInMemory = true; options.TempFiles = new TempFileCollection(_tempDir); ICodeCompiler compiler = _codeProvider.CreateCompiler(); CompilerResults results = compiler.CompileAssemblyFromDomBatch(options, new CodeCompileUnit[] { new CodeCompileUnit(), new CodeCompileUnit() }); // verify compilation was successful AssertCompileResults(results, true); Assert.AreEqual(string.Empty, results.CompiledAssembly.Location, "#1"); Assert.IsNull(results.PathToAssembly, "#2"); // verify we don't cleanup files in temp directory too agressively string[] tempFiles = Directory.GetFiles(_tempDir); Assert.AreEqual(1, tempFiles.Length, "#3"); Assert.AreEqual(tempFile, tempFiles[0], "#4"); }
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 static CompilerResults CompileVBScripts(string name, string sourcePath, string assemblyFile, LibraryConfig libConfig, bool debug) { VBCodeProvider provider = new VBCodeProvider(); ICodeCompiler compiler = provider.CreateCompiler(); string[] files = GetScripts(libConfig, sourcePath, "*.vb"); if (files.Length == 0) { return(null); } Console.Write("{0}[VB,{1}", name, files.Length); CompilerResults results = compiler.CompileAssemblyFromFileBatch(new CompilerParameters(GetReferenceAssemblies(), assemblyFile, true), files); m_AdditionalReferences.Add(assemblyFile); if (results.Errors.Count > 0) { int errorCount = 0, warningCount = 0; foreach (CompilerError e in results.Errors) { if (e.IsWarning) { ++warningCount; } else { ++errorCount; } } Console.WriteLine(); if (errorCount > 0) { Console.WriteLine("failed ({0} errors, {1} warnings)", errorCount, warningCount); } else { Console.WriteLine("done ({0} errors, {1} warnings)", errorCount, warningCount); } foreach (CompilerError e in results.Errors) { Console.WriteLine(" - {0}: {1}: {2}: (line {3}, column {4}) {5}", e.IsWarning ? "Warning" : "Error", e.FileName, e.ErrorNumber, e.Line, e.Column, e.ErrorText); } } else { Console.Write("] "); } return(results); }
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; } }
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 Assembly BuildAssembly(string code) { Microsoft.CSharp.CSharpCodeProvider provider = new CSharpCodeProvider(); ICodeCompiler compiler = provider.CreateCompiler(); CompilerParameters compilerparams = new CompilerParameters(); compilerparams.GenerateExecutable = false; compilerparams.GenerateInMemory = true; //compilerparams.IncludeDebugInformation = true; compilerparams.ReferencedAssemblies.Add("System.dll"); compilerparams.ReferencedAssemblies.Add("System.Core.dll"); compilerparams.ReferencedAssemblies.Add("convexcad.exe"); CompilerResults results = compiler.CompileAssemblyFromFile(compilerparams, 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 System.ApplicationException(errors.ToString()); } else { return(results.CompiledAssembly); } }
// Eval > Evaluates C# sourcelanguage public object Eval(string code, Type outType = null, string[] includeNamespaces = null, string[] includeAssemblies = null) { StringBuilder namespaces = null; object methodResult = null; using (CSharpCodeProvider codeProvider = new CSharpCodeProvider()) { ICodeCompiler codeCompiler = codeProvider.CreateCompiler(); CompilerParameters compileParams = new CompilerParameters(); compileParams.CompilerOptions = "/t:library"; compileParams.GenerateInMemory = true; if (includeAssemblies != null && includeAssemblies.Any()) { foreach (string _assembly in includeAssemblies) { compileParams.ReferencedAssemblies.Add(_assembly); } } if (includeNamespaces != null && includeNamespaces.Any()) { foreach (string _namespace in includeNamespaces) { namespaces = new StringBuilder(); namespaces.Append(string.Format("using {0};\n", _namespace)); } } code = string.Format( @"{1} using System; namespace CSharpCode{{ public class Parser{{ public {2} Eval(){{ {3} {0}; }} }} }}", code, namespaces != null ? namespaces.ToString() : null, outType != null ? outType.FullName : "void", outType != null ? "return" : string.Empty ); CompilerResults compileResult = codeCompiler.CompileAssemblyFromSource(compileParams, code); if (compileResult.Errors.Count > 0) { //throw new Exception(compileResult.Errors[0].ErrorText); //RichTextBox inputBox = inputBox; setString(inputBox, "Syntax Error"); return(" "); } System.Reflection.Assembly assembly = compileResult.CompiledAssembly; object classInstance = assembly.CreateInstance("CSharpCode.Parser"); Type type = classInstance.GetType(); System.Reflection.MethodInfo methodInfo = type.GetMethod("Eval"); methodResult = methodInfo.Invoke(classInstance, null); } return(methodResult.ToString()); }
public override Type GetCompiledType () { Type type = CachingCompiler.GetTypeFromCache (parser.PhysicalPath); if (type != null) return type; if (parser.Program.Trim () == "") { type = parser.GetTypeFromBin (parser.ClassName); CachingCompiler.InsertType (type, parser.PhysicalPath); return type; } string lang = parser.Language; CompilationConfiguration config; config = CompilationConfiguration.GetInstance (parser.Context); provider = config.GetProvider (lang); if (provider == null) throw new HttpException ("Configuration error. Language not supported: " + lang, 500); compiler = provider.CreateCompiler (); compilerParameters = CachingCompiler.GetOptions (parser.Assemblies); compilerParameters.IncludeDebugInformation = parser.Debug; compilerParameters.CompilerOptions = config.GetCompilerOptions (lang); compilerParameters.WarningLevel = config.GetWarningLevel (lang); bool keepFiles = (Environment.GetEnvironmentVariable ("MONO_ASPNET_NODELETE") != null); TempFileCollection tempcoll; tempcoll = new TempFileCollection (config.TempDirectory, keepFiles); compilerParameters.TempFiles = tempcoll; if (!Directory.Exists (dynamicBase)) Directory.CreateDirectory (dynamicBase); inputFile = tempcoll.AddExtension (provider.FileExtension); Stream st = File.OpenWrite (inputFile); StreamWriter sw = new StreamWriter (st); sw.WriteLine (parser.Program); sw.Close (); string dllfilename = Path.GetFileName (tempcoll.AddExtension ("dll", true)); compilerParameters.OutputAssembly = Path.Combine (dynamicBase, dllfilename); CompilerResults results = CachingCompiler.Compile (this); CheckCompilerErrors (results); if (results.CompiledAssembly == null) throw new CompilationException (inputFile, results.Errors, "No assembly returned after compilation!?"); results.TempFiles.Delete (); type = results.CompiledAssembly.GetType (parser.ClassName, true); CachingCompiler.InsertType (type, parser.PhysicalPath); return type; }
static TestUtilities() { cSharpCompiler = new CSharpCodeProvider(); compiler = cSharpCompiler.CreateCompiler(); compileParameters = new CompilerParameters(); vbCompilerProvider = new VBCodeProvider(); vbCompiler = vbCompilerProvider.CreateCompiler(); vbCompileParameters = new CompilerParameters(); }
public WordScriptExecuter(string language, string codeText, List<string> namespaces) { Language = language; _namespaces = namespaces; _rootClassName = "AutomationKoboScript" + Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture); _codeText = codeText; _compilerInfo = CreateCompilerInfo(Language); _compiler = _compilerInfo.Compiler; _parameters = new CompilerParameters {GenerateExecutable = false, GenerateInMemory = true, MainClass = _rootClassName}; }
public HelixViewModel(ICodeCompiler codeCompiler) { DisplayName = "Helix"; _codeCompiler = codeCompiler; _scripts = new List<IDemoScript>(); CameraPosition = new Point3D(6, 5, 4); CameraFieldOfView = 45; LightPosition = new Point3D(0, 5, 0); RotationAngle = 0; }
/// <summary> /// Compiles a method from the provided source with the parameters specified. /// </summary> /// <param name="compiler"> /// The compiler to use for compiling the source to MSIL. /// </param> /// <param name="methodSource"> /// The actual source of the method. /// </param> /// <param name="methodName"> /// The name of the method. /// </param> /// <param name="options"> /// The parameters to be set for the compiler. /// </param> /// <param name="language"> /// A specification of the syntax of the language of the code /// </param> /// <returns> /// The resulting method and any warnings produced by the compiler, wrapped in a MethodResults object. /// </returns> /// <exception cref="CompilationException"/> public static MethodResults CreateMethod(ICodeCompiler compiler, string methodSource, string methodName, CompilerParameters options, Language language) { string containerName = String.Format("{0}Container", methodName); StringBuilder sourceBuilder = new StringBuilder(); sourceBuilder.Append(language.beginType(containerName)); sourceBuilder.Append(methodSource); sourceBuilder.Append(language.endType(containerName)); TypeResults compiledType = CreateType(compiler, sourceBuilder.ToString(), containerName, options, language); return compiledType.GetMethod(methodName); }
private static void CompileCode(ICodeCompiler itfCC, string syntaxTarget) { // Set assembly name. assemblyName = String.Format("Hello{0}Asm", syntaxTarget.ToUpper()); // Compile the code. CompilerParameters parms = new CompilerParameters(); parms.OutputAssembly = assemblyName + ".dll"; parms.CompilerOptions = "/t:library /r:System.Windows.Forms.dll"; itfCC.CompileAssemblyFromFile(parms, String.Format("Hello.{0}", syntaxTarget)); }
public SnippetCompiler() { this.provider = new CSharpCodeProvider(); this.compiler = this.provider.CreateCompiler(); this.parameters = new CompilerParameters(); this.parameters.GenerateInMemory = false; this.parameters.IncludeDebugInformation = true; this.parameters.ReferencedAssemblies.Add("System.dll"); this.parameters.OutputAssembly = String.Format("MbUnit.Tests.Snippet.{0}.dll", DateTime.Now.Ticks ); }
public TestCompiler( string[] assemblyNames, string outputName ) { Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider(); this.compiler = provider.CreateCompiler(); this.options = new CompilerParameters(); if ( assemblyNames != null && assemblyNames.Length > 0 ) options.ReferencedAssemblies.AddRange( assemblyNames ); if ( outputName != null ) options.OutputAssembly = outputName; options.IncludeDebugInformation = false; options.TempFiles = new TempFileCollection( ".", false ); options.GenerateInMemory = false; }
/* setup the compiler on construction to prevent the overhead of * having to do that for each call */ public CscriptProcessor() { CSharpCodeProvider provider = new CSharpCodeProvider(); _compiler = provider.CreateCompiler(); _parameters = new CompilerParameters(); /* this processor will only support the System namespace */ _parameters.ReferencedAssemblies.Add("system.dll"); /* don't compile this to the disk, just leave the assembly in memory */ _parameters.GenerateInMemory = true; /* build a library */ _parameters.CompilerOptions = "/t:library"; }
public CompilationException( ICodeCompiler compiler, CompilerParameters parameters, CompilerResults results, params String[] sources ) { StringWriter sw = new StringWriter(); sw.WriteLine("Compilation: {0} errors",results.Errors.Count); sw.WriteLine("Compiler: {0}",compiler.GetType().Name); sw.WriteLine("CompilerParameters: {0}",parameters.ToString()); foreach(CompilerError error in results.Errors) { sw.WriteLine(error.ToString()); } sw.WriteLine("Sources:"); foreach(string source in sources) sw.WriteLine(source); this.message =sw.ToString(); }
/// <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">Stream containing the source to compile</param> /// <param name="throwOnWarning"> /// true if assertion should throw if any warning. /// </param> public static void Compiles(ICodeCompiler compiler, CompilerParameters options, Stream source, bool throwOnWarning) { using (StreamReader sr = new StreamReader(source)) { Compiles(compiler, options, sr.ReadToEnd(), throwOnWarning); } }
/// <summary> /// Verifies that <paramref name="source"/> does not compile using the provided compiler. /// </summary> /// <param name="compiler"> /// <see cref="ICodeCompiler"/> instance.</param> /// <param name="source">Source to compile</param> public static void NotCompiles( ICodeCompiler compiler, Stream source) { CompilerParameters options = new CompilerParameters(); NotCompiles(compiler, options, 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 void Compiles(ICodeCompiler compiler, CompilerParameters options, string source, bool throwOnWarning) { Assert.IsNotNull(compiler); Assert.IsNotNull(options); CompilerResults results = compiler.CompileAssemblyFromSource(options, source); if (results.Errors.HasErrors) throw new CompilationException(compiler, options, results, source); if (throwOnWarning && results.Errors.HasWarnings) throw new CompilationException(compiler, 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">Stream containing the source to compile</param> public static void Compiles(ICodeCompiler compiler, CompilerParameters options, Stream source) { Compiles(compiler, options, source, false); }
/// <summary> /// Verifies that <paramref name="source"/> compiles using the provided compiler. /// </summary> /// <param name="compiler">Compiler instance</param> /// <param name="references">Referenced assemblies</param> /// <param name="source">Source code to compile</param> public static void Compiles(ICodeCompiler compiler, StringCollection references, string source) { Assert.IsNotNull(compiler); Assert.IsNotNull(references); Assert.IsNotNull(source); CompilerParameters ps = new CompilerParameters(); foreach (string ra in references) ps.ReferencedAssemblies.Add(ra); Compiles(compiler, ps, 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> public static void Compiles(ICodeCompiler compiler, CompilerParameters options, string source) { Assert.IsNotNull(compiler); Assert.IsNotNull(options); Assert.IsNotNull(source); Compiles(compiler, options, source, false); }
public Interpreter() { AddNamespace("System"); AddNamespace("System.Collections"); AddReference("system.dll"); SetValue("interpreter",this); SetValue("_",this); Utils.interpreter = this; AddReference(FullExecutablePath()); compiler = prov.CreateCompiler(); }
/// <summary> /// Compiles the code from the code string /// </summary> /// <param name="compiler"></param> /// <param name="parms"></param> /// <param name="source"></param> /// <returns></returns> private CompilerResults CompileCode(ICodeCompiler 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) WriteLine("Compile Error:" + error.ErrorText); return null; } return results; }
static void Main(string[] args) { // Prompt for target language. Console.Write("Do you want to generate C# or VB .NET code? "); syntaxTarget = Console.ReadLine(); // Get ICodeGenerator interface. switch(syntaxTarget.ToUpper()) { case "C#": case "CSharp": case "CS": syntaxTarget = "cs"; CSharpCodeProvider cdp = new CSharpCodeProvider(); itfCG = cdp.CreateGenerator(); itfCC = cdp.CreateCompiler(); break; case "VB .NET": case "VB.NET": case "VB": syntaxTarget = "vb"; VBCodeProvider vbdp = new VBCodeProvider(); itfCG = vbdp.CreateGenerator(); itfCC = vbdp.CreateCompiler(); break; default: Console.WriteLine("Sorry...can't do it..."); syntaxTarget = null; break; } // Only proceed if they picked a valid language // supported by System.CodeDOM. if(syntaxTarget != null) { // Now create the file and generate the code! TextWriter txtWriter = CreateFile(syntaxTarget); PopulateNamespace(itfCG, txtWriter); txtWriter.Close(); Console.WriteLine("Done!"); // Now compile the code into a .NET DLL. Console.WriteLine("Compiling code..."); CompileCode(itfCC, syntaxTarget); // Now launch the application! Console.Write("Enter your message: "); string msg = Console.ReadLine(); LoadAndRunAsm(msg); Console.WriteLine("Thanks for playing..."); } }
/// <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( ICodeCompiler compiler, CompilerParameters options, Stream source) { using (StreamReader sr = new StreamReader(source)) { NotCompiles(compiler, options, sr.ReadToEnd()); } }
/// <summary> /// Verifies that <paramref name="source"/> does not compile using the provided compiler. /// </summary> /// <param name="compiler"> /// <see cref="ICodeCompiler"/> instance.</param> /// <param name="referencedAssemblies">Collection of referenced assemblies</param> /// <param name="source">Source to compile</param> public static void NotCompiles( ICodeCompiler compiler, StringCollection referencedAssemblies, string source) { CompilerParameters options = new CompilerParameters(); CompilerParameters ps = new CompilerParameters(); foreach (string ra in referencedAssemblies) ps.ReferencedAssemblies.Add(ra); NotCompiles(compiler, options, source); }
public virtual Type GetCompiledType () { Type type = CachingCompiler.GetTypeFromCache (parser.InputFile); if (type != null) return type; ConstructType (); string lang = parser.Language; string tempdir; string compilerOptions; int warningLevel; Provider = CreateProvider (parser.Context, lang, out compilerOptions, out warningLevel, out tempdir); if (Provider == null) throw new HttpException ("Configuration error. Language not supported: " + lang, 500); #if !NET_2_0 compiler = provider.CreateCompiler (); #endif CompilerParameters parameters = CompilerParameters; parameters.IncludeDebugInformation = parser.Debug; parameters.CompilerOptions = compilerOptions + " " + parser.CompilerOptions; parameters.WarningLevel = warningLevel; bool keepFiles = (Environment.GetEnvironmentVariable ("MONO_ASPNET_NODELETE") != null); if (tempdir == null || tempdir == "") tempdir = DynamicDir (); TempFileCollection tempcoll = new TempFileCollection (tempdir, keepFiles); parameters.TempFiles = tempcoll; string dllfilename = Path.GetFileName (tempcoll.AddExtension ("dll", true)); parameters.OutputAssembly = Path.Combine (DynamicDir (), dllfilename); CompilerResults results = CachingCompiler.Compile (this); CheckCompilerErrors (results); Assembly assembly = results.CompiledAssembly; if (assembly == null) { if (!File.Exists (parameters.OutputAssembly)) { results.TempFiles.Delete (); throw new CompilationException (parser.InputFile, results.Errors, "No assembly returned after compilation!?"); } assembly = Assembly.LoadFrom (parameters.OutputAssembly); } results.TempFiles.Delete (); Type mainClassType = assembly.GetType (MainClassType, true); #if NET_2_0 if (parser.IsPartial) { // With the partial classes, we need to make sure we // don't have any methods that should have not been // created (because they are accessible from the base // types). We cannot do this normally because the // codebehind file is actually a partial class and we // have no way of identifying the partial class' base // type until now. if (!isRebuilding && CheckPartialBaseType (mainClassType)) { isRebuilding = true; parser.RootBuilder.ResetState (); return GetCompiledType (); } } #endif return mainClassType; }
CompilerResults CompileAssembly(ICodeCompiler compiler, CompilerParameters compilerParams, string[] filesToCompile) { //var sw = new Stopwatch(); //sw.Start(); CompilerResults retval = compiler.CompileAssemblyFromFileBatch(compilerParams, filesToCompile); //sw.Stop(); //Console.WriteLine(sw.ElapsedMilliseconds); if (!retval.Errors.HasErrors && options.postProcessor != "") { string rawAssembly = compilerParams.OutputAssembly + ".raw"; try { MethodInfo postProcessor = Assembly.LoadFrom(options.postProcessor) .GetType("CSSPostProcessor", true) .GetMethod("Process"); string[] refAsms = new string[compilerParams.ReferencedAssemblies.Count]; compilerParams.ReferencedAssemblies.CopyTo(refAsms, 0); postProcessor.Invoke(null, new object[] { compilerParams.OutputAssembly, refAsms, options.searchDirs }); } catch (Exception e) { throw new ApplicationException("Cannot post-process compiled script (set UsePostProcessor to \"null\" if the problem persist).\n" + e.Message); } } return retval; }
/// <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( ICodeCompiler compiler, CompilerParameters options, string source) { Assert.IncrementAssertCount(); if (compiler == null) throw new ArgumentNullException("compiler"); if (options == null) throw new ArgumentNullException("options"); CompilerResults results = compiler.CompileAssemblyFromSource(options, source); if (!results.Errors.HasErrors) throw new CompilationException(compiler, options, results, source); }
public TypedDataSetGeneratorTest () { CodeDomProvider p = new CSharpCodeProvider (); gen = p.CreateGenerator (); compiler = p.CreateCompiler (); }
//Returns "" if no errors, an error string if there are errors private CompilerResults CompileCode(ICodeCompiler compiler, CompilerParameters parms, string source) { //actually compile the code CompilerResults results = compiler.CompileAssemblyFromSource( parms, source); return results; }
/// <summary> /// Creates a new LuaEnvironment without initializing the state, /// for use with a derrived type. /// </summary> protected LuaEnvironmentNet() { this._compiler = new CodeCompiler(); this._parser = new PlainParser(); this._runtime = LuaRuntimeNet.Create(this); this.Settings = new LuaSettings().AsReadOnly(); this._globals = new LuaValues.LuaTable(); this._modules = new ModuleBinder(); }
public CompilerInfo(CodeDomProvider provider) { Compiler = provider.CreateCompiler(); CodeGen = provider.CreateGenerator(); }
/// <summary> /// Creates a new environment with the given settings. /// </summary> /// <param name="settings">The settings to give the Environment.</param> /// <exception cref="System.ArgumentNullException">If settings is null.</exception> public LuaEnvironmentNet(LuaSettings settings) { if (settings == null) throw new ArgumentNullException("settings"); this._globals = new LuaValues.LuaTable(); this._runtime = LuaRuntimeNet.Create(this); this._compiler = new CodeCompiler(); this._parser = new PlainParser(); this._modules = new ModuleBinder(); this.Settings = settings.AsReadOnly(); // initialize the global variables. LuaStaticLibraries.Initialize(this); InitializeTypes(); }