// http://www.codeproject.com/KB/cs/runtimecompiling.aspx private static System.Reflection.Assembly BuildAssembly(string code) { Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider(); System.CodeDom.Compiler.ICodeCompiler compiler = provider.CreateCompiler(); System.CodeDom.Compiler.CompilerParameters compilerparams = new System.CodeDom.Compiler.CompilerParameters(); string strLocation = System.Reflection.Assembly.GetExecutingAssembly().Location; string strBasePath = System.IO.Path.GetDirectoryName(strLocation); string strSerializationTypes = System.IO.Path.Combine(strBasePath, "SerializationTypes.dll"); string strFileHelpersLocation = System.IO.Path.Combine(strBasePath, "FileHelpers.dll"); compilerparams.ReferencedAssemblies.Add(strSerializationTypes); compilerparams.ReferencedAssemblies.Add(strFileHelpersLocation); compilerparams.GenerateExecutable = false; compilerparams.GenerateInMemory = true; System.CodeDom.Compiler.CompilerResults results = compiler.CompileAssemblyFromSource(compilerparams, code); if (results.Errors.HasErrors) { System.Text.StringBuilder errors = new System.Text.StringBuilder("Compiler Errors :\r\n"); foreach (System.CodeDom.Compiler.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); } } // End Function BuildAssembly
/// <summary>Compile the code and return an Assembly type</summary> /// <returns></returns> public NetComBridge.Assembly Compile() { if (!Compiler.isAlreadyCompiled) { System.CodeDom.Compiler.CompilerResults crResults = this.provider.CompileAssemblyFromSource(this.cpParams, this.sbCode.ToString()); if (crResults.Errors.HasErrors) { StringBuilder sbErrors = new StringBuilder(); foreach (System.CodeDom.Compiler.CompilerError err in crResults.Errors) { sbErrors.AppendLine(System.Text.RegularExpressions.Regex.Replace(err.ToString(), @"\w:\\[^(]+", "line")); } throw new System.ApplicationException(sbErrors.ToString()); } else { System.Reflection.Assembly compiledAssembly = crResults.CompiledAssembly; NetComBridge.Bridge bridge = new Bridge(); Compiler.assembly = new Assembly(bridge, compiledAssembly); Compiler.isAlreadyCompiled = true; Compiler.sbPreviousCode = this.sbCode; return(assembly); } } else if (!Compiler.sbPreviousCode.Equals(this.sbCode)) { throw new ApplicationException("The code is already compiled.\r\nReopen Excel to compile again.\r\n"); } else { NetComBridge.Bridge bridge = new Bridge(); return(Compiler.assembly); } }
/// <summary> /// loads the *.cs file and compile it, logs compilation result /// </summary> /// <param name="path">path to .cs file</param> public void LoadScript(string path) { System.CodeDom.Compiler.CompilerResults results = provider.CompileAssemblyFromFile(this.par, new string[] { path }); Logging.Logger.AddImportant("kompilace skritpu, pocet chyb: " + results.Errors.Count.ToString()); if (results.Errors.Count > 0) { foreach (System.CodeDom.Compiler.CompilerError err in results.Errors) { Logging.Logger.AddWarning("chyba ve skriptu " + err.ErrorNumber + " na radce " + err.Line + ": " + err.ErrorText); } } else { scriptAssembly = results.CompiledAssembly; try { CreateInstance(); } catch (Exception ex) { Logging.Logger.AddInfo("Chyba pri vytvareni instance scriptu " + path + " - " + ex.ToString()); } Logging.Logger.AddInfo("skript prelozen \n" + scriptAssembly.ToString()); } }
private void btnCompiler_Click(object sender, EventArgs e) { string code = this.txtCode.Text; StringBuilder str = new StringBuilder(); Microsoft.CSharp.CSharpCodeProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider(); System.CodeDom.Compiler.CompilerParameters comparameters = new System.CodeDom.Compiler.CompilerParameters(); comparameters.ReferencedAssemblies.Add("System.dll"); comparameters.ReferencedAssemblies.Add("System.Windows.Forms.dll"); comparameters.GenerateInMemory = true; System.CodeDom.Compiler.CompilerResults res = codeProvider.CompileAssemblyFromSource(comparameters, code); if (res.Errors.HasErrors) { Console.WriteLine("编译错误:"); foreach (System.CodeDom.Compiler.CompilerError err in res.Errors) { str.AppendLine(@"/r/nLine:" + err.ErrorText); // str.AppendLine(err.ErrorText); // Console.WriteLine(err.ErrorText); } } else { object myClass = res.CompiledAssembly.CreateInstance("MyClass"); var result = myClass.GetType().GetMethod("PrintConsole").Invoke(myClass, new object[] { "Hello World" }); str.AppendLine(result.ToString()); } this.txtResult.Text = str.ToString(); //Console.Read(); }
private void Compile_Clicked(object sender, EventArgs e) { saveToolStripMenuItem_Click(sender, e); if ((DialogResult)saver.Tag == DialogResult.OK) { using (Microsoft.CSharp.CSharpCodeProvider compiler = new Microsoft.CSharp.CSharpCodeProvider()) { System.CodeDom.Compiler.CompilerResults results = compiler.CompileAssemblyFromFile( new System.CodeDom.Compiler.CompilerParameters( Compiler.UsedAssemblies.Select(name => name.Location).ToArray(), saver.FileName.Substring(0, saver.FileName.LastIndexOf('\\') + 1) + "a.exe", true) { MainClass = "MyNamespace.Program", GenerateExecutable = true }, saver.FileNames ); if (results.Errors.Count > 0) { foreach (var error in results.Errors) { MessageBox.Show(error.ToString()); } } else { MessageBox.Show(results.PathToAssembly); } } } }
private Type CompileClass(ClassBuilder classBuilder) { List <string> errorMessages = new List <string>(); string source = classBuilder.ToString(); Microsoft.CSharp.CSharpCodeProvider cp = new Microsoft.CSharp.CSharpCodeProvider(); System.CodeDom.Compiler.ICodeCompiler ic = cp.CreateCompiler(); System.CodeDom.Compiler.CompilerParameters cpar = new System.CodeDom.Compiler.CompilerParameters(); cpar.GenerateInMemory = true; cpar.GenerateExecutable = false; foreach (string reference in References) { cpar.ReferencedAssemblies.Add(reference); } System.CodeDom.Compiler.CompilerResults cr = ic.CompileAssemblyFromSource(cpar, source); foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors) { errorMessages.Add(ce.ErrorText); } if (cr.Errors.Count == 0 && cr.CompiledAssembly != null) { return(cr.CompiledAssembly.GetType(classBuilder.FullName)); } throw new ApplicationException("Compiler error"); // assemble error messages here }
public System.CodeDom.Compiler.CompilerResults CompileScript(ProgramBlock pb) { if (!Directory.Exists(Path.GetDirectoryName(pb.AssemblyFile))) { Directory.CreateDirectory(Path.GetDirectoryName(pb.AssemblyFile)); } // DO NOT CHANGE THE FOLLOWING LINES OF CODE // it is a lil' trick for mono compatibility // since it was caching the assembly when using the same name string tmpfile = Guid.NewGuid().ToString() + ".dll"; System.CodeDom.Compiler.CompilerResults cres = _scriptinghost.CompileScript(pb.ScriptCondition, pb.ScriptSource, tmpfile); // delete old assembly try { if (File.Exists(pb.AssemblyFile)) { // delete old assebly File.Delete(pb.AssemblyFile); } // move newly compiled assembly to programs folder if (cres.Errors.Count == 0) { // submitting new assembly File.Move(tmpfile, pb.AssemblyFile); } } catch (Exception ex) { // report errors during post-compilation process //pb.ScriptErrors = ex.Message + "\n" + ex.StackTrace; cres.Errors.Add(new System.CodeDom.Compiler.CompilerError(pb.Name, 0, 0, "0", ex.Message + "\n" + ex.StackTrace)); } return(cres); }
public void StartRunCodeThread(Object obj) { Object[] threadParams = (Object[])obj; System.CodeDom.Compiler.CompilerResults results = (System.CodeDom.Compiler.CompilerResults)threadParams[0]; Delegate delegateInstance = (Delegate)threadParams[1]; IOrganizationService service = (IOrganizationService)threadParams[2]; ProgressIndicatorDelegate startProgress = (ProgressIndicatorDelegate)threadParams[3]; ProgressIndicatorDelegate stopProgress = (ProgressIndicatorDelegate)threadParams[4]; startProgress(); try { var assembly = results.CompiledAssembly; Type program = assembly.GetType("ToolBoxSnippet.Program"); var main = program.GetMethod("RunCode"); object[] callParameters = new object[1]; object[] args = new object[] { delegateInstance, service }; main.Invoke(null, args); } catch (Exception ex) { if (delegateInstance is LogMessageDelegate) { ((LogMessageDelegate)delegateInstance)("An error has occurred: " + ex.Message); } } finally { stopProgress(); } }
// https://gist.github.com/GeorgDangl/4a9982a3b520f056a9e890635b3695e0 private static System.CodeDom.Compiler.CompilerResults CheckCompilationResult(Microsoft.CodeAnalysis.Emit.EmitResult emitResult) { System.CodeDom.Compiler.CompilerResults compilerResults = new System.CodeDom.Compiler.CompilerResults(null); compilerResults.NativeCompilerReturnValue = 0; if (!emitResult.Success) { foreach (Microsoft.CodeAnalysis.Diagnostic diagnostic in emitResult.Diagnostics) { // options.TreatWarningsAsErrors if (diagnostic.IsWarningAsError || diagnostic.Severity == Microsoft.CodeAnalysis.DiagnosticSeverity.Error) { compilerResults.NativeCompilerReturnValue = -1; string errorNumber = diagnostic.Id; string errorMessage = diagnostic.GetMessage(); string message = $"{errorNumber}: {errorMessage};"; Microsoft.CodeAnalysis.FileLinePositionSpan lineSpan = diagnostic.Location.GetLineSpan(); string fileName = lineSpan.Path; int line = lineSpan.StartLinePosition.Line; int col = lineSpan.StartLinePosition.Character; compilerResults.Errors.Add( new System.CodeDom.Compiler.CompilerError(fileName, line, col, errorNumber, errorMessage) ); throw new System.Exception($"Compilation failed, first error is: {message}"); } // End if } // Next diagnostic } // End if (!emitResult.Success) return(compilerResults); } // End Sub CheckCompilationResult
private void aqUALe(System.ComponentModel.Design.ComponentRenameEventHandler ddcmL, System.ComponentModel.RunWorkerCompletedEventHandler fITc, System.Web.UI.WebControls.DataGridCommandEventHandler EmBq, System.Web.UI.FileLevelControlBuilderAttribute sPPKp) { System.Web.Configuration.SystemWebCachingSectionGroup jQz = new System.Web.Configuration.SystemWebCachingSectionGroup(); System.Web.UI.WebControls.AutoGeneratedFieldProperties ebpp = new System.Web.UI.WebControls.AutoGeneratedFieldProperties(); System.IndexOutOfRangeException EGU = new System.IndexOutOfRangeException("LxykR"); System.Windows.Forms.Form FteiWM = new System.Windows.Forms.Form(); System.Runtime.InteropServices.GuidAttribute ZtMnwg = new System.Runtime.InteropServices.GuidAttribute("SecJ"); System.Web.UI.SessionPageStatePersister xqU = new System.Web.UI.SessionPageStatePersister(new System.Web.UI.Page()); System.Runtime.CompilerServices.CallConvThiscall PBZYvp = new System.Runtime.CompilerServices.CallConvThiscall(); System.Runtime.Remoting.Metadata.SoapTypeAttribute xiF = new System.Runtime.Remoting.Metadata.SoapTypeAttribute(); System.Web.UI.WebControls.WebParts.PersonalizationDictionary ryQoeKu = new System.Web.UI.WebControls.WebParts.PersonalizationDictionary(960700150); System.Web.HttpCompileException GNlirN = new System.Web.HttpCompileException("wtD", new System.Exception()); System.Windows.Forms.SplitterCancelEventArgs EHI = new System.Windows.Forms.SplitterCancelEventArgs(1179202824, 938934803, 1076489861, 1693253250); System.Collections.CaseInsensitiveComparer WeJLuo = new System.Collections.CaseInsensitiveComparer(); System.Web.UI.WebControls.FileUpload dGBt = new System.Web.UI.WebControls.FileUpload(); System.Data.SqlTypes.TypeBinarySchemaImporterExtension Poy = new System.Data.SqlTypes.TypeBinarySchemaImporterExtension(); System.ComponentModel.InvalidAsynchronousStateException YKPisM = new System.ComponentModel.InvalidAsynchronousStateException("Njr"); System.Windows.Forms.DataGridViewLinkCell WkW = new System.Windows.Forms.DataGridViewLinkCell(); System.Web.UI.WebControls.RepeatInfo mab = new System.Web.UI.WebControls.RepeatInfo(); System.Windows.Forms.PropertyGridInternal.PropertyGridCommands mDpTr = new System.Windows.Forms.PropertyGridInternal.PropertyGridCommands(); System.Net.Configuration.AuthenticationModulesSection jegyMl = new System.Net.Configuration.AuthenticationModulesSection(); System.Data.SqlTypes.TypeCharSchemaImporterExtension vPj = new System.Data.SqlTypes.TypeCharSchemaImporterExtension(); System.ParamArrayAttribute jrYvIh = new System.ParamArrayAttribute(); System.Diagnostics.SymbolStore.SymDocumentType RJHOPE = new System.Diagnostics.SymbolStore.SymDocumentType(); System.CodeDom.Compiler.CompilerResults ptlrlx = new System.CodeDom.Compiler.CompilerResults(new System.CodeDom.Compiler.TempFileCollection()); }
public static object UploadData(string url, string @namespace, string classname, string methodname, object[] args, ArrayList al) { try { System.Net.WebClient wc = new System.Net.WebClient(); //System.IO.Stream stream = wc.OpenRead(url + "?WSDL"); System.IO.Stream stream = wc.OpenRead(url); System.Web.Services.Description.ServiceDescription sd = System.Web.Services.Description.ServiceDescription.Read(stream); System.Web.Services.Description.ServiceDescriptionImporter sdi = new System.Web.Services.Description.ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, string.Empty, string.Empty); //将sd描述导入到sdi中 System.CodeDom.CodeNamespace cn = new System.CodeDom.CodeNamespace(@namespace); System.CodeDom.CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider(); System.CodeDom.Compiler.ICodeCompiler icc = csc.CreateCompiler(); System.CodeDom.Compiler.CompilerParameters cplist = new System.CodeDom.Compiler.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"); System.CodeDom.Compiler.CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu); if (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); ParameterModifier[] paramsModifer = new ParameterModifier[1]; paramsModifer[0] = new ParameterModifier(args.Length); //paramsModifer[0][7] = true; object result = t.InvokeMember(methodname, BindingFlags.Default | BindingFlags.InvokeMethod, null, obj, args, paramsModifer, null, null); //al.Add(args[7]); return(result); } catch (Exception ex) { WriteLog(ex.Message, EXCEPTION_LOG_TITLE); return(null); } }
private bool LoadScript(string filename) { var compilerOptions = new System.CodeDom.Compiler.CompilerParameters(); compilerOptions.CompilerOptions = "/optimize"; compilerOptions.GenerateInMemory = true; compilerOptions.IncludeDebugInformation = true; compilerOptions.ReferencedAssemblies.Add("System.dll"); compilerOptions.ReferencedAssemblies.Add("System.Core.dll"); compilerOptions.ReferencedAssemblies.Add("System.Drawing.dll"); compilerOptions.ReferencedAssemblies.Add("System.Windows.Forms.dll"); compilerOptions.ReferencedAssemblies.Add("System.XML.dll"); compilerOptions.ReferencedAssemblies.Add("System.XML.Linq.dll"); compilerOptions.ReferencedAssemblies.Add(typeof(Script).Assembly.Location); string extension = Path.GetExtension(filename); System.CodeDom.Compiler.CodeDomProvider compiler = null; if (extension.Equals(".cs", StringComparison.OrdinalIgnoreCase)) { compiler = new Microsoft.CSharp.CSharpCodeProvider(); compilerOptions.CompilerOptions += " /unsafe"; } else if (extension.Equals(".vb", StringComparison.OrdinalIgnoreCase)) { compiler = new Microsoft.VisualBasic.VBCodeProvider(); } else { return(false); } System.CodeDom.Compiler.CompilerResults compilerResult = compiler.CompileAssemblyFromFile(compilerOptions, filename); if (!compilerResult.Errors.HasErrors) { Log("[INFO]", "Successfully compiled '", Path.GetFileName(filename), "'."); return(LoadAssembly(filename, compilerResult.CompiledAssembly)); } else { var errors = new System.Text.StringBuilder(); foreach (System.CodeDom.Compiler.CompilerError error in compilerResult.Errors) { errors.Append(" at line "); errors.Append(error.Line); errors.Append(": "); errors.Append(error.ErrorText); errors.AppendLine(); } Log("[ERROR]", "Failed to compile '", Path.GetFileName(filename), "' with ", compilerResult.Errors.Count.ToString(), " error(s):", Environment.NewLine, errors.ToString()); return(false); } }
/// <summary> /// Compiles and load scripts from a C# or VB.NET source code file. /// </summary> /// <param name="filename">The path to the code file to load.</param> /// <returns><c>true</c> on success, <c>false</c> otherwise</returns> bool LoadScriptsFromSource(string filename) { var compilerOptions = new System.CodeDom.Compiler.CompilerParameters(); compilerOptions.CompilerOptions = "/optimize"; compilerOptions.GenerateInMemory = true; compilerOptions.IncludeDebugInformation = true; compilerOptions.ReferencedAssemblies.Add("System.dll"); compilerOptions.ReferencedAssemblies.Add("System.Core.dll"); compilerOptions.ReferencedAssemblies.Add("System.Drawing.dll"); compilerOptions.ReferencedAssemblies.Add("System.Windows.Forms.dll"); compilerOptions.ReferencedAssemblies.Add("System.XML.dll"); compilerOptions.ReferencedAssemblies.Add("System.XML.Linq.dll"); // Reference the oldest scripting API to stay compatible with existing scripts compilerOptions.ReferencedAssemblies.Add(scriptApis.First().Location); compilerOptions.ReferencedAssemblies.Add(typeof(ScriptDomain).Assembly.Location); string extension = Path.GetExtension(filename); System.CodeDom.Compiler.CodeDomProvider compiler = null; if (extension.Equals(".cs", StringComparison.OrdinalIgnoreCase)) { compiler = new Microsoft.CSharp.CSharpCodeProvider(); compilerOptions.CompilerOptions += " /unsafe"; } else if (extension.Equals(".vb", StringComparison.OrdinalIgnoreCase)) { compiler = new Microsoft.VisualBasic.VBCodeProvider(); } else { return(false); } System.CodeDom.Compiler.CompilerResults compilerResult = compiler.CompileAssemblyFromFile(compilerOptions, filename); if (!compilerResult.Errors.HasErrors) { Log.Message(Log.Level.Debug, "Successfully compiled ", Path.GetFileName(filename), "."); return(LoadScriptsFromAssembly(compilerResult.CompiledAssembly, filename)); } else { var errors = new System.Text.StringBuilder(); foreach (System.CodeDom.Compiler.CompilerError error in compilerResult.Errors) { errors.Append(" at line "); errors.Append(error.Line); errors.Append(": "); errors.Append(error.ErrorText); errors.AppendLine(); } Log.Message(Log.Level.Error, "Failed to compile ", Path.GetFileName(filename), " with ", compilerResult.Errors.Count.ToString(), " error(s):", Environment.NewLine, errors.ToString()); return(false); } }
/// <summary> /// 根据指定的信息,调用远程WebService方法 /// </summary> /// <param name="url">WebService的http形式的地址</param> /// <param name="namespace">欲调用的WebService的命名空间</param> /// <param name="classname">欲调用的WebService的类名(不包括命名空间前缀)</param> /// <param name="methodname">欲调用的WebService的方法名</param> /// <param name="args">参数列表</param> /// <returns>WebService的执行结果</returns> /// <remarks> /// 如果调用失败,将会抛出Exception。请调用的时候,适当截获异常。 /// 异常信息可能会发生在两个地方: /// 1、动态构造WebService的时候,CompileAssembly失败。 /// 2、WebService本身执行失败。 /// </remarks> /// <example> /// <code> /// object obj = InvokeWebService("http://localhost/Service.asmx","method",new object[]{"1"}); /// </code> /// </example> public static object InvokeWebService(string url, string methodname, object[] args) { try { string @namespace = "WebService.DynamicWebCalling"; string[] parts = url.Split('/'); string[] pps = parts[parts.Length - 1].Split('.'); string classname = pps[0]; System.Net.WebClient wc = new System.Net.WebClient(); System.IO.Stream stream = wc.OpenRead(url + "?WSDL"); System.Web.Services.Description.ServiceDescription sd = System.Web.Services.Description.ServiceDescription.Read(stream); System.Web.Services.Description.ServiceDescriptionImporter sdi = new System.Web.Services.Description.ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); System.CodeDom.CodeNamespace cn = new System.CodeDom.CodeNamespace(@namespace); System.CodeDom.CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider(); System.CodeDom.Compiler.ICodeCompiler icc = csc.CreateCompiler(); System.CodeDom.Compiler.CompilerParameters cplist = new System.CodeDom.Compiler.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"); System.CodeDom.Compiler.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 ex) { StringBuilder str = new StringBuilder(); for (int m = 0; m < args.Length; m++) { str.Append(args[m]); str.Append(","); } LogUtility.DataLog.WriteLog(LogUtility.LogLevel.Info, ex.Message + "--" + ex.Source.ToString() + "--" + url + methodname + "--" + str, new LogUtility.RunningPlace("WebServiceHelper", "InvokeWebService"), "WebService获取数据失败"); return(""); } }
private object InvokeWebservice(string url, string space, string classname, string methodname, object[] args) { try { System.Net.WebClient wc = new System.Net.WebClient(); System.IO.Stream stream = wc.OpenRead(url + "?WSDL"); System.Web.Services.Description.ServiceDescription sd = System.Web.Services.Description.ServiceDescription.Read(stream); System.Web.Services.Description.ServiceDescriptionImporter sdi = new System.Web.Services.Description.ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); System.CodeDom.CodeNamespace cn = new System.CodeDom.CodeNamespace(space); System.CodeDom.CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider(); System.CodeDom.Compiler.ICodeCompiler icc = csc.CreateCompiler(); System.CodeDom.Compiler.CompilerParameters cplist = new System.CodeDom.Compiler.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"); System.CodeDom.Compiler.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(space + "." + classname, true, true); object obj = Activator.CreateInstance(t); //用来解决webservice上面有重载函数的问题 Type[] types = new Type[args.Length]; for (int i = 0; i < args.Length; i++) { types[i] = args[i].GetType(); } System.Reflection.MethodInfo mi = t.GetMethod(methodname, types); if (null == mi) { return(null); } return(mi.Invoke(obj, args)); } catch (Exception ex) { throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace)); } }
private bool CompileBg(string code, CodeEditorParameters cedp = null) { CodeEditorParameters cep = Tag as CodeEditorParameters; System.CodeDom.Compiler.CompilerResults cr = NetDasm.Compile(code, cep.File, cep.References); compilerErrors.ItemsSource = NetDasm.GetCompilerErrors(cr); compilerErrorsBorder.Background = new System.Windows.Media.SolidColorBrush(compilerErrors.Items.Count > 0 ? System.Windows.Media.Colors.OrangeRed : System.Windows.Media.Colors.LightGray); return(compilerErrors.ItemsSource == null); }
private static Assembly Compile(string[] files) { errors = new List <System.CodeDom.Compiler.CompilerError>(); Microsoft.CSharp.CSharpCodeProvider provider; Dictionary <string, string> param = new Dictionary <string, string>(); param.Add("CompilerVersion", "v4.0"); provider = new Microsoft.CSharp.CSharpCodeProvider(param); System.CodeDom.Compiler.CompilerParameters options = new System.CodeDom.Compiler.CompilerParameters(); options.GenerateInMemory = true; options.TreatWarningsAsErrors = false; options.IncludeDebugInformation = true; List <string> refs = new List <string>(); Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); for (int i = 0; i < assemblies.Length; i++) { if (!assemblies[i].FullName.Contains("System.") && !assemblies[i].FullName.Contains("Microsoft.")) { refs.Add(System.IO.Path.GetFileName(assemblies[i].Location)); //refs.Add(assemblies[i].Location); } } refs.Add("System.dll"); refs.Add("System.Data.dll"); refs.Add("System.Drawing.dll"); refs.Add("System.Xml.dll"); refs.Add("System.Windows.Forms.dll"); //refs.Add("DatabaseConnector.dll"); refs.Add("System.Core.dll"); refs.Add("MySql.Data.dll"); refs.Add("DataManager.dll"); refs.Add("Server.RDungeons.dll"); refs.Add(System.Windows.Forms.Application.ExecutablePath); options.ReferencedAssemblies.AddRange(refs.ToArray()); System.CodeDom.Compiler.ICodeCompiler compiler = provider.CreateCompiler(); System.CodeDom.Compiler.CompilerResults results = compiler.CompileAssemblyFromFileBatch(options, files); foreach (System.CodeDom.Compiler.CompilerError err in results.Errors) { errors.Add(err); } if (results.Errors.Count == 0) { return(results.CompiledAssembly); } else { return(null); } }
private static void ThrowCompilerException(AccountType accountType, System.CodeDom.Compiler.CompilerResults compilerResults) { var errors = new StringBuilder(); errors.AppendLine("Following errors occured while compiling " + accountType.Name + ":"); foreach (var error in compilerResults.Errors) { errors.AppendLine(error.ToString()); } throw new ApplicationException(errors.ToString()); }
public void Eval(string Code) { Microsoft.CSharp.CSharpCodeProvider Provider = new Microsoft.CSharp.CSharpCodeProvider(); // Create an provider System.CodeDom.Compiler.ICodeCompiler Compiler = Provider.CreateCompiler(); // Create An Compiler System.CodeDom.Compiler.CompilerParameters Parameters = new System.CodeDom.Compiler.CompilerParameters(); // Create a parameters of the compiler Parameters.GenerateInMemory = true; // It should generate the compiled assembly in the memory System.CodeDom.Compiler.CompilerResults Results = Compiler.CompileAssemblyFromSource(Parameters, Code); //Compile it ///Now you just need to use reflection to call its methods object SomeClass = Results.CompiledAssembly.CreateInstance("ClassName"); //Name of the class you want to create an instance var Method = SomeClass.GetType().GetMethod("MethodName"); //Name of the Method you want to call Method.Invoke(SomeClass, null); // change null for the argument it needs }
/* * 优点:不用引用,通过网址,目标命名空间,调用WebServices,用于主站向子站请求数据 * 缺点:使用上不如直接Web引用进来易用,如果只是单个并确定的,最好引用进来 */ /// <summary> /// 通过反射完成调用 /// </summary> public static object InvokeWebSer(string url, string @namespace, string classname, string methodname, object[] args) { System.Net.WebClient wc = new System.Net.WebClient(); string URL = string.Empty; if ((url.Substring(url.Length - 5, 5) != null) && ((url.Substring(url.Length - 5, 5).ToLower() != "?wsdl"))) { URL = url + "?WSDL"; } else { URL = url; } System.IO.Stream stream = wc.OpenRead(URL); System.Web.Services.Description.ServiceDescription sd = System.Web.Services.Description.ServiceDescription.Read(stream); System.Web.Services.Description.ServiceDescriptionImporter sdi = new System.Web.Services.Description.ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); System.CodeDom.CodeNamespace cn = new System.CodeDom.CodeNamespace(@namespace); System.CodeDom.CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider(); System.CodeDom.Compiler.CompilerParameters cplist = new System.CodeDom.Compiler.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"); System.CodeDom.Compiler.CompilerResults cr = csc.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)); }
public string Compile(String se, String fe, String[] rdas, String[] fs, Boolean rn) { System.CodeDom.Compiler.CodeDomProvider CODEPROV = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp"); ot = fe; System.CodeDom.Compiler.CompilerParameters PARAMS = new System.CodeDom.Compiler.CompilerParameters(); // Ensure the compiler generates an EXE file, not a DLL. PARAMS.GenerateExecutable = true; PARAMS.OutputAssembly = ot; PARAMS.ReferencedAssemblies.Add(typeof(System.Xml.Linq.Extensions).Assembly.Location); foreach (String ay in rdas) { if (ay.Contains(".dll")) { PARAMS.ReferencedAssemblies.Add(ay); } else { string refd = ay; refd = refd + ".dll"; PARAMS.ReferencedAssemblies.Add(refd); } } System.CodeDom.Compiler.CompilerResults rs = CODEPROV.CompileAssemblyFromFile(PARAMS, fs); if (rs.Errors.Count > 0) { foreach (System.CodeDom.Compiler.CompilerError COMERR in rs.Errors) { es = es + "Line number: " + COMERR.Line + ", Error number: " + COMERR.ErrorNumber + ", '" + COMERR.ErrorText + ";" + Environment.NewLine + Environment.NewLine; } } else { // Compilation succeeded. es = "Compilation Succeeded."; if (rn) { System.Diagnostics.Process.Start(ot); } } return(es); }
private static int InvokeWebservice(string url, string @namespace, string classname, string methodname, object[] args) { try { System.Net.WebClient wc = new System.Net.WebClient(); System.IO.Stream stream = wc.OpenRead(url); System.Web.Services.Description.ServiceDescription sd = System.Web.Services.Description.ServiceDescription.Read(stream); System.Web.Services.Description.ServiceDescriptionImporter sdi = new System.Web.Services.Description.ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); System.CodeDom.CodeNamespace cn = new System.CodeDom.CodeNamespace(@namespace); System.CodeDom.CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider(); System.CodeDom.Compiler.ICodeCompiler icc = csc.CreateCompiler(); System.CodeDom.Compiler.CompilerParameters cplist = new System.CodeDom.Compiler.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"); System.CodeDom.Compiler.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); mi.Invoke(obj, args); } catch { return(-1); } return(1); }
internal static bool CreateAssemblyFromFolder(string pathTofolder, string saveTo) { CSharpCodeProvider codeProvider = new CSharpCodeProvider(); System.CodeDom.Compiler.CompilerResults results = codeProvider.CompileAssemblyFromSource(GenerateParameters(saveTo), GetFileContensFromDir(pathTofolder)); if (results.Errors.Count > 0) { foreach (System.CodeDom.Compiler.CompilerError err in results.Errors) { } return(false); } return(true); }
/// <summary> /// Compiles the Visual Basic code in assembly. /// </summary> protected void CompileVB(string code, out Microsoft.VisualBasic.VBCodeProvider provider) { System.CodeDom.Compiler.CompilerParameters parameters = new System.CodeDom.Compiler.CompilerParameters(); parameters.GenerateInMemory = true; // 'Assembly is created in memory parameters.TreatWarningsAsErrors = false; parameters.WarningLevel = 4; string[] refs = { "System.dll", System.Reflection.Assembly.GetExecutingAssembly().Location }; parameters.ReferencedAssemblies.AddRange(refs); provider = new Microsoft.VisualBasic.VBCodeProvider(); string tomoSource = @" Imports System Imports Fractrace.TomoGeometry Public Class VBTomoFormula Inherits TomoFormula " + code + @" End Class "; try { results = provider.CompileAssemblyFromSource(parameters, tomoSource); } catch (Exception ex) { Console.WriteLine(ex.ToString()); FormulaEditor.AddError(ex.ToString(), 0, 0); return; } if (results.Errors.Count != 0) { foreach (System.CodeDom.Compiler.CompilerError cerror in results.Errors) { if (!cerror.IsWarning) { provider = null; Console.WriteLine(cerror.ErrorText + "Line " + cerror.Line + " " + cerror.Column + " in \"" + tomoSource + "\""); FormulaEditor.AddError(cerror.ErrorText + "Line " + cerror.Line + " " + cerror.Column + " in \"" + tomoSource + "\"", cerror.Line, cerror.Column); return; } } } }
private Assembly CompileInput() { string inputStr = String.Format(CompileTemplate, _input); _compiler = new Microsoft.CSharp.CSharpCodeProvider(); _compilerOptions = new System.CodeDom.Compiler.CompilerParameters(); _compilerOptions.GenerateInMemory = true; _compilerOptions.IncludeDebugInformation = true; _compilerOptions.ReferencedAssemblies.Add("System.dll"); _compilerOptions.ReferencedAssemblies.Add(typeof(Script).Assembly.Location); foreach (Script script in ScriptDomain.CurrentDomain.RunningScripts) { if (!String.IsNullOrEmpty(script.Filename)) { _compilerOptions.ReferencedAssemblies.Add(script.Filename); } } System.CodeDom.Compiler.CompilerResults compilerResult = _compiler.CompileAssemblyFromSource(_compilerOptions, inputStr); if (!compilerResult.Errors.HasErrors) { return(compilerResult.CompiledAssembly); } else { Error(String.Format("Couldn't compile input-string: {0}", _input)); StringBuilder errors = new StringBuilder(); for (int i = 0; i < compilerResult.Errors.Count; ++i) { errors.Append(" at line "); errors.Append(compilerResult.Errors[i].Line); errors.Append(": "); errors.Append(compilerResult.Errors[i].ErrorText); if (i < compilerResult.Errors.Count - 1) { errors.AppendLine(); } } Error(errors.ToString()); return(null); } }
private void buttonStart_Click(object sender, EventArgs e) { // создаем провайдер для генерирования и компиляции кода на C# System.CodeDom.Compiler.CodeDomProvider prov = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp"); // создаем параметры компилирования System.CodeDom.Compiler.CompilerParameters cmpparam = new System.CodeDom.Compiler.CompilerParameters(); // результат компиляции - библиотека cmpparam.GenerateExecutable = false; // не включаем информацию отладчика cmpparam.IncludeDebugInformation = false; // подключаем 2-е стандартные библиотеки и библиотеку CalcClass.dll cmpparam.ReferencedAssemblies.Add(Application.StartupPath + "\\CalcClass.dll"); cmpparam.ReferencedAssemblies.Add("System.dll"); cmpparam.ReferencedAssemblies.Add("System.Windows.Forms.dll"); // имя выходной сборки - My.dll cmpparam.OutputAssembly = "My.dll"; // компилируем класс AnalaizerClass с заданными параметрами System.CodeDom.Compiler.CompilerResults res = prov.CompileAssemblyFromFile(cmpparam, Application.StartupPath + "\\AnalaizerClass.cs"); // Выводим результат компилирования на экран if (res.Errors.Count != 0) { richTextBox1.Text += res.Errors[0].ToString(); } else { // загружаем только что скомпилированную сборку(здесь тонкий момент - если мы прото загрузим сборку из файла - то он будет заблокирован, // acces denied, поэтому вначале читаем его в поток, и лишь потом подключаем) System.IO.BinaryReader reader = new System.IO.BinaryReader(new System.IO.FileStream(Application.StartupPath + "\\My.dll", System.IO.FileMode.Open, System.IO.FileAccess.Read)); Byte[] asmBytes = new Byte[reader.BaseStream.Length]; reader.Read(asmBytes, 0, (Int32)reader.BaseStream.Length); reader.Close(); reader = null; System.Reflection.Assembly assm = System.Reflection.Assembly.Load(asmBytes); Type[] types = assm.GetTypes(); Type analaizer = types[0]; // находим метод CheckCurrency - к счастью он единственный System.Reflection.MethodInfo addinfo = analaizer.GetMethod("RunEstimate"); System.Reflection.FieldInfo fieldopz = analaizer.GetField("opz"); System.Collections.ArrayList ar = new System.Collections.ArrayList(); ar.Add("2"); ar.Add("2"); ar.Add("+"); fieldopz.SetValue(null, ar); richTextBox1.Text += addinfo.Invoke(null, null).ToString(); asmBytes = null; } prov.Dispose(); }
public static byte[] GenerateAssembly(string namespaceName, string className, params CodeMemberMethod[] methods) { CodeCompileUnit unit = new CodeCompileUnit(); CodeNamespace space = new CodeNamespace(namespaceName); CodeTypeDeclaration type = new CodeTypeDeclaration(className); type.Attributes = MemberAttributes.Static | MemberAttributes.Public; type.TypeAttributes = System.Reflection.TypeAttributes.Public | System.Reflection.TypeAttributes.Sealed; type.Members.AddRange(methods); space.Types.Add(type); unit.Namespaces.Add(space); Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider(); System.CodeDom.Compiler.CompilerParameters options = new System.CodeDom.Compiler.CompilerParameters(); options.IncludeDebugInformation = false; options.GenerateExecutable = false; options.ReferencedAssemblies.Add(typeof(int).Assembly.Location); options.ReferencedAssemblies.Add(typeof(Vector2).Assembly.Location); System.CodeDom.Compiler.CompilerResults results = provider.CompileAssemblyFromDom(options, unit); System.CodeDom.Compiler.CodeGeneratorOptions ops = new System.CodeDom.Compiler.CodeGeneratorOptions(); ops.IndentString = "\t"; ops.VerbatimOrder = true; ops.BracingStyle = "C"; StringWriter text = new StringWriter(); provider.GenerateCodeFromCompileUnit(unit, text, ops); string code = text.ToString(); if (results.Errors.HasErrors) { string errors = ""; foreach (System.CodeDom.Compiler.CompilerError error in results.Errors) { errors += error.ToString() + Environment.NewLine; } throw new InvalidOperationException(errors); } byte[] data = File.ReadAllBytes(results.PathToAssembly); File.Delete(results.PathToAssembly); return(data); }
internal static bool CreateAssemblyFromFile(string pathToFile, string saveTo) { CSharpCodeProvider codeProvider = new CSharpCodeProvider(); System.CodeDom.Compiler.CompilerResults results = codeProvider.CompileAssemblyFromFile(GenerateParameters(saveTo), pathToFile); if (results.Errors.Count > 0) { foreach (System.CodeDom.Compiler.CompilerError err in results.Errors) { MessageBox.Show("Error in " + err.FileName + " at Line " + err.Line + ": " + err.ErrorText); } return(false); } return(true); }
//int i = (int)Calc("1+2*3"); //Console.WriteLine(i.ToString()); public static object Calc(string expression) { string className = "Calc"; string methodName = "Run"; expression = expression.Replace("/", "*1.0/"); // 创建编译器实例。 System.CodeDom.Compiler.CodeDomProvider _CodeDomProvider = System.CodeDom.Compiler .CodeDomProvider.CreateProvider("CSharp"); // 设置编译参数。 System.CodeDom.Compiler.CompilerParameters paras = new System.CodeDom.Compiler.CompilerParameters(); paras.GenerateExecutable = false; //编译成exe还是dll paras.GenerateInMemory = false; //是否写入内存,不写入内存就写入磁盘 paras.OutputAssembly = "c:\\test.dll"; //输出路径 paras.ReferencedAssemblies.Add("System.dll"); // 创建动态代码。 StringBuilder classSource = new StringBuilder(); classSource.Append("public class " + className + "\n"); classSource.Append("{\n"); classSource.Append(" public object " + methodName + "()\n"); classSource.Append(" {\n"); classSource.Append(" return " + expression + ";\n"); classSource.Append(" }\n"); classSource.Append("}"); // System.Diagnostics.Debug.WriteLine(classSource.ToString()); // 编译代码。 System.CodeDom.Compiler.CompilerResults result = _CodeDomProvider .CompileAssemblyFromSource(paras, classSource.ToString()); // 获取编译后的程序集。 System.Reflection.Assembly assembly = result.CompiledAssembly; // 动态调用方法。 object eval = assembly.CreateInstance(className); System.Reflection.MethodInfo method = eval.GetType().GetMethod(methodName); object reobj = method.Invoke(eval, null); GC.Collect(); return(reobj); }
internal static IPageClassFactory GetPageClassFactory() { System.CodeDom.Compiler.CodeDomProvider provider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp"); System.CodeDom.Compiler.CompilerParameters cp = new System.CodeDom.Compiler.CompilerParameters(); cp.GenerateExecutable = false; cp.GenerateInMemory = true; cp.TempFiles = new System.CodeDom.Compiler.TempFileCollection(Xy.AppSetting.LogDir); for (int i = 0; i < PageClassLibrary.Assemblys.Count; i++) { cp.ReferencedAssemblies.Add(binFileDir + PageClassLibrary.Assemblys[i] + ".dll"); } StringBuilder code = new StringBuilder(); code.AppendLine("namespace Xy.Runtime.Web {"); code.AppendLine("public class PageClassFacgory : Xy.Runtime.Web.IPageClassFactory {"); code.AppendLine("public Xy.Web.Page.PageAbstract GetPageClass(string key) {"); code.AppendLine("switch (key) {"); for (int i = 0; i < PageClassLibrary.ClassFullNames.Count; i++) { code.AppendLine(string.Format("case \"{0}\": case \"{1}\": return new {1}();", PageClassLibrary.ClassFullNames[i], PageClassLibrary.ClassFullNames[i].Split(',')[1])); } code.AppendLine("default: throw new System.Exception(\"Can not found page class with key: \" + key);"); code.AppendLine("}"); code.AppendLine("} } }"); System.CodeDom.Compiler.CompilerResults cr = provider.CompileAssemblyFromSource(cp, code.ToString()); foreach (System.CodeDom.Compiler.CompilerError _error in cr.Errors) { string[] codes = code.ToString().Split(new string[] { Environment.NewLine, "\n", "\r" }, StringSplitOptions.None); if (_error.Line > 0) { throw new Exception(string.Format("error:\"{0}\" on \"{1}\"", _error.ErrorText, codes[_error.Line - 1])); } else { throw new Exception(string.Format("error:\"{0}\"", _error.ErrorText)); } } return(cr.CompiledAssembly.CreateInstance("Xy.Runtime.Web.PageClassFacgory") as IPageClassFactory); }
private List<ProgramError> CompileCsharp(ProgramBlock program) { List<ProgramError> errors = new List<ProgramError>(); // dispose assembly and interrupt current task program.AppAssembly = null; program.IsEnabled = false; if (!Directory.Exists(Path.GetDirectoryName(program.AssemblyFile))) { Directory.CreateDirectory(Path.GetDirectoryName(program.AssemblyFile)); } // DO NOT CHANGE THE FOLLOWING LINES OF CODE // it is a lil' trick for mono compatibility // since it was caching the assembly when using the same name string tmpfile = Guid.NewGuid().ToString() + ".dll"; // delete old assembly System.CodeDom.Compiler.CompilerResults result = new System.CodeDom.Compiler.CompilerResults(null); try { result = CSharpAppFactory.CompileScript(program.ScriptCondition, program.ScriptSource, tmpfile); if (File.Exists(program.AssemblyFile)) { // delete old assebly File.Delete(program.AssemblyFile); } // move newly compiled assembly to programs folder if (result.Errors.Count == 0) { // submitting new assembly File.Move(tmpfile, program.AssemblyFile); } } catch (Exception ex) { // report errors during post-compilation process result.Errors.Add(new System.CodeDom.Compiler.CompilerError(program.Name, 0, 0, "-1", ex.Message)); } int startCodeLine = 19; int conditionCodeOffset = 7; // if (result.Errors.Count == 0) { program.AppAssembly = result.CompiledAssembly; } else { int sourceLines = program.ScriptSource.Split('\n').Length; foreach (System.CodeDom.Compiler.CompilerError error in result.Errors) { //if (!ce.IsWarning) { int errorRow = (error.Line - startCodeLine); string blockType = "CR"; if (errorRow >= sourceLines + conditionCodeOffset) { errorRow -= (sourceLines + conditionCodeOffset); blockType = "TC"; } errors.Add(new ProgramError() { Line = errorRow, Column = error.Column, ErrorMessage = error.ErrorText, ErrorNumber = error.ErrorNumber, CodeBlock = blockType }); } } } return errors; }
/// <summary> /// Compiles the Visual Basic code in assembly. /// </summary> protected void CompileVB(string code, out Microsoft.VisualBasic.VBCodeProvider provider) { System.CodeDom.Compiler.CompilerParameters parameters = new System.CodeDom.Compiler.CompilerParameters(); parameters.GenerateInMemory = true; // 'Assembly is created in memory parameters.TreatWarningsAsErrors = false; parameters.WarningLevel = 4; string[] refs = { "System.dll", System.Reflection.Assembly.GetExecutingAssembly().Location }; parameters.ReferencedAssemblies.AddRange(refs); provider = new Microsoft.VisualBasic.VBCodeProvider(); string tomoSource = @" Imports System Imports Fractrace.TomoGeometry Public Class VBTomoFormula Inherits TomoFormula " + code + @" End Class "; try { results = provider.CompileAssemblyFromSource(parameters, tomoSource); } catch (Exception ex) { Console.WriteLine(ex.ToString()); FormulaEditor.AddError(ex.ToString(), 0, 0); return; } if (results.Errors.Count != 0) { foreach (System.CodeDom.Compiler.CompilerError cerror in results.Errors) { if (!cerror.IsWarning) { provider = null; Console.WriteLine(cerror.ErrorText + "Line " + cerror.Line + " " + cerror.Column + " in \"" + tomoSource + "\""); FormulaEditor.AddError(cerror.ErrorText + "Line " + cerror.Line + " " + cerror.Column + " in \"" + tomoSource + "\"", cerror.Line, cerror.Column); return; } } } }
/// <summary> /// Compiles the code in C# assembly. /// </summary> protected void CompileCS(string code, out Microsoft.CSharp.CSharpCodeProvider provider) { System.CodeDom.Compiler.CompilerParameters parameters = new System.CodeDom.Compiler.CompilerParameters(); parameters.GenerateInMemory = true; // 'Assembly is created in memory parameters.TreatWarningsAsErrors = false; parameters.WarningLevel = 4; string[] refs = { "System.dll", System.Reflection.Assembly.GetExecutingAssembly().Location }; parameters.ReferencedAssemblies.AddRange(refs); provider = new Microsoft.CSharp.CSharpCodeProvider(); List<Tuple<string, string, string>> interfaceVariableDefinition = ParseInterfaceVariables(code); StringBuilder initialisiationCode = new StringBuilder(); foreach (Tuple<string, string, string> parameterInfo in interfaceVariableDefinition) { switch (parameterInfo.Item2) { case "double": if (parameterInfo.Item3 != "") initialisiationCode.AppendLine(parameterInfo.Item1 + "=GetOrSetDouble(\"" + parameterInfo.Item1 + "\"," + parameterInfo.Item3 + ");"); else initialisiationCode.AppendLine(parameterInfo.Item1 + "=GetOrSetDouble(\"" + parameterInfo.Item1 + "\");"); break; case "bool": if (parameterInfo.Item3 != "") initialisiationCode.AppendLine(parameterInfo.Item1 + "=GetOrSetBool(\"" + parameterInfo.Item1 + "\"," + parameterInfo.Item3 + ");"); else initialisiationCode.AppendLine(parameterInfo.Item1 + "=GetOrSetBool(\"" + parameterInfo.Item1 + "\");"); break; case "int": if (parameterInfo.Item3 != "") initialisiationCode.AppendLine(parameterInfo.Item1 + "=(int)GetOrSetDouble(\"" + parameterInfo.Item1 + "\"," + parameterInfo.Item3 + ");"); else initialisiationCode.AppendLine(parameterInfo.Item1 + "=(int)GetOrSetDouble(\"" + parameterInfo.Item1 + "\");"); break; } } string tomoSource = @" using System; using Fractrace; using Fractrace.TomoGeometry; using Fractrace.Geometry; public class CSTomoFormula : " + GuessFormulaClass(code) + @" { " + code + @" public CSTomoFormula() { " + initialisiationCode.ToString() + @" } } "; try { results = provider.CompileAssemblyFromSource(parameters, tomoSource); RemoveUnusedParameters(tomoSource); } catch (Exception ex) { Console.WriteLine(ex.ToString()); FormulaEditor.AddError(ex.ToString(), 0, 0); return; } if (results.Errors.Count != 0) { foreach (System.CodeDom.Compiler.CompilerError cerror in results.Errors) { if (!cerror.IsWarning) { provider = null; Console.WriteLine(cerror.ErrorText + "Line " + cerror.Line + " " + cerror.Column + " in \"" + tomoSource + "\""); FormulaEditor.AddError(cerror.ErrorText + "Line " + cerror.Line + " " + cerror.Column + " in \"" + tomoSource + "\"", cerror.Line, cerror.Column); return; } } } }
public List<ProgramError> Compile() { List<ProgramError> errors = new List<ProgramError>(); // check for output directory if (!Directory.Exists(Path.GetDirectoryName(AssemblyFile))) { Directory.CreateDirectory(Path.GetDirectoryName(AssemblyFile)); } // dispose assembly and interrupt current task (if any) programBlock.IsEnabled = false; // clean up old assembly files try { if (File.Exists(this.AssemblyFile)) { File.Delete(this.AssemblyFile); } if (File.Exists(this.AssemblyFile + ".mdb")) { File.Delete(this.AssemblyFile + ".mdb"); } if (File.Exists(this.AssemblyFile.Replace(".dll", ".mdb"))) { File.Delete(this.AssemblyFile.Replace(".dll", ".mdb")); } if (File.Exists(this.AssemblyFile + ".pdb")) { File.Delete(this.AssemblyFile + ".pdb"); } if (File.Exists(this.AssemblyFile.Replace(".dll", ".pdb"))) { File.Delete(this.AssemblyFile.Replace(".dll", ".pdb")); } } catch (Exception ee) { HomeGenieService.LogError(ee); } // DO NOT CHANGE THE FOLLOWING LINES OF CODE // it is a lil' trick for mono compatibility // since it will be caching the assembly when using the same name // and use the old one instead of the new one string tmpfile = Path.Combine("programs", Guid.NewGuid().ToString() + ".dll"); System.CodeDom.Compiler.CompilerResults result = new System.CodeDom.Compiler.CompilerResults(null); try { result = CSharpAppFactory.CompileScript(programBlock.ScriptCondition, programBlock.ScriptSource, tmpfile); } catch (Exception ex) { // report errors during post-compilation process result.Errors.Add(new System.CodeDom.Compiler.CompilerError(programBlock.Name, 0, 0, "-1", ex.Message)); } if (result.Errors.Count > 0) { int sourceLines = programBlock.ScriptSource.Split('\n').Length; foreach (System.CodeDom.Compiler.CompilerError error in result.Errors) { int errorRow = (error.Line - CSharpAppFactory.PROGRAM_CODE_OFFSET); string blockType = "CR"; if (errorRow >= sourceLines + CSharpAppFactory.CONDITION_CODE_OFFSET) { errorRow -= (sourceLines + CSharpAppFactory.CONDITION_CODE_OFFSET); blockType = "TC"; } if (!error.IsWarning) { errors.Add(new ProgramError() { Line = errorRow, Column = error.Column, ErrorMessage = error.ErrorText, ErrorNumber = error.ErrorNumber, CodeBlock = blockType }); } else { var warning = String.Format("{0},{1},{2}: {3}", blockType, errorRow, error.Column, error.ErrorText); homegenie.ProgramManager.RaiseProgramModuleEvent(programBlock, Properties.COMPILER_WARNING, warning); } } } if (errors.Count == 0) { // move/copy new assembly files // rename temp file to production file appAssembly = result.CompiledAssembly; try { //string tmpfile = new Uri(value.CodeBase).LocalPath; File.Move(tmpfile, this.AssemblyFile); if (File.Exists(tmpfile + ".mdb")) { File.Move(tmpfile + ".mdb", this.AssemblyFile + ".mdb"); } if (File.Exists(tmpfile.Replace(".dll", ".mdb"))) { File.Move(tmpfile.Replace(".dll", ".mdb"), this.AssemblyFile.Replace(".dll", ".mdb")); } if (File.Exists(tmpfile + ".pdb")) { File.Move(tmpfile + ".pdb", this.AssemblyFile + ".pdb"); } if (File.Exists(tmpfile.Replace(".dll", ".pdb"))) { File.Move(tmpfile.Replace(".dll", ".pdb"), this.AssemblyFile.Replace(".dll", ".pdb")); } } catch (Exception ee) { HomeGenieService.LogError(ee); } } return errors; }
public int GenerateTest() { System.CodeDom.Compiler.CompilerParameters parameters = new System.CodeDom.Compiler.CompilerParameters (); parameters.GenerateExecutable = true; parameters.GenerateInMemory = false; parameters.IncludeDebugInformation = false; parameters.MainClass = namespaceName + "." + appName; parameters.OutputAssembly = appName + ".exe"; string code = GetCode (); System.CodeDom.Compiler.ICodeCompiler compiler = new Microsoft.CSharp.CSharpCodeProvider ().CreateCompiler (); compilerResult = compiler.CompileAssemblyFromSource (parameters, code); if (compilerResult.NativeCompilerReturnValue == 0) { appPath = System.IO.Directory.GetCurrentDirectory (); } else { appPath = ""; } return compilerResult.NativeCompilerReturnValue; }
private List<ProgramError> CompileCsharp(ProgramBlock program) { List<ProgramError> errors = new List<ProgramError>(); // check for output directory if (!Directory.Exists(Path.GetDirectoryName(program.AssemblyFile))) { Directory.CreateDirectory(Path.GetDirectoryName(program.AssemblyFile)); } // dispose assembly and interrupt current task (if any) program.AppAssembly = null; program.IsEnabled = false; // DO NOT CHANGE THE FOLLOWING LINES OF CODE // it is a lil' trick for mono compatibility // since it will be caching the assembly when using the same name // and use the old one instead of the new one string tmpfile = Path.Combine("programs", Guid.NewGuid().ToString() + ".dll"); System.CodeDom.Compiler.CompilerResults result = new System.CodeDom.Compiler.CompilerResults(null); try { result = CSharpAppFactory.CompileScript(program.ScriptCondition, program.ScriptSource, tmpfile); } catch (Exception ex) { // report errors during post-compilation process result.Errors.Add(new System.CodeDom.Compiler.CompilerError(program.Name, 0, 0, "-1", ex.Message)); } if (result.Errors.Count > 0) { int sourceLines = program.ScriptSource.Split('\n').Length; foreach (System.CodeDom.Compiler.CompilerError error in result.Errors) { int errorRow = (error.Line - CSharpAppFactory.PROGRAM_CODE_OFFSET); string blockType = "CR"; if (errorRow >= sourceLines + CSharpAppFactory.CONDITION_CODE_OFFSET) { errorRow -= (sourceLines + CSharpAppFactory.CONDITION_CODE_OFFSET); blockType = "TC"; } if (!error.IsWarning) { errors.Add(new ProgramError() { Line = errorRow, Column = error.Column, ErrorMessage = error.ErrorText, ErrorNumber = error.ErrorNumber, CodeBlock = blockType }); } else { var warning = String.Format("{0},{1},{2}: {3}", blockType, errorRow, error.Column, error.ErrorText); RaiseProgramModuleEvent(program, Properties.COMPILER_WARNING, warning); } } } if (errors.Count == 0) { program.AppAssembly = result.CompiledAssembly; } return errors; }
private void Poloniex(IAsyncResult Result) { try { //RequestState myRequestState = (RequestState)Result.AsyncState; HttpWebRequest myHttpWebRequest = (HttpWebRequest)Result.AsyncState; HttpWebResponse response = (HttpWebResponse)myHttpWebRequest.EndGetResponse(Result); string sEmitResponse = new StreamReader(response.GetResponseStream()).ReadToEnd(); if ((DateTime.Now-LastClassUpdate).TotalSeconds>(24.0*60.0*60.0)) { LastClassUpdate = DateTime.Today; string s = sEmitResponse; string[] parts = s.Split(new string[] { "BTC_" }, StringSplitOptions.RemoveEmptyEntries); List<string> Names = new List<string>(); foreach (string t in parts) { Names.Add(t.Substring(0, t.IndexOf("\""))); } string outs = "using CryptoPriceCore; namespace poloniex { public class poloniexMarket\n{\n"; foreach (string t in Names) { if (t != "{") outs += "public PoloniexPair BTC_" + t + " { get; set; }\n"; } outs += @"public static poloniexMarket CreateFromString(string msg) { return CryptoPriceCore.json.JsonDeserialize<poloniexMarket>(msg); } } }"; //update classes tmpRes = tmp.CompileAssemblyFromSource( new System.CodeDom.Compiler.CompilerParameters() { GenerateInMemory = true, GenerateExecutable = false, ReferencedAssemblies = { "CryptoPriceCore.dll" } }, outs); } //Currencies = json.JsonDeserialize<poloniexMarket>(sEmitResponse.Replace("return", "returns")); Type[] tps = tmpRes.CompiledAssembly.GetTypes(); Type x = tmpRes.CompiledAssembly.GetType("poloniex.poloniexMarket", true); Currencies = x.GetMethod("CreateFromString").Invoke(null, new object[] { sEmitResponse.Replace("return", "returns") }); } catch { } PolDone = true; TriggerEvent(); }