/// <summary> /// Call Method in the class /// </summary> /// <param name="classNameSpace"></param> /// <param name="method"></param> /// <param name="param"></param> /// <returns></returns> public object Invoke(string classNameSpace, string method, object[] param) { RemoteLoaderFactory factory = (RemoteLoaderFactory) ObjAppDomain.CreateInstance("MiniAbp", "MiniAbp.Compile.RemoteLoaderFactory") .Unwrap(); object objObject = factory.Create(_dllName, classNameSpace, null); if (objObject == null) { throw new ArgumentNullException("Error: " + "Couldn't load class."); } IRemoteInterface objRemote = (IRemoteInterface)objObject; //Initialize db configuration if (!IsIntialized) { lock (_initObjLock) { if (!IsIntialized) { var dbSetting = IocManager.Instance.Resolve <DatabaseConfiguration>(); objRemote.Initialize(dbSetting.ConnectionString, dbSetting.Dialect); IsIntialized = true; } } } return(objRemote.Invoke(method, param)); }
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 bool Connect(string host, int port) { bool connected = false; try { remoteInterface = (IRemoteInterface)Activator.GetObject(typeof(IRemoteInterface), new UriBuilder("http", host, port, "/IMIServer").ToString()); remoteInterface.Time(); connected = true; } catch (Exception e) { Console.WriteLine("Failed to connect, error {0}", e.Message); remoteInterface = null; } return(connected); }
public bool Connect() { connected = false; try { remoteInterface = (IRemoteInterface)Activator.GetObject(typeof(IRemoteInterface), new UriBuilder("http", config.HostName, config.Port, "/IMIServer").ToString()); DateTime serverTime = remoteInterface.Time(); timeDiff = serverTime - DateTime.Now; connected = true; OnConnectStateChanged(); } catch (Exception) { remoteInterface = null; throw; } return(connected); }
public object CallMethod(object loObject, string lcMethod, params object[] loParameters) { // *** Try to run it try { if (AppDomain == null) { // *** Just invoke the method directly through Reflection return(loObject.GetType().InvokeMember(lcMethod, BindingFlags.InvokeMethod, null, loObject, loParameters)); } else { #if useRemoteLoader // *** Invoke the method through the Remote interface and the Invoke method object loResult; try { // *** Cast the object to the remote interface to avoid loading type info IRemoteInterface loRemote = (IRemoteInterface)loObject; // *** Indirectly call the remote interface loResult = loRemote.Invoke(lcMethod, loParameters); } catch (Exception ex) { this.bError = true; this.cErrorMsg = ex.Message; return(null); } return(loResult); #endif } } catch (Exception ex) { Error = true; ErrorMessage = ex.GetBaseException().Message; } return(null); }
public object CallMethod(object loObject, string lcMethod, params object[] loParameters) { _ErrorMsg = string.Empty; try { if (oAppDomain == null) { // *** Just invoke the method directly through Reflection return(loObject.GetType().InvokeMember(lcMethod, BindingFlags.InvokeMethod, null, loObject, loParameters)); } else { // *** Invoke the method through the Remote interface and the Invoke method object loResult; try { // *** Cast the object to the remote interface to avoid loading type info IRemoteInterface loRemote = (IRemoteInterface)loObject; // *** Indirectly call the remote interface loResult = loRemote.Invoke(lcMethod, loParameters); } catch (Exception ex) { bError = true; _ErrorMsg = ex.Message; return(null); } return(loResult); } } catch (Exception ex) { bError = true; _ErrorMsg = ex.Message; } return(null); }
public object CallMethod(object obj, string methodName, params object[] parameters) { // *** Try to run it try { if (this.AppDomain == null) { // *** Just invoke the method directly through Reflection return(obj.GetType().InvokeMember(methodName, BindingFlags.InvokeMethod, null, obj, parameters)); } else { // *** Invoke the method through the Remote interface and the Invoke method object oResult; try { // *** Cast the object to the remote interface to avoid loading type info IRemoteInterface oRemote = (IRemoteInterface)obj; // *** Indirectly call the remote interface oResult = oRemote.Invoke(methodName, parameters); } catch (Exception ex) { this.HasError = true; this.ErrorMessage = ex.Message; return(null); } return(oResult); } } catch (Exception ex) { this.HasError = true; this.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 void test() { loSetup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; AppDomain loAppDomain = AppDomain.CreateDomain("MyAppDomain", null, loSetup); // Must create a fully functional assembly code 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"); // Important that this gets loaded or the Interface won't work! 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) { // ... return; } // create the factory class in the secondary app-domain RemoteLoaderFactory factory = (RemoteLoaderFactory)loAppDomain.CreateInstance("RemoteLoader", "Westwind.RemoteLoader.RemoteLoaderFactory").Unwrap(); // with help of factory, create a real 'LiveClass' instance object loObject = factory.Create("mynamespace.dll", "MyNamespace.MyClass", null); // Cast object to remote Interface, 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\"+loResult.ToString()) } catch (Exception loError) { //MessageBox.Show(loError.Message, "Compiler Demo"); } loRemote = null; AppDomain.Unload(loAppDomain); loAppDomain = null; // Delete the generated code DLL when done File.Delete("mynamespace.dll"); }
public void Disconnect() { connected = false; remoteInterface = null; OnConnectStateChanged(); }
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); }
public RemoteInterfaceProxy(IRemoteInterface remoteInterface) { this.remoteInterface = remoteInterface; }
public RemoteInterfaceProxy() { remoteInterface = null; }
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"); }