public object Execute(string method, params object[] args) { object obj2 = null; AppDomain domain = null; string str = "script_" + Guid.NewGuid().ToString(); try { StringBuilder sb = new StringBuilder(); StringWriter writer = new StringWriter(sb); foreach (string str2 in this.namespaces) { writer.WriteLine("using " + str2 + ";"); } writer.WriteLine(); writer.WriteLine("namespace CodeDomAssistant.Script {"); writer.WriteLine(" // Encapsulate Code Snippet Script"); writer.WriteLine(" public class CodeSnippet : MarshalByRefObject, IRemoteInterface {"); writer.WriteLine(" // Invoke Method Through IRemoteInterface"); writer.WriteLine(" public object Invoke(string method, object[] parms) {"); writer.WriteLine(" return this.GetType().InvokeMember(method, BindingFlags.InvokeMethod, null, this, parms);"); writer.WriteLine(" }"); writer.WriteLine(); writer.WriteLine(this.codesnippet); writer.WriteLine(" }"); writer.WriteLine("}"); writer.Flush(); writer.Close(); this.parameters.OutputAssembly = str + ".dll"; new CSharpCodeProvider().CompileAssemblyFromSource(this.parameters, new string[] { sb.ToString() }); AppDomainSetup info = new AppDomainSetup(); info.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; domain = AppDomain.CreateDomain("Scripting", null, info); RemoteLoaderFactory factory = (RemoteLoaderFactory)domain.CreateInstance("RemoteLoader", "RemoteLoader.RemoteLoaderFactory").Unwrap(); obj2 = factory.Create(str + ".dll", "CodeDomAssistant.Script.CodeSnippet", null).Invoke(method, args); } finally { if (domain != null) { AppDomain.Unload(domain); } if (File.Exists(str + ".dll")) { File.Delete(str + ".dll"); } } return(obj2); }
public static void MergeLocal(DataSet assemblydata, string assemblyfile, Progress progress) { DataRow row = null; bool flag = false; AppDomain domain = null; try { if (progress != null) { progress.Message = string.Format("Scanning DLL: {0}", Path.GetFileName(assemblyfile)); progress.Notify(); } AppDomainSetup info = new AppDomainSetup(); info.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; domain = AppDomain.CreateDomain("TestCodeDomProviders", null, info); RemoteLoaderFactory factory = (RemoteLoaderFactory)domain.CreateInstance("RemoteLoader", "RemoteLoader.RemoteLoaderFactory").Unwrap(); string assemblyName = factory.GetAssemblyName(assemblyfile); if (assemblyName != null) { flag = factory.IsSubclassOfCodeDomProvider(assemblyfile); DataRow[] rowArray = assemblydata.Tables[0].Select(string.Format("Path = '{0}'", assemblyfile)); if (rowArray.Length == 0) { row = assemblydata.Tables[0].NewRow(); } else { row = rowArray[0]; } row["Load"] = false; row["Name"] = assemblyName; row["Path"] = assemblyfile; row["IsGAC"] = false; row["HasProvider"] = flag; if (rowArray.Length == 0) { assemblydata.Tables[0].Rows.Add(row); } } } finally { if (domain != null) { AppDomain.Unload(domain); } } }
TaskResult DynamiclyDomain(string source) { var AssemblyName = "DynamicalCode"; var ClassName = "Dynamicly.HelloWorld"; var ActionName = "HelloWorld"; var AssemblyResult = DynamiclyCompiler(source, AssemblyName); if (AssemblyResult.Succeeded == false) { return(AssemblyResult); } if (System.IO.File.Exists($"{AppDomain.CurrentDomain.BaseDirectory}\\{AssemblyName}.dll") == false) { return(AssemblyResult.AddError($"Error:{AssemblyName} create fail! ")); } // 0. Create an addtional AppDomain AppDomainSetup objSetup = new AppDomainSetup(); objSetup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; AppDomain objAppDomain = AppDomain.CreateDomain("DynamiclyAppDomain", null, objSetup); // 1. Invoke the method by using Reflection RemoteLoaderFactory factory = (RemoteLoaderFactory)objAppDomain.CreateInstance("RemoteAccess", "RemoteAccess.RemoteLoaderFactory").Unwrap(); // with help of factory, create a real 'LiveClass' instance object objObject = factory.Create($"{AssemblyName}.dll", "Dynamicly.HelloWorld", null); if (objObject == null) { return(new TaskResult("Error: Couldn't load class.")); } // *** Cast object to remote interface, avoid loading type info IRemoteInterface objRemote = (IRemoteInterface)objObject; object[] objCodeParms = new object[1]; objCodeParms[0] = "Allan."; string strResult = (string)objRemote.Invoke("GetTime", objCodeParms); //Dispose the objects and unload the generated DLLs. objRemote = null; AppDomain.Unload(objAppDomain); System.IO.File.Delete("DynamicalCode.dll"); return(AssemblyResult); }
public object CreateInstance() { if (ObjRef != null) { return(ObjRef); } // *** Create an instance of the new object try { if (AppDomain == null) { try { ObjRef = Assembly.CreateInstance(AssemblyNamespace + "." + ClassName); return(ObjRef); } catch (Exception ex) { Error = true; ErrorMessage = ex.Message; return(null); } } else { #if useRemoteLoader // create the factory class in the secondary app-domain RemoteLoaderFactory factory = (RemoteLoaderFactory)this.oAppDomain.CreateInstance("RemoteLoader", "Westwind.RemoteLoader.RemoteLoaderFactory").Unwrap(); // with the help of this factory, we can now create a real 'LiveClass' instance this.oObjRef = factory.Create(this.cOutputAssembly, this.cAssemblyNamespace + "." + this.cClassName, null); return(this.oObjRef); #endif return(null); } } catch (Exception ex) { Error = true; ErrorMessage = ex.Message; return(null); } }
public static bool NewExcuteScriptCaseCode(string dllName, BLL.EM_SCRIPT_NODE_CASE.Entity nodeCase, List <KV> monitList, ref ErrorInfo err) { bool resBool = true; // string dllPath = dllName; // AppDomain ad = AppDomain.CurrentDomain; // ProxyObject obj = (ProxyObject)ad.CreateInstanceFromAndUnwrap(System.AppDomain.CurrentDomain.BaseDirectory + "Easyman.ScriptService.exe", "Easyman.ScriptService.Script.ProxyObject"); // obj.LoadAssembly(dllPath); // resBool=obj.Invoke("Easyman.ScriptService.Script.ScripRunner", nodeCase.ID, nodeCase.DB_SERVER_ID); //// AppDomain.Unload(ad); //DoAbsoluteDeleteFile(dllName, ref err); #region 原模式 AppDomain objAppDomain = null; IRemoteInterface objRemote = null; try { // 0. Create an addtional AppDomain //AppDomainSetup objSetup = new AppDomainSetup(); //objSetup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; //objAppDomain = AppDomain.CreateDomain("MyAppDomain", null, objSetup); objAppDomain = AppDomain.CreateDomain("Domain_" + DateTime.Now.Ticks.ToString());//.CurrentDomain; // 4. Invoke the method by using Reflection RemoteLoaderFactory factory = (RemoteLoaderFactory)objAppDomain.CreateInstance("Easyman.ScriptService", "RemoteAccess.RemoteLoaderFactory").Unwrap(); // with help of factory, create a real 'LiveClass' instance object objObject = factory.Create(dllName, "Easyman.ScriptService.Script.ScripRunner", null); if (objObject == null) { resBool = false; err.IsError = true; err.Message = "创建实例【Easyman.ScriptService.Script.ScripRunner】失败"; } // *** Cast object to remote interface, avoid loading type info objRemote = (IRemoteInterface)objObject; //初始化节点实例相关数据Initialize() objRemote.Invoke("SetScriptNodeCaseID", new object[] { nodeCase.ID }); //设置启动数据库编号 //objRemote.Invoke("setnowdbid", new object[] { nodeCase.DB_SERVER_ID }); //设置待拷贝文件编号 if (monitList != null && monitList.Count() > 0) { objRemote.Invoke("SetMonitFileList", new object[] { monitList.Select(p => p.K).ToList() }); } //运行脚本 objRemote.Invoke("Run", null); #region 获取错误信息GetErr() //外部job需要接收内部错误信息 //用于判断重试次数、用于是否再执行 var errorMsg = (string)objRemote.Invoke("GetErrorMessage", null); if (!string.IsNullOrEmpty(errorMsg.ToString())) { err.IsError = true; err.Message = errorMsg.ToString(); resBool = false; } else { var warnMsg = (string)objRemote.Invoke("GetWarnMessage", null); if (!string.IsNullOrEmpty(warnMsg.ToString())) { err.IsError = false; err.Message = warnMsg.ToString(); err.IsWarn = true; } } ////Dispose the objects and unload the generated DLLs. //objRemote = null; //AppDomain.Unload(objAppDomain); //System.IO.File.Delete(dllName); #endregion } catch (Exception ex) { resBool = false; err.IsError = true; err.Message = ex.Message; } finally { //Dispose the objects and unload the generated DLLs. //objRemote = null; AppDomain.Unload(objAppDomain); // System.IO.File.Delete(dllName); DoAbsoluteDeleteFile(dllName, ref err); } // BLL.EM_SCRIPT_NODE_CASE_LOG.Instance.Add(nodeCase.ID, 3, "执行错误:\r\n" + err.Message,""); #endregion return(resBool); }
public static void MergeGAC(DataSet assemblydata, bool refreshcache, Progress progress) { AppDomain domain = null; try { AppDomainSetup info = new AppDomainSetup(); info.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; domain = AppDomain.CreateDomain("FindCodeDomProviders", null, info); RemoteLoaderFactory factory = (RemoteLoaderFactory)domain.CreateInstance("RemoteLoader", "RemoteLoader.RemoteLoaderFactory").Unwrap(); foreach (string str2 in Directory.GetDirectories(Path.Combine(Environment.ExpandEnvironmentVariables("%windir%"), @"assembly\GAC"))) { if (progress != null) { progress.Message = string.Format("Scanning GAC: {0}", Path.GetFileName(str2)); progress.Notify(); } foreach (string str3 in Directory.GetDirectories(str2)) { foreach (string str4 in Directory.GetFiles(str3, "*.dll")) { DataRow[] rowArray = assemblydata.Tables[0].Select(string.Format("Path = '{0}'", str4)); if ((rowArray.Length == 0) || refreshcache) { string assemblyName = factory.GetAssemblyName(str4); if (assemblyName != null) { bool flag = factory.IsSubclassOfCodeDomProvider(str4); DataRow row = null; if (rowArray.Length == 0) { row = assemblydata.Tables[0].NewRow(); } else { row = rowArray[0]; } row = assemblydata.Tables[0].NewRow(); row["Load"] = false; row["Name"] = assemblyName; row["Path"] = str4; row["IsGAC"] = true; row["HasProvider"] = flag; if (rowArray.Length == 0) { assemblydata.Tables[0].Rows.Add(row); } } } } } } } finally { if (domain != null) { AppDomain.Unload(domain); } } }
private void button1_Click(object sender, EventArgs e) { // get the code to compile string strSourceCode = this.txtSource.Text; // 0. Create an addtional AppDomain AppDomainSetup objSetup = new AppDomainSetup(); objSetup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; AppDomain objAppDomain = AppDomain.CreateDomain("MyAppDomain", null, objSetup); // 1.Create a new CSharpCodePrivoder instance CSharpCodeProvider objCSharpCodePrivoder = new CSharpCodeProvider(); // 2.Sets the runtime compiling parameters by crating a new CompilerParameters instance CompilerParameters objCompilerParameters = new CompilerParameters(); objCompilerParameters.ReferencedAssemblies.Add("System.dll"); objCompilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll"); // Load the remote loader interface objCompilerParameters.ReferencedAssemblies.Add("RemoteAccess.dll"); // Load the resulting assembly into memory objCompilerParameters.GenerateInMemory = false; objCompilerParameters.OutputAssembly = "DynamicalCode.dll"; // 3.CompilerResults: Complile the code snippet by calling a method from the provider CompilerResults cr = objCSharpCodePrivoder.CompileAssemblyFromSource(objCompilerParameters, strSourceCode); if (cr.Errors.HasErrors) { string strErrorMsg = cr.Errors.Count.ToString() + " Errors:"; for (int x = 0; x < cr.Errors.Count; x++) { strErrorMsg = strErrorMsg + "/r/nLine: " + cr.Errors[x].Line.ToString() + " - " + cr.Errors[x].ErrorText; } this.txtResult.Text = strErrorMsg; MessageBox.Show("There were build erros, please modify your code.", "Compiling Error"); return; } // 4. Invoke the method by using Reflection RemoteLoaderFactory factory = (RemoteLoaderFactory)objAppDomain.CreateInstance("RemoteAccess", "RemoteAccess.RemoteLoaderFactory").Unwrap(); // with help of factory, create a real 'LiveClass' instance object objObject = factory.Create("DynamicalCode.dll", "Dynamicly.HelloWorld", null); if (objObject == null) { this.txtResult.Text = "Error: " + "Couldn't load class."; return; } // *** Cast object to remote interface, avoid loading type info IRemoteInterface objRemote = (IRemoteInterface)objObject; object[] objCodeParms = new object[1]; objCodeParms[0] = "Allan."; string strResult = (string)objRemote.Invoke("GetTime", objCodeParms); this.txtResult.Text = strResult; //Dispose the objects and unload the generated DLLs. objRemote = null; AppDomain.Unload(objAppDomain); System.IO.File.Delete("DynamicalCode.dll"); }
public object[] Execute(string text, string connectionString, string provider, string providerMetaData, string namespaces, bool parseOnly) { string assemblyName = "esQuerySandbox_Dynamic.dll"; AppDomain loAppDomain = null; IRemoteInterface loRemote = null; object loResult = null; try { // ** Create an AppDomain AppDomainSetup loSetup = new AppDomainSetup(); loSetup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; loSetup.ConfigurationFile = "esQuerySandbox.redirect.config"; loAppDomain = AppDomain.CreateDomain("MyAppDomain", null, loSetup); string code = GetSnippet(text, connectionString, provider, providerMetaData, namespaces, parseOnly); CodeDomProvider compiler = new CSharpCodeProvider(); CompilerParameters parameters = new CompilerParameters(); // *** Start by adding any referenced assemblies parameters.ReferencedAssemblies.Add("System.dll"); parameters.ReferencedAssemblies.Add("System.Xml.dll"); parameters.ReferencedAssemblies.Add("System.Data.dll"); parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll"); parameters.ReferencedAssemblies.Add("System.Configuration.dll"); parameters.ReferencedAssemblies.Add("EntitySpaces.SandboxLoader.dll"); foreach (string assemblyFileName in referenceList.AssemblyPaths) { parameters.ReferencedAssemblies.Add(assemblyFileName); } // *** Load the resulting assembly into memory parameters.GenerateInMemory = false; parameters.OutputAssembly = assemblyName; // *** Now compile the whole thing CompilerResults loCompiled = compiler.CompileAssemblyFromSource(parameters, code); if (loCompiled.Errors.HasErrors) { string lcErrorMsg = ""; // *** Create Error String lcErrorMsg = loCompiled.Errors.Count.ToString() + " Errors:"; for (int x = 0; x < loCompiled.Errors.Count; x++) { lcErrorMsg = lcErrorMsg + "\r\nLine: " + (loCompiled.Errors[x].Line - 21).ToString() + " - " + loCompiled.Errors[x].ErrorText; } MessageBox.Show(lcErrorMsg, "Compiler Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return(null); } string compiledCode = code; // create the factory class in the secondary app-domain RemoteLoaderFactory factory = (RemoteLoaderFactory)loAppDomain.CreateInstance("EntitySpaces.SandboxLoader", "EntitySpaces.SandboxLoader.RemoteLoaderFactory").Unwrap(); // with the help of this factory, we can now create a real 'LiveClass' instance object loObject = factory.Create(assemblyName, "MyNamespace.MyClass", null); // *** Cast the object to the remote interface to avoid loading type info loRemote = (IRemoteInterface)loObject; if (loObject == null) { MessageBox.Show("Couldn't load class."); return(null); } try { object[] codeParms = new object[1]; codeParms[0] = "EntitySpaces, LLC"; // *** Indirectly call the remote interface loResult = loRemote.Invoke("DynamicCode", codeParms); } catch (Exception loError) { MessageBox.Show(loError.Message, "DynamicCode Execution Error", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Execution Error", MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { loRemote = null; if (loAppDomain != null) { AppDomain.Unload(loAppDomain); loAppDomain = null; } File.Delete(assemblyName); } return((object[])loResult); }
private void button2_Click(object sender, System.EventArgs e) { string lcCode = this.txtCode.Text; // ** Create an AppDomain AppDomainSetup loSetup = new AppDomainSetup(); loSetup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; AppDomain loAppDomain = AppDomain.CreateDomain("MyAppDomain", null, loSetup); // *** Must create a fully functional assembly lcCode = @" using System; using System.IO; using System.Windows.Forms; using System.Reflection; using Westwind.RemoteLoader; namespace MyNamespace { public class MyClass : MarshalByRefObject,IRemoteInterface { public object Invoke(string lcMethod,object[] Parameters) { return this.GetType().InvokeMember(lcMethod, BindingFlags.InvokeMethod,null,this,Parameters); } public object DynamicCode(params object[] Parameters) { " + lcCode + "} } }"; ICodeCompiler loCompiler = new CSharpCodeProvider().CreateCompiler(); CompilerParameters loParameters = new CompilerParameters(); // *** Start by adding any referenced assemblies loParameters.ReferencedAssemblies.Add("System.dll"); loParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll"); loParameters.ReferencedAssemblies.Add("Remoteloader.dll"); // *** Load the resulting assembly into memory loParameters.GenerateInMemory = false; loParameters.OutputAssembly = "MyNamespace.dll"; // *** Now compile the whole thing CompilerResults loCompiled = loCompiler.CompileAssemblyFromSource(loParameters, lcCode); if (loCompiled.Errors.HasErrors) { string lcErrorMsg = ""; // *** Create Error String lcErrorMsg = loCompiled.Errors.Count.ToString() + " Errors:"; for (int x = 0; x < loCompiled.Errors.Count; x++) { lcErrorMsg = lcErrorMsg + "\r\nLine: " + loCompiled.Errors[x].Line.ToString() + " - " + loCompiled.Errors[x].ErrorText; } MessageBox.Show(lcErrorMsg + "\r\n\r\n" + lcCode, "Compiler Demo", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } this.txtAssemblyCode.Text = lcCode; // create the factory class in the secondary app-domain RemoteLoaderFactory factory = (RemoteLoaderFactory)loAppDomain.CreateInstance("RemoteLoader", "Westwind.RemoteLoader.RemoteLoaderFactory").Unwrap(); // with the help of this factory, we can now create a real 'LiveClass' instance object loObject = factory.Create("mynamespace.dll", "MyNamespace.MyClass", null); // *** Cast the object to the remote interface to avoid loading type info IRemoteInterface loRemote = (IRemoteInterface)loObject; if (loObject == null) { MessageBox.Show("Couldn't load class."); return; } object[] loCodeParms = new object[1]; loCodeParms[0] = "West Wind Technologies"; try { // *** Indirectly call the remote interface object loResult = loRemote.Invoke("DynamicCode", loCodeParms); DateTime ltNow = (DateTime)loResult; MessageBox.Show("Method Call Result:\r\n\r\n" + loResult.ToString(), "Compiler Demo", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception loError) { MessageBox.Show(loError.Message, "Compiler Demo", MessageBoxButtons.OK, MessageBoxIcon.Information); } loRemote = null; AppDomain.Unload(loAppDomain); loAppDomain = null; File.Delete("mynamespace.dll"); }