public MathProxy() { AppDomain domain = AppDomain.CreateDomain("MathDomain", null, null); System.Runtime.Remoting.ObjectHandle handle = domain.CreateInstance("ConsoleDemo", "ConsoleDemo.DesginPatterns.ConstructorPatterns.Math"); mathObj = handle.Unwrap() as Math; }
static void Main() { Console.WriteLine("[{0}] {1}", System.AppDomain.CurrentDomain.FriendlyName, "Entered Main"); //stvara novu aplikacijsku domenu AppDomain ad2 = AppDomain.CreateDomain("Shape Domain"); //Assembly a = Assambly.LoadForm("ProgCSharp.exe"); //Object theShape = a.CreateInstance("Shape"); //Instanciranje Shape objekta System.Runtime.Remoting.ObjectHandle oh = ad2.CreateInstance( "Marshaling", "Marshaling.Shape", false, BindingFlags.CreateInstance, null, new object[] { 3, 5 }, null, null); Shape s1 = (Shape)oh.Unwrap(); s1.ShowUpperLeft(); //zahtjeva od objekta da prikaze //dobili ste lokalnu kopiju posrednika Point localPoint = s1.GetUpperLeft(); //dodjeljuje nove vrijednosti localPoint.X = 500; localPoint.Y = 600; //prikazuje vrijednosti lokalnog pointa Console.WriteLine("[{0}] localPoint: {1}, {2}", System.AppDomain.CurrentDomain.FriendlyName, localPoint.X, localPoint.Y); s1.ShowUpperLeft(); //prikazuje vrijednost jos jednom }
private static string resolveAssemblyDllFromBaseDirectory(string name, string baseDirectory) { progress("dllFromBase: Resolve [" + name + "] from " + baseDirectory); // Resolve name to the dll as if .exe in baseDirectory was executed AppDomainSetup setup = new AppDomainSetup(); setup.ApplicationBase = baseDirectory; setup.DisallowApplicationBaseProbing = false; AppDomain dtest = AppDomain.CreateDomain("temp" + Guid.NewGuid(), null, setup); progress("dllFromBase: Domain created"); try { System.Runtime.Remoting.ObjectHandle v = Activator.CreateInstanceFrom(dtest, Assembly.GetExecutingAssembly().Location, typeof(AppDomainWorker).FullName); if (v != null) { AppDomainWorker appDomainWorker = v.Unwrap() as AppDomainWorker; progress("dllFromBase: Resolver created"); if (appDomainWorker != null) { string s = appDomainWorker.ResolveDllFromAssemblyName(name); progress("dllFromBase: " + name + " >> " + s); return(s); } } progress("dllFromBase: Resolve " + name + " failed"); return(null); } finally { AppDomain.Unload(dtest); } }
private void CreatePNUnitServices( TestDomain testDomain, TestConsoleAccess consoleAccess) { log.Info("Creating PNUnitServices in the AppDomain of the test"); object[] param = { mPNUnitTestInfo, consoleAccess }; try { System.Runtime.Remoting.ObjectHandle obj #if NET_2_0 = Activator.CreateInstance( testDomain.AppDomain, #else = testDomain.AppDomain.CreateInstance( #endif typeof(PNUnitServices).Assembly.FullName, typeof(PNUnitServices).FullName, false, BindingFlags.Default, null, param, null, null, null); obj.Unwrap(); } catch (Exception e) { BuildError(e, consoleAccess); log.ErrorFormat("Error running test {0}", e.Message); return; } }
private void btnAdd_Click(object sender, System.EventArgs e) { //TODO: How to dynamically create an object from a string? Use scripting engine? Or a factory? //TODO: How to find all behavior classes? Search in a separate folder? Or register somehow? Behavior bh = null; //TODO: only works in IDE mode. How to do it in normal mode? System.IO.FileInfo finfo = new System.IO.FileInfo(EndogineHub.Instance.CastLib.DirectoryPath); ArrayList aFiles = new ArrayList(); GetAllFiles(finfo.Directory.FullName, "Bh*.cs", ref aFiles); if (false) { } else { System.Runtime.Remoting.ObjectHandle obj = System.Activator.CreateInstance("Tests", "DivStuff.BhSwing"); object o = obj.Unwrap(); bh = (Behavior)o; } //Behavior bh = (Behavior)obj.Unwrap();//typeof("ThisMovie.BhSwing") if (bh != null) { m_sp.AddBehavior(bh); RefreshView(); } }
private static Exception ConvertException(String exceptionType, String message, Exception innerException) { try { string className = rocksteadyExceptionNameSpace + "." + exceptionType; Type t = typeof(Microsoft.VisualStudio.TestPlatform.Common.TestRunner.TestPlatformException); string assembly = Assembly.GetAssembly(t).FullName; System.Runtime.Remoting.ObjectHandle handle = Activator.CreateInstance(assembly, className, true, 0, null, new object[] { message, innerException }, CultureInfo.InvariantCulture, null, null); return((TestPlatformException)handle.Unwrap()); } catch (Exception) { // Ignore it, and try to get System.Exception } try { string className = "System" + "." + exceptionType; Type t = typeof(System.Exception); string assembly = Assembly.GetAssembly(t).FullName; System.Runtime.Remoting.ObjectHandle handle = Activator.CreateInstance(assembly, className, true, 0, null, new object[] { message, innerException }, CultureInfo.InvariantCulture, null, null); Exception tempEx = (Exception)handle.Unwrap(); return(tempEx); } catch (Exception) { // Neither System nor TestPlatformException, but still pass it as TestPlatformException return(new TestPlatformException(message, innerException)); } }
public override void OnTest(string[] args) { if (args.Length != 3) // 파라미터의 개수를 확인한다. { throw new ArgumentException("Parameter(s): [<Optional properties>]" + " <Port> <Protocol> <Dispatcher>"); } int servPort = Int32.Parse(args[0]); // 서버포트 String protocolName = args[1]; // 프로토콜 이름 String dispatcherName = args[2]; // 전달자(dispatcher) 이름 TcpListener listener = new TcpListener(IPAddress.Any, servPort); listener.Start(); ILogger logger = new ConsoleLogger(); // 메시지를 콘솔에 기록한다. System.Runtime.Remoting.ObjectHandle objHandle = Activator.CreateInstance(null, protocolName + "ProtocolFactory"); IProtocolFactory protoFactory = (IProtocolFactory)objHandle.Unwrap(); objHandle = Activator.CreateInstance(null, dispatcherName + "Dispatcher"); IDispatcher dispatcher = (IDispatcher)objHandle.Unwrap(); dispatcher.startDispatching(listener, logger, protoFactory); // 이 곳으로는 도달하지 않는다. }
/// <summary> /// 获取指定类型的对象 /// </summary> /// <param name="t"></param> /// <returns></returns> public static Object GetPlugin(Type t) { if (xdConfig == null) { throw new ConfigNotFindException("PluginConfig未加载!"); } XmlNode root = xdConfig.DocumentElement; XmlNode Node = null; try { Node = root.SelectSingleNode("InterfaceMapping/" + t.Name); } catch (TypeInitializationException) { return(null); } if (Node != null) { System.Runtime.Remoting.ObjectHandle objHandle = null; objHandle = System.Activator.CreateInstance(Node.Attributes["LoadFromAssembly"].Value, Node.InnerText); return(objHandle.Unwrap()); } else { return(null); } }
/// <summary> /// 获取需设置的类变更属性 /// </summary> protected void GetShiftProperty() { Neusoft.FrameWork.WinForms.Classes.Function.ShowWaitForm(Neusoft.FrameWork.Management.Language.Msg("正在载入信息 请稍候...")); Application.DoEvents(); try { System.Runtime.Remoting.ObjectHandle oHandle = System.Activator.CreateInstance("HISFC.Object", this.txtTypeStr.Text); if (oHandle == null) { Neusoft.FrameWork.WinForms.Classes.Function.HideWaitForm(); MessageBox.Show(Neusoft.FrameWork.Management.Language.Msg("未能由输入信息获取类型 请检查是否输入正确")); return; } Type t = oHandle.Unwrap().GetType(); if (t == null) { Neusoft.FrameWork.WinForms.Classes.Function.HideWaitForm(); MessageBox.Show(Neusoft.FrameWork.Management.Language.Msg("未能由输入信息获取类型 请检查是否输入正确")); return; } if (this.hsExtisClass.ContainsKey(t.ToString())) { Neusoft.FrameWork.WinForms.Classes.Function.HideWaitForm(); MessageBox.Show(Neusoft.FrameWork.Management.Language.Msg("该实体信息已存在 请删除原信息后重新添加")); this.txtTypeStr.SelectAll(); return; } List <Neusoft.FrameWork.Models.NeuObject> alProperty = this.GetProperty(t); if (alProperty != null) { if (alProperty.Count == 0) { Neusoft.FrameWork.WinForms.Classes.Function.HideWaitForm(); MessageBox.Show(Neusoft.FrameWork.Management.Language.Msg("该实体类无满足条件的属性信息")); return; } this.neuSpread1_Sheet1.Rows.Count = 0; foreach (Neusoft.FrameWork.Models.NeuObject info in alProperty) { this.neuSpread1_Sheet1.Rows.Add(0, 1); this.neuSpread1_Sheet1.Cells[0, 0].Text = info.Name; //属性名称中文描述 this.neuSpread1_Sheet1.Cells[0, 1].Text = info.Memo; //属性描述 this.neuSpread1_Sheet1.Rows[0].Tag = info; } } } catch { Neusoft.FrameWork.WinForms.Classes.Function.HideWaitForm(); MessageBox.Show(Neusoft.FrameWork.Management.Language.Msg("未能由输入信息获取类型 请检查是否输入正确")); return; } Neusoft.FrameWork.WinForms.Classes.Function.HideWaitForm(); }
private object MashallLoad() { try { //Create 'New AppDomain' to load 'Assembly' AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation; AppDomain newDomain = AppDomain.CreateDomain("NewDom", AppDomain.CurrentDomain.Evidence, setup); //Create instance of 'AssemblyLoader' class in new appdomain System.Runtime.Remoting.ObjectHandle obj = newDomain.CreateInstance(typeof(AssemblyLoader).Assembly.FullName, typeof(AssemblyLoader).FullName); //The instance we created came from a different AppDomain //We will get that instance in wrapped format //So we have to unwrap it AssemblyLoader loader = (AssemblyLoader)obj.Unwrap(); //Call loadassembly method //so that the assembly will be loaded into the new appdomain and the object will also remain in the new appdomain only. loader.Load(m_path); //Call exceuteMethod and pass the name of the method from assembly and the parameters. object result = loader.ExecuteMethod("Class", "TestMethod", null); //After the method has been executed call the unload method of the appdomain. AppDomain.Unload(newDomain); return(result); } catch (AppDomainUnloadedException ex) { // return(null); } }
private static void MashallLoad(string asmPath) { try { System.Text.StringBuilder sb = new StringBuilder(); AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation; AppDomain newDomain = AppDomain.CreateDomain("NewDom", AppDomain.CurrentDomain.Evidence, setup); System.Runtime.Remoting.ObjectHandle obj = newDomain.CreateInstance(typeof(AssemblyLoader).Assembly.FullName, typeof(AssemblyLoader).FullName); AssemblyLoader loader = (AssemblyLoader)obj.Unwrap(); loader.Load(asmPath); sb = loader.GetAsmMembers(); Console.WriteLine(sb.ToString().Trim('\n')); Console.WriteLine("\n\nPlz enter the key.."); Console.ReadKey(); // ※ 주의 // main AppDomain에서 Type형 변수에 Read한 Assembly의 Type객체를 대입하게되면 // 내부적으로 Assembly Load가 발생하게 된다. // Type type = loader.GetType(); } catch (AppDomainUnloadedException ex) { // } }
public static void GetFullNameOfClassThatInheritsFromApplication(string pathOfAssemblyThatContainsEntryPoint, out string applicationClassFullName, out string assemblyName, out string assemblyFullName) { //----------------- // Thanks to: http://www.c-sharpcorner.com/UploadFile/girish.nehte/how-to-unload-an-assembly-loaded-dynamically-using-reflection/ //----------------- // Load the assembly in a new AppDomain mainly so that we are able to unload it, which is necessary when we want to delete all temporary files including this assembly. AppDomainSetup setupInformation = AppDomain.CurrentDomain.SetupInformation; AppDomain newAppDomain = AppDomain.CreateDomain("newAppDomain", AppDomain.CurrentDomain.Evidence, setupInformation); //Create an instance of the inspector class in the new domain: //System.Runtime.Remoting.ObjectHandle obj = newAppDomain.CreateInstance(typeof(AssemblyInspectorOnOtherDomain).Assembly.FullName, typeof(AssemblyInspectorOnOtherDomain).FullName); string pathOfThisVeryAssembly = PathsHelper.GetPathOfThisVeryAssembly(); System.Runtime.Remoting.ObjectHandle obj = newAppDomain.CreateInstanceFrom(pathOfThisVeryAssembly, typeof(AssemblyInspectorOnOtherDomain).FullName); IAssemblyInspectorOnOtherDomain inspector = (IAssemblyInspectorOnOtherDomain)obj.Unwrap(); // As the object we are creating is from another appdomain hence we will get that object in wrapped format and hence in next step we have unwrappped it // Call LoadAssembly method so that the assembly will be loaded into the new appdomain amd the object will also remain in new appdomain only: inspector.LoadAssembly(pathOfAssemblyThatContainsEntryPoint); // Call the method that finds the type that inherits from Application: applicationClassFullName = inspector.FindApplicationClassFullName(); // Get the assembly name and full name too: assemblyName = inspector.GetAssemblyName(); assemblyFullName = inspector.GetAssemblyFullName(); // Unload the assembly (so that we can later delete it if necessary): AppDomain.Unload(newAppDomain); GC.Collect(); // Collects all unused memory GC.WaitForPendingFinalizers(); // Waits until GC has finished its work GC.Collect(); }
/// <summary> /// 设置配置标签打印接口 /// </summary> /// <returns></returns> public static int InitCompoundPrintInterface() { object[] o = new object[] { }; try { //门诊标签打印接口实现类 Neusoft.HISFC.BizProcess.Integrate.Common.ControlParam ctrlIntegrate = new Neusoft.HISFC.BizProcess.Integrate.Common.ControlParam(); string labelValue = "Neusoft.Report.Logistics.ucCompoundLabel"; //ctrlIntegrate.GetControlParam<string>(Neusoft.HISFC.BizProcess.Integrate.PharmacyConstant.Compound_Print_Label, true, "Neusoft.Report.Logistics.ucCompoundLabel"); System.Runtime.Remoting.ObjectHandle objHandel = System.Activator.CreateInstance("Report", labelValue, false, System.Reflection.BindingFlags.CreateInstance, null, o, null, null, null); object oLabel = objHandel.Unwrap(); if (oLabel.GetType().GetInterface("ICompoundPrint") == null) { System.Windows.Forms.MessageBox.Show("不符合接口"); return(-1); } Neusoft.Report.Logistics.DrugStore.Function.ICompoundPrint = oLabel as Neusoft.HISFC.BizProcess.Interface.Pharmacy.ICompoundPrint; //Neusoft.HISFC.Components.DrugStore.Function.ICompoundPrint = oLabel as Neusoft.HISFC.BizProcess.Integrate.PharmacyInterface.ICompoundPrint; } catch (System.TypeLoadException ex) { Neusoft.FrameWork.WinForms.Classes.Function.HideWaitForm(); System.Windows.Forms.MessageBox.Show(Neusoft.FrameWork.Management.Language.Msg("标签命名空间无效\n" + ex.Message)); return(-1); } return(1); }
void _MetroUI_QueryControl(object sender, DevExpress.XtraBars.Docking2010.Views.QueryControlEventArgs e) { if (e.Document.ControlTypeName == "DataSetting") { try { StaticVars.DataSetting_ProcName = e.Document.ControlName; StaticVars.FullClassName = string.Format("{0}.{1}", e.Document.ControlTypeName, e.Document.ControlName); System.Runtime.Remoting.ObjectHandle handle = System.Activator.CreateInstance("HPA.Setting", "HPA.Setting.DynamicUserControl"); HPA.CommonForm.UserControlHasButton frm = (HPA.CommonForm.UserControlHasButton)(handle.Unwrap()); frm.Caption = e.Document.Caption; e.Control = frm; } catch (Exception ex) { //if (MessageBox.Show("Ket noi lai ko?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Yes) //{ // DBEngine = new EzSqlCollection.EzSql2(HPA.Common.StaticVars.ServerName, HPA.Common.StaticVars.DatabaseName, HPA.Common.StaticVars.UserID_sql, HPA.Common.StaticVars.Password); // DBEngine.open(); // MessageBox.Show("ket noi thanh cong"); //} } } else { e.Control = new Control(); } }
/// <summary> /// 设置处方打印接口 /// </summary> /// <returns></returns> public static int InitLabelPrintInterface() { object[] o = new object[] { }; try { System.Runtime.Remoting.ObjectHandle objHandel = System.Activator.CreateInstance("WinForms.Report", "Neusoft.WinForms.Report.DrugStore.ucRecipeLabel", false, System.Reflection.BindingFlags.CreateInstance, null, o, null, null, null); object oLabel = objHandel.Unwrap(); if (oLabel.GetType().GetInterface("IDrugPrint") == null) { System.Windows.Forms.MessageBox.Show("不符合接口"); return(-1); } Neusoft.HISFC.Components.DrugStore.Function.IDrugPrint = oLabel as Neusoft.HISFC.BizProcess.Interface.Pharmacy.IDrugPrint; } catch (System.TypeLoadException ex) { Neusoft.FrameWork.WinForms.Classes.Function.HideWaitForm(); System.Windows.Forms.MessageBox.Show(Neusoft.FrameWork.Management.Language.Msg("标签命名空间无效\n" + ex.Message)); return(-1); } return(1); }
/// <summary> /// it is an helper method for ObjList CURD(Insert, Update, Delete) methods /// </summary> /// <typeparam name="T">Name of Model Object</typeparam> /// <param name="obj"></param> /// <param name="ControllerActionName">Name of Controller method to invoke</param> /// <returns></returns> private static int PerformActionList <T>(List <T> obj, string ControllerActionName) { try { string ModelName = obj[0].GetType().FullName.Split('.').Last(); string FullControllerName = obj[0].GetType().FullName.Replace(".Entities.", ".DBContexts.") + "Context"; string Namespace = FullControllerName.Substring(0, FullControllerName.IndexOf(".DBContexts.")); if (obj.Count < 1) { throw new Exception("Cannot perform operation while no valid " + ModelName + " data provided. Please check provided " + ModelName + "List object and try again."); } ///----- Referencing Controller Class of same object System.Runtime.Remoting.ObjectHandle ControllerWrapper = Activator.CreateInstance(Namespace, FullControllerName); var Controller = ControllerWrapper.Unwrap(); ControllerWrapper = null; ///----- Referencing Insert method from Controller Class MethodInfo InsertController = Controller.GetType().GetMethods().ToList().Find(x => x.Name == ControllerActionName && x.GetParameters().Count() == 1 && x.GetParameters()[0].Name == "obj" + ModelName + "List"); if (InsertController == null) { throw new Exception("Unable to find " + ControllerActionName + " method in Controller class which accepts " + ModelName + " as parameter."); } ///----- Invoking Insert and returning the Primary Key of newly inserted object return((int)InsertController.Invoke(Controller, new Object[] { obj })); } catch (Exception ex) { throw ex; } }
/// <summary> /// Accepts Entity object or its inherited object, delete row(s) from table /// /// return ObjectId of deleted row(s) /// </summary> /// <returns>ObjectId of deleted row(s)</returns> public static int Delete(this Entity Model) { try { ///----- Referencing ValidateThis method from Model Class MethodInfo ValidateModel = Model.GetType().GetMethods().ToList().Find(x => x.Name == "Validate"); if (ValidateModel == null) { throw new Exception("Unable to find Validate method in Entity."); } ///----- Invoking ValidateThis too validate whather the Model is ready to be inserted or not? ValidateModel.Invoke(Model, new object[] { SqlOperation.Delete }); string ModelName = Model.GetType().FullName.Split('.').Last(); string FullControllerName = Model.GetType().FullName.Replace(".Entities.", ".DBContexts.") + "Context"; string Namespace = FullControllerName.Substring(0, FullControllerName.IndexOf(".DBContexts.")); ///----- Referencing Controller Class of same object System.Runtime.Remoting.ObjectHandle ControllerWrapper = Activator.CreateInstance(Namespace, FullControllerName); var Controller = ControllerWrapper.Unwrap(); ControllerWrapper = null; ///----- Referencing Delete method from Controller Class MethodInfo deleteController = Controller.GetType().GetMethods().ToList().Find(x => x.Name == "Delete" && x.GetParameters().Count() == 1 && x.GetParameters()[0].Name == "obj" + ModelName); if (deleteController == null) { throw new Exception("Unable to find Update method in Controller class which accepts " + ModelName + " as parameter."); } ///----- Invoking Delete and returning the Primary Key of updated object return((int)deleteController.Invoke(Controller, new Object[] { Model })); } catch (Exception ex) { throw ex; } }
/// <summary> /// Dumps everything of a single type into the cache from the filesystem for BackingData /// </summary> /// <typeparam name="T">the type to get and store</typeparam> /// <returns>full or partial success</returns> public bool LoadAllCharactersForAccountToCache(string accountHandle) { string currentBackupDirectory = BaseDirectory + accountHandle + "/" + CurrentDirectoryName; //No current directory? WTF if (!VerifyDirectory(currentBackupDirectory, false)) { return(false); } DirectoryInfo charDirectory = new DirectoryInfo(currentBackupDirectory); foreach (FileInfo file in charDirectory.EnumerateFiles("*.playertemplate", SearchOption.AllDirectories)) { try { byte[] fileData = ReadFile(file); System.Runtime.Remoting.ObjectHandle blankEntity = Activator.CreateInstance("NetMud.Data", "NetMud.Data.Players.PlayerTemplate"); IPlayerTemplate objRef = blankEntity.Unwrap() as IPlayerTemplate; IPlayerTemplate newChar = objRef.FromBytes(fileData) as IPlayerTemplate; PlayerDataCache.Add(newChar); } catch (Exception ex) { LoggingUtility.LogError(ex); //Let it keep going } } return(true); }
private void loadProvider(string fileName, string className) { System.Runtime.Remoting.ObjectHandle handle = Activator.CreateInstanceFrom(fileName, className); IComaniSource newProvider = handle.Unwrap() as IComaniSource; providers.Add(newProvider); }
private static IVsSingleFileGenerator CreateVBMyResxFileCodeGenerator() { string className = string.Format(ResxFileCodeGeneratorTypeNameFormatString, "VBMyResXFileCodeGenerator"); System.Runtime.Remoting.ObjectHandle oh = (System.Runtime.Remoting.ObjectHandle)System.Activator.CreateInstance(ResxFileCodeGeneratorAssemblyName, className); return((IVsSingleFileGenerator)oh.Unwrap()); }
public static IConfigurationProviderFactory CreateConfigurationFactory() { string modelAssembly = AspDotNetStorefrontCore.AppLogic.AppConfig("Vortx.OnePageCheckout.ConfigurationFactoryAssembly"); string modelType = AspDotNetStorefrontCore.AppLogic.AppConfig("Vortx.OnePageCheckout.ConfigurationFactoryType"); System.Runtime.Remoting.ObjectHandle handle = System.Activator.CreateInstance(modelAssembly, modelType); return((IConfigurationProviderFactory)handle.Unwrap()); }
protected override void OnLoad(EventArgs e) { try { this.operDept = ((Neusoft.HISFC.Models.Base.Employee) this.drugStoreManager.Operator).Dept; this.DataInit(); #region 反射读取标签格式 //string dllName = "Report"; string className = "Neusoft.WinForms.Report.DrugStore.ucRecipeLabel"; //门诊标签打印接口实现类 Neusoft.HISFC.BizProcess.Integrate.Common.ControlParam ctrlIntegrate = new Neusoft.HISFC.BizProcess.Integrate.Common.ControlParam(); string labelValue = "Neusoft.WinForms.Report.DrugStore.ucRecipeLabel"; //ctrlIntegrate.GetControlParam<string>(Neusoft.HISFC.BizProcess.Integrate.PharmacyConstant.Clinic_Print_Label, true, "Report.DrugStore.ucRecipeLabel"); //门诊草药打印接口实现类 string billValue = "Neusoft.WinForms.Report.DrugStore.ucOutHerbalBill"; // ctrlIntegrate.GetControlParam<string>(Neusoft.HISFC.BizProcess.Integrate.PharmacyConstant.Clinic_Print_Bill, true, "Report.DrugStore.ucOutHerbalBill"); //默认标签打印 className = labelValue; //读取本地控制参数 判断是否采用草药打印方式 string strErr = ""; ArrayList alParm = Neusoft.FrameWork.WinForms.Classes.Function.GetDefaultValue("ClinicDrug", "PrintList", out strErr); if (alParm != null && alParm.Count > 0) { if ((alParm[0] as string) == "1") { className = billValue; this.isHerbalPrint = true; } } object[] o = new object[] { }; try { System.Runtime.Remoting.ObjectHandle objHandel = System.Activator.CreateInstance("WinForms.Report", className, false, System.Reflection.BindingFlags.CreateInstance, null, o, null, null, null); object oLabel = objHandel.Unwrap(); // Neusoft.HISFC.Components.DrugStore.Function.IDrugPrint = oLabel as Neusoft.HISFC.BizProcess.Integrate.PharmacyInterface.IDrugPrint; Neusoft.Report.Logistics.DrugStore.Function.IDrugPrint = oLabel as Neusoft.HISFC.BizProcess.Interface.Pharmacy.IDrugPrint; } catch (System.TypeLoadException ex) { Neusoft.FrameWork.WinForms.Classes.Function.HideWaitForm(); MessageBox.Show(Language.Msg("标签命名空间无效\n" + ex.Message)); } #endregion } catch { } base.OnLoad(e); }
public static object CreateFromXMLNode(System.Xml.XmlNode a_node) { string sAssembly = a_node.Attributes.GetNamedItem("Assembly").InnerText; string sType = a_node.Attributes.GetNamedItem("Type").InnerText; System.Runtime.Remoting.ObjectHandle obj = System.Activator.CreateInstance(sAssembly, sType); object o = obj.Unwrap(); Deserialize(o, a_node); return(o); }
public static object GetInstance(string sAssmebly, string sClass) { string sUrl = ""; sUrl = System.IO.Path.Combine(Application.StartupPath, sAssmebly); System.Runtime.Remoting.ObjectHandle handle = Activator.CreateInstanceFrom(sUrl, sClass); object obj = handle.Unwrap(); return(obj); }
public object CreateInstance() { try { System.Runtime.Remoting.ObjectHandle oh = System.Activator.CreateInstance(_assemblyName, _typeName); return(oh.Unwrap()); } catch (Exception) { } return(null); }
public UserscriptHost( byte[] AssemblySerial, byte[] AssemblySymbolStoreSerial) { BeginZait = Bib3.Glob.StopwatchZaitMiliSictInt(); this.AssemblySerial = AssemblySerial; this.AssemblySymbolStoreSerial = AssemblySymbolStoreSerial; if (null == AssemblySerial) { return; } if (false) { // Weege Probleme mit Debuge (Visual Studio Debugger überspringt Method in Dll) verzict auf AppDomain ScriptAppDomain = AppDomain.CreateDomain("UserScript.Instance[" + Ident.ToString() + "]"); AssemblyLoaded = ScriptAppDomain.Load(AssemblySerial, AssemblySymbolStoreSerial); } else { AssemblyLoaded = System.Reflection.Assembly.Load(AssemblySerial, AssemblySymbolStoreSerial); } var MengeType = AssemblyLoaded.GetTypes(); ScriptInterfaceType = MengeType .FirstOrDefaultNullable(PrädikaatTypeIstScriptInterface); if (null == ScriptInterfaceType) { return; } if (false) { // Weege Probleme mit Debuge (Visual Studio Debugger überspringt Method in Dll) verzict auf AppDomain ScriptInterfaceWrapped = ScriptAppDomain.CreateInstance(AssemblyLoaded.FullName, ScriptInterfaceType.FullName); ScriptInterfaceLease = (System.Runtime.Remoting.Lifetime.ILease)ScriptInterfaceWrapped.InitializeLifetimeService(); ScriptInterface = (IUserscript)ScriptInterfaceWrapped.Unwrap(); } else { ScriptInterface = (IUserscript)Activator.CreateInstance(ScriptInterfaceType); } }
/// <summary> /// 从指定程序集加载指定类型对象 /// </summary> /// <param name="assemblyName">程序集名称</param> /// <param name="typeName">类名称</param> /// <returns></returns> public static Object GetPlugin(string assemblyName, string typeName) { System.Runtime.Remoting.ObjectHandle objHandle = System.Activator.CreateInstance(assemblyName, typeName); if (objHandle != null) { return(objHandle.Unwrap()); } else { throw new ApplicationException("从程序集" + assemblyName + "反射对象" + typeName + "时,构件对象为NULL"); } }
private void LoadPlugins() { int defaultChecked = 0; if (m_Plugins == null) { ArrayList pluginsKeeper = new ArrayList(); StreamReader pluginReader = new StreamReader("Agent.dm"); string line; char[] separator = { ' ', '\t', '\n' }; string[] tokens; while ((line = pluginReader.ReadLine()) != null) { line = line.Trim(); if (line.Length > 0 && line[0] != ';') { tokens = line.Split(separator); if (tokens[0].Equals("Agent1Default")) { defaultChecked = int.Parse(tokens[1]); } else { System.Runtime.Remoting.ObjectHandle oh = Activator.CreateInstanceFrom(tokens[0], tokens[1]); pluginsKeeper.Add(oh.Unwrap()); } } } pluginReader.Close(); m_Plugins = new AgentDecisionModule[pluginsKeeper.Count]; for (int i = 0; i < pluginsKeeper.Count; i++) { m_Plugins[i] = ( AgentDecisionModule )pluginsKeeper[i]; } } string[] pluginNames = new string[m_Plugins.Length]; for (int i = 0; i < m_Plugins.Length; i++) { pluginNames[i] = m_Plugins[i].NameId(); } m_GUI.AddLoadedPlugin(pluginNames); if (defaultChecked > 0) { m_GUI.SelectEvaluator(defaultChecked - 1); } }
/// <summary> /// it will select all data from specific table /// convert it into Model Object /// and overwrite current Instance /// </summary> /// <typeparam name="T">Name of Model Object</typeparam> /// <param name="obj"></param> public static void Select <T>(this List <T> obj) { ///----- Remove all objects from list obj.Clear(); ///----- Internal Variables string FullModelName = obj.GetType().FullName.Replace("List", ""); string ModelName = FullModelName.Split('.').Last(); string AssemblyName = FullModelName.Substring(0, FullModelName.IndexOf(".Entities.")); System.Runtime.Remoting.ObjectHandle ModelWrapper = Activator.CreateInstance(AssemblyName, FullModelName); var Model = ModelWrapper.Unwrap(); ModelWrapper = null; /////----- Gathering method which will select data from DB //MethodInfo SelectModel = Model.GetType().GetMethods().ToList().Find(x => x.Name == "Select" && x.GetParameters().Count() == 0); //if (SelectModel == null) { return; } ///----- Gathering Model's Construct that will parse DataRow into Model Object ConstructorInfo cnstrDataRow = Model.GetType().GetConstructors().ToList().Find(x => x.GetParameters().Count() == 1 && x.GetParameters()[0].Name == "Row"); if (cnstrDataRow == null) { return; } ///----- [1].Getting data from DB ///----- [2].Parsing into Model Object ///----- [3].And adding into collection ///----- [1] System.Data.DataSet ds = ((Entity)Model).Select(); if (ds != null && ds.Tables.Count > 0) { foreach (System.Data.DataRow row in ds.Tables[0].Rows) { ///----- [2] T newRow = (T)cnstrDataRow.Invoke(new object[] { row }); ///----- [3] obj.Add(newRow); } ds.Dispose(); } ///----- Clearing up Memory Model = null; ModelName = null; FullModelName = null; }
private Control CreateTypedControl_FromPath(String control_guid, String Class_Path) { Type TypeControl = Type.GetType(Class_Path); if (TypeControl == null) { System.Runtime.Remoting.ObjectHandle oh = Activator.CreateInstance(Class_Path.Substring(0, Class_Path.IndexOf(".")), Class_Path); return((Control)oh.Unwrap()); } else { return((Control)Activator.CreateInstance(TypeControl)); } }
public void Start() { _Domain = AppDomain.CreateDomain(_Setup.ApplicationName, null, _Setup); // Construct the target class, it must take over from there. _RemoteType = _Domain.CreateInstance(_TypeInfo[1], _TypeInfo[0]); }
public void Stop() { if (_Domain != null) { var shutdown = _Domain.GetData("ShutdownEvent") as EventWaitHandle; var shutdownAck = _Domain.GetData("ShutdownAckEvent") as EventWaitHandle; if (shutdown != null) { int msecTimeout = 10000; object to = _Domain.GetData("ShutdownTimeout"); if (to != null) { msecTimeout = (int)to; } shutdown.Set(); if (shutdownAck != null) { if (!shutdownAck.WaitOne(msecTimeout, false)) { mLog.WarnFormat("Timed out waiting for soft shutdown of '{0}', forcing shutdown.", _Home.Name); } else { mLog.InfoFormat("Successful soft shutdown of '{0}'.", _Home.Name); } } else { mLog.WarnFormat("No shutdown ack available for '{0}', waiting {1} msec and then forcing shutdown.", _Home.Name, msecTimeout); Thread.Sleep(msecTimeout); } } else { mLog.WarnFormat("No shutdown handshake available, performing hard shutdown for '{0}'.", _Home.Name); } _RemoteType = null; AppDomain.Unload(_Domain); _Domain = null; } }