public void UpdateSource() { _codeType = null; _codeInstance = null; if (Source == null) return; var provider = new CSharpCodeProvider(); var options = new CompilerParameters { GenerateInMemory = true }; string qn = typeof(Point3D).Assembly.Location; options.ReferencedAssemblies.Add("System.dll"); options.ReferencedAssemblies.Add(qn); string src = template.Replace("#code#", Source); CompilerResults compilerResults = provider.CompileAssemblyFromSource(options, src); if (!compilerResults.Errors.HasErrors) { Errors = null; var assembly = compilerResults.CompiledAssembly; _codeInstance = assembly.CreateInstance("MyNamespace.MyEvaluator"); _codeType = _codeInstance.GetType(); } else { // correct line numbers Errors = compilerResults.Errors; for (int i = 0; i < Errors.Count; i++) Errors[i].Line -= 17; } _w = ParameterW; UpdateModel(); }
public static void OutputAssembly(Dictionary<string, string> generated, IEnumerable<string> assemblies, string assemblyPath) { var providerOptions = new Dictionary<string, string> {{"CompilerVersion", "v4.0"}}; using (var codeProvider = new CSharpCodeProvider(providerOptions)) { string[] sources = (from p in generated.Keys select generated[p]).ToArray(); List<string> assemblyPaths = new List<string>(assemblies); assemblyPaths.Add(typeof (ManifestEventAttribute).Assembly.Location); var compilerParameters = new CompilerParameters( assemblyPaths.ToArray(), assemblyPath, false); CompilerResults results = codeProvider.CompileAssemblyFromSource(compilerParameters, sources); if (results.Errors.Count == 0) return; var sb = new StringBuilder(); foreach (object o in results.Errors) { sb.AppendLine(o.ToString()); } string errors = sb.ToString(); throw new Exception(errors); } }
public static CompilerResults CompileFile(string input, string output, params string[] references) { CreateOutput(output); List<string> referencedAssemblies = new List<string>(references.Length + 3); referencedAssemblies.AddRange(references); referencedAssemblies.Add("System.dll"); referencedAssemblies.Add(typeof(IModule).Assembly.CodeBase.Replace(@"file:///", "")); referencedAssemblies.Add(typeof(ModuleAttribute).Assembly.CodeBase.Replace(@"file:///", "")); CSharpCodeProvider codeProvider = new CSharpCodeProvider(); CompilerParameters cp = new CompilerParameters(referencedAssemblies.ToArray(), output); using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(input)) { if (stream == null) { throw new ArgumentException("input"); } StreamReader reader = new StreamReader(stream); string source = reader.ReadToEnd(); CompilerResults results = codeProvider.CompileAssemblyFromSource(cp, source); ThrowIfCompilerError(results); return results; } }
private static object ExecuteScript(string script, ScriptExecutionOptions options) { object result = null; CompilerParameters cpar = new CompilerParameters(); cpar.GenerateInMemory = true; cpar.ReferencedAssemblies.Add("mscorlib.dll"); cpar.ReferencedAssemblies.Add("System.dll"); cpar.ReferencedAssemblies.Add("System.Core.dll"); cpar.ReferencedAssemblies.Add("System.Data.dll"); cpar.ReferencedAssemblies.Add("System.Xml.dll"); cpar.ReferencedAssemblies.Add(typeof(CSharpScriptingProvider).Assembly.Location); string code = Properties.Resources.ScriptProviderCSharpTemplate; code = code.Replace("{Source}", script); CSharpCodeProvider csp = new CSharpCodeProvider(); CompilerResults res = csp.CompileAssemblyFromSource(cpar, code); if (!res.Errors.HasErrors) { MethodInfo func = res.CompiledAssembly.ExportedTypes.First().GetMethods().First(); result = func.Invoke(null, new object[] { options }); } return result; }
public bool Compile(string src) { var param = new CompilerParameters(new string[] { "System.dll", "mscorlib.dll", "System.Data.dll", "System.Xml.dll", "System.Xml.Linq.dll", "lib.dll", "compiler.dll", }); param.GenerateInMemory = true; param.GenerateExecutable = false; param.IncludeDebugInformation = false; _provider = new CSharpCodeProvider( new Dictionary<string, string>() { { "CompilerVersion", "v4.0" }, }); _results = _provider.CompileAssemblyFromSource(param, src); if (_results.Errors.Count > 0) { foreach (CompilerError err in _results.Errors) { if (err.IsWarning) Console.WriteLine("[Warning] {0}: [{1}] {2}", err.Line, err.ErrorNumber, err.ErrorText); else Console.WriteLine("[Error] {0}: [{1}] {2}", err.Line, err.ErrorNumber, err.ErrorText); } return false; } return true; }
public static Type Compile(string name, string queryText) { var provider = new CSharpCodeProvider(new Dictionary<string, string> {{"CompilerVersion", "v4.0"}}); var results = provider.CompileAssemblyFromSource(new CompilerParameters { GenerateExecutable = false, GenerateInMemory = false, IncludeDebugInformation = true, ReferencedAssemblies = { typeof (AbstractViewGenerator).Assembly.Location, typeof (NameValueCollection).Assembly.Location, typeof (Enumerable).Assembly.Location, typeof (Binder).Assembly.Location, }, }, queryText); if (results.Errors.HasErrors) { var sb = new StringBuilder() .AppendLine("Source code:") .AppendLine(queryText) .AppendLine(); foreach (CompilerError error in results.Errors) { sb.AppendLine(error.ToString()); } throw new InvalidOperationException(sb.ToString()); } return results.CompiledAssembly.GetType(name); }
public void When_attemting_to_register_component_descended_from_valuetype_should_not_compile() { var csharpCode = @" using System; using Castle.MicroKernel; using Castle.MicroKernel.Registration; public class ShouldNotCompile { public void MethodContainsInvalidCode() { DefaultKernel kernel = new DefaultKernel(); kernel.Register(Component.For<Int32>().Instance(1)); } } "; var compiler = new CSharpCodeProvider(); var coreAssembly = AppDomain.CurrentDomain.GetAssemblies().Single(a => a.GetName().Name == "Castle.Core").Location; var windsorAssembly = typeof(DefaultKernel).Assembly.Location; var results = compiler.CompileAssemblyFromSource(new CompilerParameters(new[] { coreAssembly, windsorAssembly }), csharpCode); Assert.True(results.Errors.HasErrors); Assert.AreEqual("CS0452", results.Errors[0].ErrorNumber, results.Errors[0].ToString()); // The type 'int' must be a reference type in order to use it as parameter 'S' in the generic type or method 'Castle.MicroKernel.Registration.Component.For<S>()' }
public void BuildExe(string exe, string code, bool showConsole = true) { if (File.Exists("./Build/ECLang.dll")) { File.Delete("./Build/ECLang.dll"); } File.Copy("ECLang.dll", "./Build/ECLang.dll"); File.WriteAllText("./Build/Src/Main.ec", code); var codeProvider = new CSharpCodeProvider(); var parameters = new CompilerParameters(); parameters.GenerateExecutable = true; parameters.OutputAssembly = "./Build/" + exe; parameters.ReferencedAssemblies.Add("./ECLang.dll"); parameters.EmbeddedResources.Add("./ECLang.dll"); parameters.EmbeddedResources.Add("./Build/Src/Main.ec"); string Bootstrap = Resources.BootStrapCode; if (!showConsole) { Bootstrap = Bootstrap.Replace("/*HideConsoleReplacePoint*/", "ShowWindow(handle, SW_HIDE);"); } CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, Bootstrap); this.Execute("./Build/" + exe); var dlg = new SaveFileDialog(); dlg.Filter = "Exe file|*.exe"; if (dlg.ShowDialog() == DialogResult.OK) { if (File.Exists(dlg.FileName)) { File.Delete(dlg.FileName); } File.Copy("./Build/" + exe, dlg.FileName); } }
static AssemblyDefinition Compile(string code) { CSharpCodeProvider provider = new CSharpCodeProvider(new Dictionary<string, string> { { "CompilerVersion", "v4.0" } }); CompilerParameters options = new CompilerParameters(); options.ReferencedAssemblies.Add("System.Core.dll"); CompilerResults results = provider.CompileAssemblyFromSource(options, code); try { if (results.Errors.Count > 0) { StringBuilder b = new StringBuilder("Compiler error:"); foreach (var error in results.Errors) { b.AppendLine(error.ToString()); } throw new Exception(b.ToString()); } return AssemblyDefinition.ReadAssembly(results.PathToAssembly); } finally { File.Delete(results.PathToAssembly); results.TempFiles.Delete(); } }
protected static AssemblyDef CompileLegacy(string code, bool optimize, bool useDebug, int compilerVersion) { CSharpCodeProvider provider = new CSharpCodeProvider(new Dictionary<string, string> { { "CompilerVersion", "v" + new Version(compilerVersion, 0) } }); CompilerParameters options = new CompilerParameters(); options.CompilerOptions = "/unsafe /o" + (optimize ? "+" : "-") + (useDebug ? " /debug" : ""); if (compilerVersion >= 4) options.ReferencedAssemblies.Add("System.Core.dll"); CompilerResults results = provider.CompileAssemblyFromSource(options, code); try { if (results.Errors.Count > 0) { StringBuilder b = new StringBuilder("Compiler error:"); foreach (var error in results.Errors) { b.AppendLine(error.ToString()); } throw new Exception(b.ToString()); } return Utils.OpenAssembly(results.PathToAssembly); } finally { File.Delete(results.PathToAssembly); results.TempFiles.Delete(); } }
public string CreateExe(string exeName, string sourceString) { Directory.CreateDirectory(this.ExeDirectory); var outputExePath = this.ExeDirectory + exeName; if (File.Exists(outputExePath)) { File.Delete(outputExePath); } var codeProvider = new CSharpCodeProvider(); var parameters = new CompilerParameters { GenerateExecutable = true, OutputAssembly = outputExePath, }; parameters.ReferencedAssemblies.Add("System.dll"); parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll"); CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, sourceString); foreach (var error in results.Errors) { Console.WriteLine(error.ToString()); } Assert.IsFalse(results.Errors.HasErrors, "Code compilation contains errors!"); return outputExePath; }
static void CompileAndRun(string code) { var csc = new CSharpCodeProvider(); var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "teste.exe", true) { GenerateExecutable = true }; CompilerResults compiledAssembly = csc.CompileAssemblyFromSource(parameters, code); var errors = compiledAssembly.Errors .Cast<CompilerError>() .ToList(); if (errors.Any()) { errors.ForEach(Console.WriteLine); return; } Module module = compiledAssembly.CompiledAssembly.GetModules()[0]; Type mt = null; if (module != null) mt = module.GetType("Program"); MethodInfo methInfo = null; if (mt != null) methInfo = mt.GetMethod("Main"); if (methInfo != null) Console.WriteLine(methInfo.Invoke(null, null)); }
public static ICalc GetCalc(string csCode) { ICalc obj = null; #if !NETCOREAPP3_0 && !NETSTANDARD2_0 && !NETSTANDARD2_1 using (Microsoft.CSharp.CSharpCodeProvider csProvider = new Microsoft.CSharp.CSharpCodeProvider()) { var prm = new System.CodeDom.Compiler.CompilerParameters(); prm.GenerateInMemory = true; prm.GenerateExecutable = false; #if NET451 || NET471 prm.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location); #endif counter++; // Implement the interface in the dynamic code var res = csProvider.CompileAssemblyFromSource(prm, String.Format(@"public class CompiledCalc{0} : ICalc { public Exception LastError { get; set; } public object Calc() { {1} }}", counter, csCode)); var type = res.CompiledAssembly.GetType(string.Format("CompiledCalc{0}", counter)); try { obj = Activator.CreateInstance(type) as ICalc; } catch (Exception ex) { obj = obj ?? new CalcEmpty(); obj.LastError = ex; } } #endif return(obj); }
private static void Run(string csFilename, IEnumerable<string> args) { var compilerParameters = new CompilerParameters { GenerateExecutable = false, GenerateInMemory = true }; var referencedAssemblies = new[] {"System.dll", "System.Core.dll", "System.Data.dll"}; foreach (var assembly in referencedAssemblies) { compilerParameters.ReferencedAssemblies.Add(assembly); } compilerParameters.IncludeDebugInformation = true; var cSharpCodeProvider = new CSharpCodeProvider(); var code = File.ReadAllText(csFilename); foreach(Match m in RxRef.Matches(code)) { compilerParameters.ReferencedAssemblies.Add(m.Groups[1].Value); } var result = cSharpCodeProvider.CompileAssemblyFromSource(compilerParameters, code); if (result.Errors.Count != 0) { foreach (var error in result.Errors) { Console.WriteLine(error); } return; } result.CompiledAssembly.GetType("CsRun.Program").GetMethod("Main").Invoke(null, new object[] {args.ToArray()}); }
/// <summary> /// Compiles the source to assembly. /// </summary> /// <param name="script">The SharpScript.</param> /// <returns>Assembly.</returns> public static Assembly CompileToAssembly(CSharpScript script) { var cdProvider = new CSharpCodeProvider(); var param = new CompilerParameters(); param.ReferencedAssemblies.Add("System.dll"); param.ReferencedAssemblies.Add("Sharpex2D.dll"); param.ReferencedAssemblies.Add(Application.ExecutablePath); param.GenerateExecutable = false; CompilerResults result = cdProvider.CompileAssemblyFromSource(param, script.Content); bool flag = false; foreach (CompilerError error in result.Errors) { if (error.IsWarning) { Logger.Warn("{0} -> {1} (Line {2})", script.Guid, error.ErrorText, error.Line); } else { Logger.Critical("{0} -> {1} (Line {2})", script.Guid, error.ErrorText, error.Line); flag = true; } } if (flag) { throw new ScriptException("Critical error while compiling script."); } return result.CompiledAssembly; }
private void CreateEvaluator() { string Code = "using System; public class Evaluator { public static double Evaluate (double x) { return " + this.Expression + "; } }"; CompilerParameters Parameters = new CompilerParameters(); Parameters.GenerateExecutable = false; Parameters.TreatWarningsAsErrors = true; Parameters.TempFiles.KeepFiles = false; Parameters.GenerateInMemory = true; Parameters.ReferencedAssemblies.Add("System.dll"); CSharpCodeProvider Provider = new CSharpCodeProvider(); CompilerResults CompResults = Provider.CompileAssemblyFromSource(Parameters, Code); if (CompResults.Errors.Count > 0) { throw new FormatException("Espressione non valida!"); } else { System.Reflection.Assembly Asm = CompResults.CompiledAssembly; this.EvaluateFunction = Asm.GetType("Evaluator").GetMethod("Evaluate"); } }
//Method has to be static //Method name has to be "MyMethod" and Type name has to be "MyProgram" and Namespace name has to be "MyNamespace" public static Eval CreateEval(string sCSCode, bool print, string desc) { CSharpCodeProvider ccc = new CSharpCodeProvider(); CompilerParameters cp = new CompilerParameters(); cp.ReferencedAssemblies.Add("System.dll"); cp.ReferencedAssemblies.Add("SlackBot.exe"); cp.ReferencedAssemblies.Add("SlackAPI.dll"); cp.ReferencedAssemblies.Add("System.Data.dll"); cp.GenerateExecutable = false; cp.GenerateInMemory = false; String name = ((String) General.sc.caller.CallAPIString("http://randomword.setgetgo.com/get.php", new Dictionary<string, dynamic>()).Result).Trim(); cp.OutputAssembly = Helper.GetApplicationPath() + "/" + name + ".dll"; String finalcode = "using System; \nusing SlackBot; \nusing SlackAPI; \nusing System.Data;\nnamespace MyNamespace { \npublic class MyProgram { \npublic static String MyMethod(String text){\n " + sCSCode + "\n } \n } \n }"; CompilerResults cr = ccc.CompileAssemblyFromSource(cp, finalcode); if (cr.Errors.HasErrors) { StringBuilder sb = new StringBuilder(); foreach (CompilerError error in cr.Errors) { sb.AppendLine(String.Format("Error ({0}): {1} : {2} : {3}", error.ErrorNumber, error.ErrorText, error.Line, error.Column)); } throw new InvalidOperationException(sb.ToString()); } String path = (((cr.CompiledAssembly.Location.Replace("file:///", "")).Replace("\\", "/")).Trim()); return new Eval(print, path, desc); }
public IEnumerable<string> Build(string path,string output_path,string provider_name, string[] namesapces) { byte[] sourceDll = System.IO.File.ReadAllBytes(path); Assembly assembly = Assembly.Load(sourceDll); var types = assembly.GetExportedTypes(); var codes = Build(provider_name, namesapces, types); Dictionary<string, string> optionsDic = new Dictionary<string, string> { {"CompilerVersion", "v3.5"} }; var provider = new CSharpCodeProvider(optionsDic); var options = new CompilerParameters { OutputAssembly = output_path, GenerateExecutable = false, ReferencedAssemblies = { "System.Core.dll", "RegulusLibrary.dll", "RegulusRemoting.dll", "protobuf-net.dll", path, } }; var result = provider.CompileAssemblyFromSource(options, codes.ToArray()); return codes; }
public CompilerResults Compile() { string executable = Application.ExecutablePath; string baseDir = Path.GetDirectoryName(executable); CodeDomProvider compiler = new CSharpCodeProvider(options.CompilerOptions); CompilerParameters parameters = new CompilerParameters(); parameters.WarningLevel = 4; parameters.GenerateExecutable = false; parameters.GenerateInMemory = true; foreach (string assembly in options.Assemblies) { string suffix = assembly.EndsWith(".exe") ? "" : ".dll"; string prefix = ""; if (!assembly.StartsWith("System") && !assembly.StartsWith("Microsoft") && assembly != "WindowsBase") { prefix = baseDir + "\\"; } // This is a really grotty hack, but appears to work if (assembly == "WindowsBase") { string refDir = @"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\"; if (!Directory.Exists(refDir)) { refDir = refDir.Replace(" (x86)", ""); } prefix = refDir; } parameters.ReferencedAssemblies.Add(prefix + assembly + suffix); } return compiler.CompileAssemblyFromSource(parameters, GenerateCode(true)); }
/// <summary> /// 根据代码获取一个Assembly /// </summary> /// <param name="Code">代码区域 包含USING</param> /// <param name="UsingList">需要引用的DLL</param> /// <returns>返回Assembly</returns> public static Assembly GetCodeAssembly(string p_Code, IList<string> p_UsingList) { CodeDomProvider _CodeDom = new CSharpCodeProvider(); CompilerParameters _CodeParamertes = new CompilerParameters(); for (int i = 0; i != p_UsingList.Count; i++) { _CodeParamertes.ReferencedAssemblies.Add(p_UsingList[i].ToString()); //("System.dll"); } _CodeParamertes.GenerateExecutable = false; _CodeParamertes.GenerateInMemory = true; CompilerResults _CompilerResults = _CodeDom.CompileAssemblyFromSource(_CodeParamertes, p_Code); if (_CompilerResults.Errors.HasErrors) { string _ErrorText = ""; foreach (CompilerError _Error in _CompilerResults.Errors) { _ErrorText += _Error.ErrorText + "/r/n"; } throw new Exception(_ErrorText); } else { return _CompilerResults.CompiledAssembly; } }
/// <summary> /// 执行一段 C# 代码并返回结果。 /// </summary> /// <param name="codeBody">方法体。</param> /// <param name="parameters">参数(名称,值)。</param> /// <returns>方法的返回值。</returns> public static object RunCode(string codeBody, Dictionary<string, object> parameters) { using (CSharpCodeProvider provider = new CSharpCodeProvider()) { CompilerParameters parameter = new CompilerParameters(); parameter.GenerateExecutable = false; parameter.GenerateInMemory = true; StringBuilder sb = new StringBuilder(); // 生成方法参数代码。 List<object> methodParameters = new List<object>(); // 调用方法时的参数对象列表。 for (int i = 0; i < parameters.Count; i++) { var temp = parameters.ElementAt(i); sb.Append(temp.Value.GetType().FullName + " " + temp.Key); methodParameters.Add(temp.Value); if (i != parameters.Count - 1) { sb.Append(","); } } string source = @"using System;namespace NameSpace{public class Class{public static object Method(" + sb.ToString() + @"){" + codeBody + @"}}}"; // 最终代码段。 CompilerResults result = provider.CompileAssemblyFromSource(parameter, source); // 编译代码。 if (result.Errors.Count > 0) { throw new Exception("代码错误"); } else { Assembly assembly = result.CompiledAssembly; // 获得编译成功的程序集。 Type type = assembly.GetType("NameSpace.Class"); return type.GetMethod("Method").Invoke(null, methodParameters.ToArray()); // 执行方法。 } } }
public CompilerResults Compile(string generatedCodeFileName = null) { var options = new Dictionary<string, string> { {"CompilerVersion", "v3.5"} }; var codeProvider = new CSharpCodeProvider(options); var scanner = new Scanner(this.fileName); var parser = new Parser(scanner); parser.Parse(); var generatator = new Generator(); var generatedCode = generatator.Generate(null, parser.ruleClassStatement, ""); if (generatedCodeFileName != null) { using (var stream = new StreamWriter(generatedCodeFileName, false, Encoding.UTF8)) { stream.Write(generatedCode); } } return codeProvider.CompileAssemblyFromSource(this._compilerParams, generatedCode.ToString()); }
/// <summary> /// Compiles a C# script as if it were a file in your project. /// </summary> /// <param name="scriptText">The text of the script.</param> /// <param name="errors">The compiler errors and warnings from compilation.</param> /// <param name="assemblyIfSucceeded">The compiled assembly if compilation succeeded.</param> /// <returns>True if compilation was a success, false otherwise.</returns> public static bool CompileCSharpScript(string scriptText, out CompilerErrorCollection errors, out Assembly assemblyIfSucceeded) { var codeProvider = new CSharpCodeProvider(); var compilerOptions = new CompilerParameters(); // We want a DLL and we want it in memory compilerOptions.GenerateExecutable = false; compilerOptions.GenerateInMemory = true; // Add references for UnityEngine and UnityEditor DLLs compilerOptions.ReferencedAssemblies.Add(typeof(Vector2).Assembly.Location); compilerOptions.ReferencedAssemblies.Add(typeof(EditorApplication).Assembly.Location); // Default to null output parameters errors = null; assemblyIfSucceeded = null; // Compile the assembly from the source script text CompilerResults result = codeProvider.CompileAssemblyFromSource(compilerOptions, scriptText); // Store the errors for the caller. even on successful compilation, we may have warnings. errors = result.Errors; // See if any errors are actually errors. if so return false foreach (CompilerError e in errors) { if (!e.IsWarning) { return false; } } // Otherwise we pass back the compiled assembly and return true assemblyIfSucceeded = result.CompiledAssembly; return true; }
public static void RunTransformations(string userCode) { using (var codeProvider = new CSharpCodeProvider()) { string code = @"using Aitako.DSL;using System; using Aitako.DSL.Components;using System.Collections.Generic; public class Runner { public void Execute() { " + userCode + " Service.Execute();}}"; CompilerResults compilerResult = codeProvider.CompileAssemblyFromSource( new CompilerParameters(new[] {"Aitako.DSL.dll"}) {GenerateInMemory = true}, code); if (compilerResult.Errors.Count > 0) { foreach (object error in compilerResult.Errors) { Console.WriteLine(error.ToString()); } return; } Type compiledType = compilerResult.CompiledAssembly.GetType("Runner"); object instance = Activator.CreateInstance(compiledType); object output = compiledType.GetMethod("Execute").Invoke(instance, new object[] {}); Console.WriteLine(output); } }
public static IPlayer MakeFrom( string text ) { CSharpCodeProvider csc = new CSharpCodeProvider(); string[] refs = new[] { "mscorlib.dll", "System.Drawing.dll", "ModelPreviewer.exe", "OpenTK.dll" }; CompilerParameters prms = new CompilerParameters( refs, "model.dll", true ); prms.GenerateInMemory = true; CompilerResults results = csc.CompileAssemblyFromSource( prms, text ); using( StreamWriter writer = new StreamWriter( "error.txt", false ) ) { StringBuilder builder = new StringBuilder(); foreach( CompilerError error in results.Errors ) { writer.WriteLine( "=== errror" ); writer.WriteLine( "line {0}: {1} ({2})", error.Line, error.ErrorText, error.ErrorNumber ); builder.AppendFormat( "line {0}: {1} ({2})", error.Line, error.ErrorText, error.ErrorNumber ); } if( results.Errors.Count > 0 ) { MessageBox.Show( builder.ToString(), "Model error" ); return null; } } foreach( var type in results.CompiledAssembly.GetTypes() ) { if( type.IsSubclassOf( typeof( IPlayer ) ) ) { try { return (IPlayer)Activator.CreateInstance( type ); } catch( Exception ex ) { MessageBox.Show( ex.ToString(), "Model error" ); } } } return null; }
/// <summary> /// Compiles the srcipt and returns an evaluator (a delegate) /// which takes in time and returns audioFrame values /// </summary> /// <returns>A delegate of type Func<double,double></returns> public Func<double, double> Compile() { var codeProvider = new CSharpCodeProvider(); var compilerResults = codeProvider.CompileAssemblyFromSource( new CompilerParameters(new[] {"TuneItDynamicBase.dll"}) {GenerateInMemory = true}, @" using System; using TuneItDynamicBase; public class DynamicCompiledScript : DynamicCompiledScriptBase { public override Func<double, double> Evaluator { get { return delegate(double time) {" + script + @" }; } } } "); if (compilerResults.Errors.HasErrors) { return null; } var dynamicScriptInstance = (IDynamicScript) compilerResults.CompiledAssembly.CreateInstance("DynamicCompiledScript"); if (dynamicScriptInstance == null) { return null; } return dynamicScriptInstance.Evaluator; }
public static void BuildAssembly(string code, AssemblyName name) { // Use the CSharpCodeProvider to compile the generated code: CompilerResults results; var path = Path.GetDirectoryName(typeof(VfpDynamicDataContextDriver).Assembly.Location); var references = new[] { "System.dll", "System.Data.dll", "System.Core.dll", Path.Combine(path, "IQToolkit.dll"), Path.Combine(path, "IQToolkit.Data.dll"), Path.Combine(path, "IQToolkitContrib.dll"), Path.Combine(path, "LINQtoVFP.dll"), Path.Combine(path, "VfpClient3.5.dll") }; using (var codeProvider = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } })) { var options = new CompilerParameters(references, name.CodeBase, true); results = codeProvider.CompileAssemblyFromSource(options, code); } if (results.Errors.Count > 0) { throw new Exception("Cannot compile typed context: " + results.Errors[0].ErrorText + " (line " + results.Errors[0].Line + ")"); } }
public static void compileSource() { //UNDER CONSTRUCTION string source = @" namespace Foo { public class Bar { public void SayHello() { System.Console.WriteLine(""Hello World""); } } } "; Dictionary<string, string> providerOptions = new Dictionary<string, string> { {"CompilerVersion", "v4" } }; CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions); CompilerParameters compilerParams = new CompilerParameters {GenerateInMemory = true, GenerateExecutable = false}; CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source); if (results.Errors.Count != 0) throw new Exception("Mission Failed"); object o = results.CompiledAssembly.CreateInstance("Foo.Bar"); MethodInfo mi = o.GetType().GetMethod("SayHello"); mi.Invoke(o, null); }
private static Assembly CompileWithReferences(string sourcecode,CompileLanguage language, string[] references) { CodeDomProvider comp =null; switch (language ){ case CompileLanguage.VisualBasic: comp = new Microsoft.VisualBasic.VBCodeProvider(); break; case CompileLanguage.CSharp: default: comp = new CSharpCodeProvider(); break; } CompilerParameters cp = new CompilerParameters(); foreach (string reference in references) { cp.ReferencedAssemblies.Add(reference); } cp.GenerateInMemory = true; CompilerResults cr = comp.CompileAssemblyFromSource(cp, sourcecode); if (cr.Errors.HasErrors) { string error = string.Empty; foreach (CompilerError err in cr.Errors) { error += err.ErrorText + System.Environment.NewLine; } System.Diagnostics.Trace.WriteLine(error); return null; } return cr.CompiledAssembly; }
public static void CompileAssembly(string[] code) { CompilerParameters compilerParams = new CompilerParameters(); string outputDirectory = Directory.GetCurrentDirectory(); compilerParams.GenerateInMemory = true; compilerParams.TreatWarningsAsErrors = false; compilerParams.GenerateExecutable = false; compilerParams.CompilerOptions = "/optimize"; compilerParams.OutputAssembly = "DynamicLibrary.dll"; string[] references = { "System.dll" }; compilerParams.ReferencedAssemblies.AddRange(references); //Console.WriteLine("Compile assembly from source..."); CSharpCodeProvider provider = new CSharpCodeProvider(); CompilerResults compile = provider.CompileAssemblyFromSource(compilerParams, code); if (compile.Errors.HasErrors) { string text = "Compile error: "; foreach (CompilerError ce in compile.Errors) text += "rn" + ce.ToString(); throw new Exception(text); } CompiledAssembly = compile.CompiledAssembly; }
public static TDelegate BuildFold7 <TDelegate>(string funcSource, string name) where TDelegate : class { var compiler = new Microsoft.CSharp.CSharpCodeProvider(); var parms = new System.CodeDom.Compiler.CompilerParameters { GenerateExecutable = false, GenerateInMemory = true }; parms.ReferencedAssemblies.Add("System.dll"); var result = compiler.CompileAssemblyFromSource(parms, new[] { string.Format( @" using System; public class MyClass {{ {0} }} ", funcSource), }); if (result.Errors.Count > 0) { throw new Exception(string.Join("\n", result.Errors)); } return(result.CompiledAssembly.GetType("MyClass").GetMethod(name).CreateDelegate(typeof(TDelegate)) as TDelegate); }
static Assembly CompileSettings(string inputFilePath) { string fileName = Path.GetFileNameWithoutExtension(inputFilePath); string code = File.ReadAllText(inputFilePath); code = "using SettingsCompiler;\r\n\r\n" + "namespace " + fileName + "\r\n{\r\n" + code; code += "\r\n}"; Dictionary<string, string> compilerOpts = new Dictionary<string, string> { { "CompilerVersion", "v4.0" } }; CSharpCodeProvider compiler = new CSharpCodeProvider(compilerOpts); string[] sources = { code }; CompilerParameters compilerParams = new CompilerParameters(); compilerParams.GenerateInMemory = true; compilerParams.ReferencedAssemblies.Add("System.dll"); compilerParams.ReferencedAssemblies.Add("SettingsCompilerAttributes.dll"); CompilerResults results = compiler.CompileAssemblyFromSource(compilerParams, sources); if(results.Errors.HasErrors) { string errMsg = "Errors were returned from the C# compiler:\r\n\r\n"; foreach(CompilerError compilerError in results.Errors) { int lineNum = compilerError.Line - 4; errMsg += inputFilePath + "(" + lineNum + "): " + compilerError.ErrorText + "\r\n"; } throw new Exception(errMsg); } return results.CompiledAssembly; }
/// <summary> /// Executes the processed code from Process() function. /// </summary> /// <param name="errors">If execution was not successful, returns CompilerErrorCollection or Exception</param> /// <returns>Values to put in each code segment (output) or null if there were errors</returns> public string[] Execute(out object errors) { errors = null; segmentsOutput = new string[segmentNum]; for (int i = 0; i < segmentNum; i++) { segmentsOutput[i] = ""; } segmentNum = -1; CSHARP.CSharpCodeProvider provider = new CSHARP.CSharpCodeProvider(); CompilerParameters parms = new CompilerParameters(); parms.GenerateInMemory = true; parms.TreatWarningsAsErrors = false; parms.TempFiles = new TempFileCollection(Environment.GetEnvironmentVariable("TEMP"), true); parms.IncludeDebugInformation = true; parms.ReferencedAssemblies.Add(Assembly.GetEntryAssembly().Location); try { string[] assms = File.ReadAllText(ConfigurationManager.SETTINGS["ASSEMBLIES"]).Split(new char[] { '\n' }); for (int i = 0; i < assms.Length; i++) { parms.ReferencedAssemblies.Add(assms[i].Trim()); } } catch { } CompilerResults res = provider.CompileAssemblyFromSource(parms, FinalCode); if (res.Errors.HasErrors) // Handling compiler errors { errors = res.Errors; return(null); } Assembly ass = res.CompiledAssembly; Type prog = ass.GetType("LWASP_Console.WebApp"); MethodInfo main = prog.GetMethod("Rain"); try { main.Invoke(null, new object[] { connection, connection.queryString, connection.formData, connection.PostData() }); } catch (Exception exx) { errors = exx != null ? exx.InnerException ?? exx : new Exception("LWASP Error"); return(null); } return(segmentsOutput); }
/// <summary> /// Compile the sharp code in SourceString and link it with the assemblies /// provided in the parameter LinkedAssemblies /// </summary> /// <param name="SourceString">the code to compile as string</param> /// <param name="LinkedAssemblies">assemblies to link with separated by semi-column ';'</param> /// <returns>true if success, else false and you can call GetLastError</returns> public bool Compile(string SourceString, string LinkedAssemblies) { CodeDomProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider(); System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters(); parameters.GenerateInMemory = true; parameters.GenerateExecutable = false; // add the linked assemblies foreach (string assembly in LinkedAssemblies.Split(';')) { parameters.ReferencedAssemblies.Add(assembly); } // compile CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, SourceString); //if errors if (results.Errors.Count > 0) { _ErrorMsg = new StringBuilder(); // append all errors foreach (CompilerError CompErr in results.Errors) { _ErrorMsg.AppendFormat("Line: {0} , Code: {1}, Msg: {2}", CompErr.Line, CompErr.ErrorNumber, CompErr.ErrorText); Tracer.Error("CSharpCodeCompiler", "Line: {0} , Code: {1}, Msg {2}", CompErr.Line, CompErr.ErrorNumber, CompErr.ErrorText); //EventManager.Instance.SendMessage(SourceString); } } if (results.Errors.Count == 0 && results.CompiledAssembly != null) { _assembly = results.CompiledAssembly; return(true); } else { return(false); } }
private Type CreateType(string className, string codeFragment, string statement) { CompilerParameters compilerParameters = CreateCompilerParameters(); statement = String.Format("{0}{2}{1}", BuildNameSpaces(), statement, Environment.NewLine); CodeDomProvider codeDomProvider = null; switch (_language) { case ChoCodeProviderLanguage.VB: codeDomProvider = new Microsoft.VisualBasic.VBCodeProvider(); break; default: codeDomProvider = new Microsoft.CSharp.CSharpCodeProvider(); break; } using (codeDomProvider) { var res = codeDomProvider.CompileAssemblyFromSource(compilerParameters, statement); if (res.Errors.Count > 0) { StringBuilder errors = new StringBuilder(); foreach (CompilerError CompErr in res.Errors) { errors.AppendFormat("Line number {0}, Error Number: {1}, {2}{3}", CompErr.Line, CompErr.ErrorNumber, CompErr.ErrorText, Environment.NewLine); } throw new ApplicationException("Exception compiling code fragment: {1}{1}{0}{1}{1}Exceptions:{1}{2}".FormatString( codeFragment.Indent(1), Environment.NewLine, errors.ToString().Indent(1))); } return(res.CompiledAssembly.GetType(className)); } }
private static Assembly CompileStrings( string[] src, string[] referenceAssemblies, bool toAssembly, string outputAssemblyPath, out string errors ) { var cpar = new System.CodeDom.Compiler.CompilerParameters() { GenerateInMemory = !toAssembly, OutputAssembly = outputAssemblyPath, }; // Add default references... cpar.ReferencedAssemblies.Add(typeof(System.Activities.Activity).Assembly.Location); cpar.ReferencedAssemblies.Add(typeof(System.CodeDom.Compiler.CodeCompiler).Assembly.Location); cpar.ReferencedAssemblies.Add(typeof(PSObject).Assembly.Location); cpar.ReferencedAssemblies.Add(typeof(Microsoft.PowerShell.Activities.PSActivity).Assembly.Location); cpar.ReferencedAssemblies.Add(ResolveReferencedAssembly("Microsoft.Management.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")); cpar.ReferencedAssemblies.Add(ResolveReferencedAssembly("Microsoft.PowerShell.Commands.Management, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")); // Add user supplied references... if (referenceAssemblies != null) { foreach (string asm in referenceAssemblies) { cpar.ReferencedAssemblies.Add(ResolveReferencedAssembly(asm)); } } var compiler = new Microsoft.CSharp.CSharpCodeProvider(); var cr = compiler.CompileAssemblyFromSource(cpar, src); if (cr.Errors == null || cr.Errors.Count == 0) { errors = string.Empty; } else { StringBuilder errorBuilder = new StringBuilder(); foreach (var err in cr.Errors) { errorBuilder.Append(err.ToString()); errorBuilder.Append('\n'); } errors = errorBuilder.ToString(); } if (errors.Length > 0) { return(null); } // If the assembly was written to disk, return null // since we don't want to load the assembly we've just created. if (toAssembly) { return(null); } else { return(cr.CompiledAssembly); } }