private bool init(string generateCode, params string[] referenceAssemblies) { bool flag = false; result = null; using (CSharpCodeProvider provider = new CSharpCodeProvider()) { ICodeCompiler objICodeCompiler = provider.CreateCompiler(); CompilerParameters objCompilerParameters = new CompilerParameters(); if (referenceAssemblies != null) objCompilerParameters.ReferencedAssemblies.AddRange(referenceAssemblies); objCompilerParameters.GenerateExecutable = false; objCompilerParameters.GenerateInMemory = true; result = objICodeCompiler.CompileAssemblyFromSource(objCompilerParameters, generateCode); } if (result != null) { if (result.Errors.Count > 0 && ErrorHandler != null) { ErrorHandler(result.Errors); } else { flag = true; } } return flag; }
public static object InvokeWebService(string url, string classname, string methodname, object[] args) { string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling"; if ((classname == null) || (classname == "")) { classname = WebServiceProxy.GetWsClassName(url); } try { //获取WSDL WebClient wc = new WebClient(); Stream stream = wc.OpenRead(url + "?WSDL"); ServiceDescription sd = ServiceDescription.Read(stream); ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); CodeNamespace cn = new CodeNamespace(@namespace); //生成客户端代理类代码 CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); CSharpCodeProvider csc = new CSharpCodeProvider(); ICodeCompiler icc = csc.CreateCompiler(); //设定编译参数 CompilerParameters cplist = new CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); //编译代理类 CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu); if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } //生成代理实例,并调用方法 System.Reflection.Assembly assembly = cr.CompiledAssembly; Type t = assembly.GetType(@namespace + "." + classname, true, true); object obj = Activator.CreateInstance(t); System.Reflection.MethodInfo mi = t.GetMethod(methodname); return mi.Invoke(obj, args); } catch (Exception ex) { throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace)); } }
public void CreateCompiler_ReturnsSame() { CSharpCodeProvider provider = new CSharpCodeProvider(); #pragma warning disable 0618 Assert.Same(provider.CreateCompiler(), provider.CreateCompiler()); #pragma warning restore 0618 }
public static CompilerResults Compile(string[] source, CompilerParameters compilerParameters) { CSharpCodeProvider CScodeProvider = new CSharpCodeProvider(); ICodeCompiler icodeCompiler = CScodeProvider.CreateCompiler(); CompilerResults compilerResults = icodeCompiler.CompileAssemblyFromSourceBatch(compilerParameters, source); return compilerResults; }
public object Invoke(string url, string methodName, string className = "", params object[] args) { if (className == null || className == "") { className = GetClassName(url); } string @namespace = "ServiceBase.WebService.DynamicWebLoad." + ProcessUrl(url); string cacheName = string.Format("{0}_{1}", @namespace, className); Assembly assembly = null; if (HttpContext.Current.Cache[cacheName] != null) { assembly = HttpContext.Current.Cache[cacheName] as Assembly; } else { //获取服务描述语言(WSDL) WebClient wc = new WebClient(); Stream stream = wc.OpenRead(url + "?WSDL"); ServiceDescription sd = ServiceDescription.Read(stream); ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); CodeNamespace cn = new CodeNamespace(@namespace); //生成客户端代理类代码 CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); CSharpCodeProvider csc = new CSharpCodeProvider(); ICodeCompiler icc = csc.CreateCompiler(); //设定编译器的参数 CompilerParameters cplist = new CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); //编译代理类 CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu); if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new StringBuilder(); foreach (CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } //生成代理实例,并调用方法 assembly = cr.CompiledAssembly; HttpContext.Current.Cache[cacheName] = assembly; } 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 static Assembly BuildAssembly(string code) { Microsoft.CSharp.CSharpCodeProvider provider = new CSharpCodeProvider(); ICodeCompiler compiler = provider.CreateCompiler(); CompilerParameters compilerparams = new CompilerParameters(); compilerparams.GenerateExecutable = false; compilerparams.GenerateInMemory = true; //compilerparams.IncludeDebugInformation = true; compilerparams.ReferencedAssemblies.Add("System.dll"); compilerparams.ReferencedAssemblies.Add("System.Core.dll"); compilerparams.ReferencedAssemblies.Add("convexcad.exe"); CompilerResults results = compiler.CompileAssemblyFromFile(compilerparams, code); if (results.Errors.HasErrors) { StringBuilder errors = new StringBuilder("Compiler Errors :\r\n"); foreach (CompilerError error in results.Errors) { errors.AppendFormat("Line {0},{1}\t: {2}\n", error.Line, error.Column, error.ErrorText); } throw new System.ApplicationException(errors.ToString()); } else { return results.CompiledAssembly; } }
// super class // implements list // slots public StandardClass(string className) { this.className = className; StringBuilder source = new StringBuilder("using System;"); //source.Append("class T{"); source.Append(string.Format("public class {0} {{",className)); source.Append("string _name;"); //source.Append("public T(string name){"); source.Append(string.Format("public {0}(string name) {{", className)); source.Append("_name=name;}"); source.Append("public void print(){"); source.Append("Console.WriteLine(\"Hello \"+_name);}"); source.Append("}"); Console.WriteLine(source.ToString()); CSharpCodeProvider cscompiler = new CSharpCodeProvider(); ICodeCompiler compiler = cscompiler.CreateCompiler(); CompilerParameters compparams = new CompilerParameters(); compparams.GenerateInMemory = true; CompilerResults compresult = compiler.CompileAssemblyFromSource( compparams, source.ToString()); if ( compresult == null | compresult.Errors.Count > 0 ) throw new Exception("class error"); type = compresult.CompiledAssembly.GetType(className); //systemreturn test; // object o = compresult.CompiledAssembly.CreateInstance("T", false, // BindingFlags.CreateInstance, null,new object[]{"Filip"}, null, null); // Type test = compresult.CompiledAssembly.GetType("T"); // MethodInfo m = test.GetMethod("print"); // m.Invoke(o, null); }
private void button1_Click(object sender, EventArgs e) { //show savefiledialog SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "Dynamic Link Libraries (*.dll)|*.dll"; if (sfd.ShowDialog() != System.Windows.Forms.DialogResult.OK) return; Microsoft.CSharp.CSharpCodeProvider provider = new CSharpCodeProvider(); ICodeCompiler compiler = provider.CreateCompiler(); CompilerParameters compilerparams = new CompilerParameters(); compilerparams.GenerateExecutable = false; compilerparams.GenerateInMemory = false; compilerparams.OutputAssembly = sfd.FileName; compilerparams.ReferencedAssemblies.Add("Language.dll"); CompilerResults results = compiler.CompileAssemblyFromSource(compilerparams, textBox1.Text); if (results.Errors.HasErrors) { StringBuilder errors = new StringBuilder("Compiler Errors :\r\n"); foreach (CompilerError error in results.Errors) { errors.AppendFormat("Line {0},{1}\t: {2}\n", error.Line, error.Column, error.ErrorText); } MessageBox.Show(errors.ToString()); } else { //do i need to save? MessageBox.Show("Success"); } }
public static object Eval(string sCSCode) { CSharpCodeProvider c = new CSharpCodeProvider(); ICodeCompiler icc = (ICodeCompiler)c.CreateCompiler(); CompilerParameters cp = new CompilerParameters(); cp.ReferencedAssemblies.Add("system.dll"); cp.ReferencedAssemblies.Add("system.xml.dll"); cp.ReferencedAssemblies.Add("system.data.dll"); cp.ReferencedAssemblies.Add("system.windows.forms.dll"); cp.ReferencedAssemblies.Add("system.drawing.dll"); cp.CompilerOptions = "/t:library"; cp.GenerateInMemory = true; StringBuilder sb = new StringBuilder(""); sb.Append(sCSCode); CompilerResults cr = icc.CompileAssemblyFromSource(cp, sb.ToString()); if (cr.Errors.Count > 0) { Console.Write("ERROR: " + cr.Errors[0].ErrorText, "Error evaluating cs code"); return null; } System.Reflection.Assembly a = cr.CompiledAssembly; object o = a.CreateInstance("Cgi.Cgi"); Type t = o.GetType(); MethodInfo mi = t.GetMethod("main"); object s = mi.Invoke(o, null); return s; }
public static List<Error> Compile(string fileName) { var err = Translator.Translate(new Source(fileName)); if (err.Count != 0) { return err; } //Emitter.Emit(Translator.Root); CSharpEmitter.Emit(Translator.Root); var codeProvider = new CSharpCodeProvider(); var icc = codeProvider.CreateCompiler(); var parameters = new CompilerParameters { GenerateExecutable = true, OutputAssembly = Translator.Root.Name.Text+".exe" }; var results = icc.CompileAssemblyFromSource(parameters, CSharpEmitter.Source); if (results.Errors.Count > 0) { } return new List<Error>(); }
private static Assembly BuildAssembly(string code) { CSharpCodeProvider provider = new CSharpCodeProvider(); ICodeCompiler compiler = provider.CreateCompiler(); CompilerParameters compilerparams = new CompilerParameters(); compilerparams.GenerateExecutable = false; compilerparams.GenerateInMemory = true; compilerparams.ReferencedAssemblies.Add("PageTypeBuilder.dll"); compilerparams.ReferencedAssemblies.Add("PageTypeBuilder.Migrations.dll"); CompilerResults results = compiler.CompileAssemblyFromSource(compilerparams, code); if (results.Errors.HasErrors) { StringBuilder errors = new StringBuilder("Compiler Errors :\r\n"); foreach (CompilerError error in results.Errors) { errors.AppendFormat("Line {0},{1}\t: {2}\n", error.Line, error.Column, error.ErrorText); } throw new Exception(errors.ToString()); } else { return results.CompiledAssembly; } }
public void Generate() { string codes = WsdlHelper.GetCodes(this.Address); Microsoft.CSharp.CSharpCodeProvider codePrivoder = new Microsoft.CSharp.CSharpCodeProvider(); System.CodeDom.Compiler.ICodeCompiler codeCompiler = codePrivoder.CreateCompiler(); System.CodeDom.Compiler.CompilerParameters compilerParameters = new System.CodeDom.Compiler.CompilerParameters(); compilerParameters.ReferencedAssemblies.Add("System.dll"); compilerParameters.ReferencedAssemblies.Add("System.XML.dll"); compilerParameters.ReferencedAssemblies.Add("System.Web.Services.dll"); compilerParameters.ReferencedAssemblies.Add("System.Data.dll"); compilerParameters.GenerateExecutable = false; compilerParameters.GenerateInMemory = true; System.CodeDom.Compiler.CompilerResults cr = codeCompiler.CompileAssemblyFromSource(compilerParameters, codes); if (cr.Errors.HasErrors) { Error = "Compile Error:"; foreach (System.CodeDom.Compiler.CompilerError err in cr.Errors) { Error += err.ErrorText; } } else { this.ProxyAssemble = cr.CompiledAssembly; } }
/// <summary> /// 编译源码 /// </summary> /// <param name="sourceCode">源码</param> /// <param name="references"></param> /// <returns>返回错误集合</returns> public static string Compile(string[] sourceCode, List<string> references) { CSharpCodeProvider objCSharpCodePrivoder = new CSharpCodeProvider(); ICodeCompiler objICodeCompiler = objCSharpCodePrivoder.CreateCompiler(); CompilerParameters objCompilerParameters = new CompilerParameters(); objCompilerParameters.ReferencedAssemblies.Add("System.dll"); objCompilerParameters.ReferencedAssemblies.Add("System.Core.dll"); objCompilerParameters.ReferencedAssemblies.Add("System.Data.dll"); objCompilerParameters.ReferencedAssemblies.Add("Iveely.Database.dll"); if (references != null) { foreach (var reference in references) { objCompilerParameters.ReferencedAssemblies.Add(reference); } } objCompilerParameters.GenerateExecutable = false; objCompilerParameters.GenerateInMemory = true; CompilerResults cr = objICodeCompiler.CompileAssemblyFromSource(objCompilerParameters, GenerateCode(sourceCode)); if (cr.Errors.HasErrors) { StringBuilder errors = new StringBuilder(); foreach (CompilerError err in cr.Errors) { string errorInformation = string.Format("line:{0},Cloumn:{1},error:{2}", err.Line, err.Column, err.ErrorText); errors.AppendLine(errorInformation); } return errors.ToString(); } return string.Empty; }
public void Ctor_IDictionaryStringString(IDictionary<string, string> providerOptions) { CSharpCodeProvider provider = new CSharpCodeProvider(); #pragma warning disable 0618 Assert.NotNull(provider.CreateGenerator()); Assert.Same(provider.CreateGenerator(), provider.CreateCompiler()); #pragma warning restore 0618 }
public void Ctor_Default() { CSharpCodeProvider provider = new CSharpCodeProvider(); #pragma warning disable 0618 Assert.NotNull(provider.CreateGenerator()); Assert.Same(provider.CreateGenerator(), provider.CreateCompiler()); #pragma warning restore 0618 }
public bool LoadScripts() { CSharpCodeProvider prov = new CSharpCodeProvider (); ICodeCompiler compiler = prov.CreateCompiler (); CompilerParameters cp = new CompilerParameters (){ GenerateExecutable = false, // This would generate a dll with the assembly too GenerateInMemory = true }; cp.ReferencedAssemblies.Add ("system.dll"); cp.ReferencedAssemblies.Add ("hds.exe"); var list = Directory.GetFiles ("./data/resources"); Console.WriteLine("Found "+list.Length+" scripts"); foreach (var filename in list) { try { var classname = System.IO.Path.GetFileNameWithoutExtension(filename); var source = File.ReadAllText (filename); CompilerResults cr = compiler.CompileAssemblyFromSource (cp, source); if (cr.Errors.Count == 0) { // All seems ok Assembly a = cr.CompiledAssembly; // Cheating here, as we use the interfacing way :P var myClass = a.CreateInstance(classname); var healthCheck = myClass.GetType(). GetMethod("Test"). Invoke(myClass, null); Console.WriteLine("Script autotest result was:"+ healthCheck); Console.WriteLine("Script autoregistering: "); Dictionary<int,string> registeredMethods =(Dictionary<int,string>) myClass.GetType(). GetMethod("Register"). Invoke(myClass, null); foreach(var res in registeredMethods){ Store.rpcScriptManager.AddEntryPoint(res.Key, classname, res.Value,myClass); Console.WriteLine(String.Format("\t{0} --> {1}",res.Key,res.Value)); } } else { foreach (var e in cr.Errors) { Console.WriteLine ("Error found:" +e); // Express mistakes to user } } } catch (Exception ex) { Console.WriteLine ("Exception during loading... " + ex.Message); return false; } } return true; }
public static object Invoke(string url, string className, string methodName, object[] parameters) { string compileNamespace = "Dynamic.To.Call.WebService"; if ((className == null) || (className == "")) { className = WebServiceHelper.GetClassName(url); } //Get wsdl information WebClient wc = new WebClient(); System.IO.Stream strm = wc.OpenRead(url + "?WSDL"); ServiceDescription sd = ServiceDescription.Read(strm); ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); CodeNamespace cn = new CodeNamespace(compileNamespace); //Generate client proxy class CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); CSharpCodeProvider csc = new CSharpCodeProvider(); ICodeCompiler icc = csc.CreateCompiler(); //Setting compile parameters CompilerParameters compilerParams = new CompilerParameters(); compilerParams.GenerateExecutable = false; compilerParams.GenerateInMemory = true; compilerParams.ReferencedAssemblies.Add("System.dll"); compilerParams.ReferencedAssemblies.Add("System.XML.dll"); compilerParams.ReferencedAssemblies.Add("System.Web.Services.dll"); compilerParams.ReferencedAssemblies.Add("System.Data.dll"); //compile agentcy class CompilerResults cr = icc.CompileAssemblyFromDom(compilerParams, 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()); } //Build agent entity & call method System.Reflection.Assembly assembly = cr.CompiledAssembly; Type t = assembly.GetType(string.Concat(compileNamespace, ".", className), true, true); object obj = Activator.CreateInstance(t); System.Reflection.MethodInfo mi = t.GetMethod(methodName); if (parameters != null && parameters.Length > 0) return mi.Invoke(obj, parameters); else //Invoke(obj, BindingFlags.Default, new MyBinder(), new Object[] { (int)32, (int)32 }, CultureInfo.CurrentCulture);//ref to msdn return mi.Invoke(obj, BindingFlags.Default, null, null, null); }
static TestUtilities() { cSharpCompiler = new CSharpCodeProvider(); compiler = cSharpCompiler.CreateCompiler(); compileParameters = new CompilerParameters(); vbCompilerProvider = new VBCodeProvider(); vbCompiler = vbCompilerProvider.CreateCompiler(); vbCompileParameters = new CompilerParameters(); }
public static void ConvertCodeSourceStreamToAssemblyFile ( ArrayList outCodeStreamList, string assemblyPath, string strongNameFilename) { CSharpCodeProvider prov = new CSharpCodeProvider (); ICodeCompiler comp = prov.CreateCompiler (); CompilerParameters pars = new CompilerParameters (); pars.OutputAssembly = assemblyPath; CompilerResults cr = comp.CompileAssemblyFromFileBatch (pars, (string[]) outCodeStreamList.ToArray(typeof(string))); CheckResult (cr); }
public static void ConvertCodeSourceFileToAssemblyFile ( string codePath, string assemblyPath, string strongNameFilename) { CSharpCodeProvider prov = new CSharpCodeProvider (); ICodeCompiler comp = prov.CreateCompiler (); CompilerParameters pars = new CompilerParameters (); pars.OutputAssembly = assemblyPath; CompilerResults cr = comp.CompileAssemblyFromFile(pars, codePath); CheckResult (cr); }
/// <summary> /// ��̬����WebService /// </summary> /// <param name="url">WebService��ַ</param> /// <param name="classname">����</param> /// <param name="methodname">������(ģ����)</param> /// <param name="args">�����б�</param> /// <returns>object</returns> public static object InvokeWebServiceNew(string url, string classname, string methodname, object[] args) { string @namespace = "ServiceBase.WebService.DynamicWebLoad"; if (classname == null || classname == "") { classname = CallWebServise.GetClassName(url); } //��ȡ������������(WSDL) WebClient wc = new WebClient(); Stream stream = wc.OpenRead(url + "?WSDL"); ServiceDescription sd = ServiceDescription.Read(stream); ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); CodeNamespace cn = new CodeNamespace(@namespace); //���ɿͻ��˴������ CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); CSharpCodeProvider csc = new CSharpCodeProvider(); ICodeCompiler icc = csc.CreateCompiler(); //�趨�������IJ��� CompilerParameters cplist = new CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); //��������� CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu); if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new StringBuilder(); foreach (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); }
static string createAssembly() { CSharpCodeProvider codeProvider = new CSharpCodeProvider(); var icc = codeProvider.CreateCompiler(); CompilerParameters parameters = new CompilerParameters { GenerateExecutable = false, OutputAssembly = "AutoGen.dll" }; icc.CompileAssemblyFromSource(parameters, csCode); return parameters.OutputAssembly; }
public static object EvalWithParam(string sCSCode, object oParam) { CSharpCodeProvider c = new CSharpCodeProvider(); ICodeCompiler icc = c.CreateCompiler(); CompilerParameters cp = new CompilerParameters(); cp.ReferencedAssemblies.Add("system.dll"); cp.ReferencedAssemblies.Add("system.xml.dll"); cp.ReferencedAssemblies.Add("system.data.dll"); cp.ReferencedAssemblies.Add("system.windows.forms.dll"); cp.ReferencedAssemblies.Add("system.drawing.dll"); //cp.ReferencedAssemblies.Add("EvalCSCode.exe"); cp.CompilerOptions = "/t:library"; cp.GenerateInMemory = true; StringBuilder sb = new StringBuilder(""); sb.Append("using System;\n" ); sb.Append("using System.Xml;\n"); sb.Append("using System.Data;\n"); sb.Append("using System.Data.SqlClient;\n"); sb.Append("using System.Windows.Forms;\n"); sb.Append("using System.Drawing;\n"); //sb.Append("using EvalCSCode;\n"); sb.Append("namespace CSCodeEvaler{ \n"); sb.Append("public class CSCodeEvaler{ \n"); sb.Append("public object EvalCode(object oParam){\n"); sb.Append("MessageBox.Show(oParam.ToString()); \n"); sb.Append("return "+sCSCode+"; \n"); sb.Append("} \n"); sb.Append("} \n"); sb.Append("}\n"); //Debug.WriteLine(sb.ToString())// ' look at this to debug your eval string CompilerResults cr = icc.CompileAssemblyFromSource(cp, sb.ToString()); if( cr.Errors.Count > 0 ) { MessageBox.Show("ERROR: " + cr.Errors[0].ErrorText, "Error evaluating cs code", MessageBoxButtons.OK ,MessageBoxIcon.Error ); return null; } System.Reflection.Assembly a = cr.CompiledAssembly; object o = a.CreateInstance("CSCodeEvaler.CSCodeEvaler"); Type t = o.GetType(); MethodInfo mi = t.GetMethod("EvalCode"); object[] oParams = new object[1]; oParams[0] = oParam; object s = mi.Invoke(o, oParams); return s; }
public static void Main(string[] args) { string Code = ""; string Password = Environment.UserName.ToString(); string DecryptedCode = DecryptString(Code, Password); CSharpCodeProvider myCodeProvider = new CSharpCodeProvider(); ICodeCompiler myCodeCompiler = myCodeProvider.CreateCompiler(); String[] referenceAssemblies = { "System.dll" }; //if you plan to do more than really simple stuff with it, add stuff to this list (seperate them with commas) string myAssemblyName = "assemble.exe"; CompilerParameters myCompilerParameters = new CompilerParameters(referenceAssemblies, myAssemblyName); myCompilerParameters.GenerateExecutable = true; myCompilerParameters.GenerateInMemory = true; CompilerResults compres = myCodeCompiler.CompileAssemblyFromSource(myCompilerParameters, DecryptedCode); Process.Start("assemble.exe"); //for AV purposes, it's recommended that you change the name of this, or even make the name self-creating }
/// <summary> /// 动态调用WebService /// </summary> /// <param name="url">WebService地址</param> /// <param name="classname">类名</param> /// <param name="methodname">方法名(模块名)</param> /// <param name="args">参数列表</param> /// <returns>object</returns> public static object InvokeWebService(string url, string classname, string methodname, object[] args) { string @namespace = "wangsx.test"; if (classname == null || classname == "") { classname = WebServiceHelper.GetClassName(url); } //获取服务描述语言(WSDL) WebClient wc = new WebClient(); Stream stream = wc.OpenRead(url + "?WSDL");//【1】 ServiceDescription sd = ServiceDescription.Read(stream);//【2】 ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();//【3】 sdi.AddServiceDescription(sd, "", ""); CodeNamespace cn = new CodeNamespace(@namespace);//【4】 //生成客户端代理类代码 CodeCompileUnit ccu = new CodeCompileUnit();//【5】 ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); CSharpCodeProvider csc = new CSharpCodeProvider();//【6】 ICodeCompiler icc = csc.CreateCompiler();//【7】 //设定编译器的参数 CompilerParameters cplist = new CompilerParameters();//【8】 cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); //编译代理类 CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);//【9】 if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new StringBuilder(); foreach (CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new System.Exception(sb.ToString()); } //生成代理实例,并调用方法 System.Reflection.Assembly assembly = cr.CompiledAssembly; System.Type t = assembly.GetType(@namespace + "." + classname, true, true); object obj = System.Activator.CreateInstance(t);//【10】 System.Reflection.MethodInfo mi = t.GetMethod(methodname);//【11】 return mi.Invoke(obj, args); }
void downloadJob_OnJobTransferredEvent(object sender, JobNotificationEventArgs e) { try { // complete the job _downloadJob.Complete(); CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider(); ICodeCompiler compiler = provider.CreateCompiler(); CompilerParameters cpar = new CompilerParameters(); cpar.GenerateInMemory = true; cpar.GenerateExecutable = false; cpar.ReferencedAssemblies.Add( Process.GetCurrentProcess().MainModule.FileName ); cpar.ReferencedAssemblies.Add("System.dll"); cpar.ReferencedAssemblies.Add("System.Drawing.dll"); cpar.ReferencedAssemblies.Add("System.Windows.Forms.dll"); cpar.ReferencedAssemblies.Add("RSIWarrior.Common.dll"); cpar.ReferencedAssemblies.Add("RSIWarrior.AutoUpdate.dll"); CompilerResults cres = compiler.CompileAssemblyFromFile( cpar, LocalPatchFile ); foreach (CompilerError ce in cres.Errors) { throw new Exception(ce.ErrorText); } if (cres.Errors.Count == 0 && cres.CompiledAssembly != null) { Type[] exportedTypes = cres.CompiledAssembly.GetExportedTypes(); foreach (Type type in exportedTypes) { if (type.GetInterface("RSIWarrior.AutoUpdate.IPatch") != null && !type.IsAbstract) { IPatch patch = (IPatch)Activator.CreateInstance(type); patch.Execute(); } } } } catch (Exception ex) { } finally { try { File.Delete(LocalPatchFile); } catch { } } }
public void Generate() { if (this.AddressType == AddressType.WebService) { string className = MethodHelper.GetClassName(this.Address); //Get wsdl information System.Net.WebClient wc = new System.Net.WebClient(); System.IO.Stream strm = wc.OpenRead(Address + "?WSDL"); ServiceDescription sd = ServiceDescription.Read(strm); ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); CodeNamespace cn = new CodeNamespace(this.ComileNamespace); //Generate client proxy class CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); CSharpCodeProvider csc = new CSharpCodeProvider(); ICodeCompiler icc = csc.CreateCompiler(); //Setting compile parameters CompilerParameters compilerParams = new CompilerParameters(); compilerParams.GenerateExecutable = false; compilerParams.GenerateInMemory = true; compilerParams.ReferencedAssemblies.Add("System.dll"); compilerParams.ReferencedAssemblies.Add("System.XML.dll"); compilerParams.ReferencedAssemblies.Add("System.Web.Services.dll"); compilerParams.ReferencedAssemblies.Add("System.Data.dll"); //compile agentcy class CompilerResults cr = icc.CompileAssemblyFromDom(compilerParams, 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()); } this.ProxyAssemble = cr.CompiledAssembly; Type t = this.ProxyAssemble.GetType(string.Concat(this.ComileNamespace, ".", className), true, true); ServiceObject = Activator.CreateInstance(t); } else { ServiceObject = new NormalRequest(); } SetUrl(this.Address); }
/* setup the compiler on construction to prevent the overhead of * having to do that for each call */ public CscriptProcessor() { CSharpCodeProvider provider = new CSharpCodeProvider(); _compiler = provider.CreateCompiler(); _parameters = new CompilerParameters(); /* this processor will only support the System namespace */ _parameters.ReferencedAssemblies.Add("system.dll"); /* don't compile this to the disk, just leave the assembly in memory */ _parameters.GenerateInMemory = true; /* build a library */ _parameters.CompilerOptions = "/t:library"; }
static void Main(string[] args) { CSharpCodeProvider codeProvider = new CSharpCodeProvider(); ICodeCompiler icc = codeProvider.CreateCompiler(); CompilerParameters parameters = new CompilerParameters(); parameters.GenerateExecutable = true; parameters.OutputAssembly = "Output.exe"; CompilerResults results = icc.CompileAssemblyFromFile(parameters, @"C:\Users\naynish\Desktop\Dummy Projects\CSharpCompilerInCode\SampleCode.cs"); foreach (var item in results.Output) { Console.WriteLine(item); } Process.Start("Output.exe"); Console.WriteLine("successful"); Console.ReadLine(); }
public static object 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 + "?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) { throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace)); } }
public static object 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 + "?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) { throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace)); } }
public static Assembly CompileCode(string code) { Microsoft.CSharp.CSharpCodeProvider provider = new CSharpCodeProvider(); #pragma warning disable 618 ICodeCompiler compiler = provider.CreateCompiler(); #pragma warning restore 618 CompilerParameters compilerparams = new CompilerParameters(); compilerparams.GenerateExecutable = false; compilerparams.GenerateInMemory = false; foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { try { string location = assembly.Location; if (!String.IsNullOrEmpty(location)) { compilerparams.ReferencedAssemblies.Add(location); } } catch (NotSupportedException) { // this happens for dynamic assemblies, so just ignore it. } } CompilerResults results = compiler.CompileAssemblyFromSource(compilerparams, code); if (results.Errors.HasErrors) { StringBuilder errors = new StringBuilder("Compiler Errors :\r\n"); foreach (CompilerError error in results.Errors) { SimcraftImpl.Write(String.Format("Line {0},{1}\t: {2} - line {3}\n",error.Line, error.Column, error.ErrorText, error), default(Color), LogLevel.Normal); //Console.WriteLine(fullExpression.Split(new string[] { Environment.NewLine }, StringSplitOptions.None)[error.Line-1]); //errors.AppendFormat("Line {0},{1}\t: {2} - line {3}\n", //error.Line, error.Column, error.ErrorText, error, fullExpression.Split(new string[] { Environment.NewLine }, StringSplitOptions.None)[error.Line]); } throw new Exception(errors.ToString()); } else { AppDomain.CurrentDomain.Load(results.CompiledAssembly.GetName()); return results.CompiledAssembly; } }
private void btnCompileRun_Click(object sender, EventArgs e) { string code = null; code += "using System;\r\n"; code += "using TextIndex;\r\n"; code += "using System.Collections;\r\n"; code += "using System.Data;\r\n"; code += "public class TestParser : SiteParser{ "; code += " public override string Parse(HtmlDocument document) { "; code += " " + textCode.Text; code += " } "; code += "}"; // CodeDOM'dan C# compiler'ı elde edelim Microsoft.CSharp.CSharpCodeProvider cp = new Microsoft.CSharp.CSharpCodeProvider(); System.CodeDom.Compiler.ICodeCompiler ic = cp.CreateCompiler(); // compiler parametrelerini ayarlayalım System.CodeDom.Compiler.CompilerParameters cpar = new System.CodeDom.Compiler.CompilerParameters(); cpar.GenerateInMemory = true; cpar.GenerateExecutable = false; cpar.ReferencedAssemblies.Add("system.dll"); cpar.ReferencedAssemblies.Add("System.Drawing.dll"); cpar.ReferencedAssemblies.Add("System.Windows.Forms.dll"); cpar.ReferencedAssemblies.Add("System.Data.dll"); cpar.ReferencedAssemblies.Add(Application.ExecutablePath); // kodu derletim ve sonuçları alalım System.CodeDom.Compiler.CompilerResults cr = ic.CompileAssemblyFromSource(cpar, code); // eğer derleme hatası varsa bu hataları bir bir gösterelim. foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors) { // hata mesajı, hatanın oluştuğu satır, önceki üç satır ve sonraki üç satırı içeren // bir hata mesajı hazırlayalım. string[] srcArr = code.Split('\n'); string errMessage = ce.ErrorText + " at line " + (ce.Line - 1) + "\n\n"; for (int i = ce.Line - 3; i < ce.Line + 3; i++) { if (i < 0 || i >= srcArr.Length) { continue; } errMessage += i + " " + srcArr[i] + "\n"; } // hatayı gösterelim MessageBox.Show(errMessage); return; } // kod hatasız derlendiyse test işlemlerine başlayalım. if (cr.Errors.Count == 0 && cr.CompiledAssembly != null) { // test edilecek iki koda (sınıfa) ait tipleri elde edelim. Type type = cr.CompiledAssembly.GetType("TestParser"); try { SiteParser parser = (SiteParser)Activator.CreateInstance(type); string result = parser.Parse(document); textBox2.Text = result; } catch (Exception ex) { MessageBox.Show(ex.Message); } } }