static void CrossDomainTest (string name, CrossAppDomainDelegate dele) { Console.WriteLine ("----Testing {0}----", name); for (int i = 0; i < 20; ++i) { var ad = AppDomain.CreateDomain (string.Format ("domain-{0}-{1}", name, i)); ad.DoCallBack (dele); AppDomain.Unload (ad); } }
public ServiceWaitForm(string title, CrossAppDomainDelegate action) { InitializeComponent(); this.Font = SystemFonts.MessageBoxFont; this.ControlBox = false; this.Text = title; bw.RunWorkerAsync(action); }
/// <summary> /// Run installers (infrastructure and per endpoint) and handles profiles. /// </summary> /// <param name="args"></param> /// <param name="configFile"></param> public static void Install(string[] args, string configFile) { // Create the new appdomain with the new config. var installDomain = AppDomain.CreateDomain("installDomain", AppDomain.CurrentDomain.Evidence, new AppDomainSetup { ConfigurationFile = configFile, AppDomainInitializer = DomainInitializer, AppDomainInitializerArguments = args }); // Call the right config method in that appdomain. var del = new CrossAppDomainDelegate(RunInstall); installDomain.DoCallBack(del); }
public static void Install(IEnumerable<string> args, Type endpointConfig, string endpointName, string configFile) { // Create the new appdomain with the new config. var installDomain = AppDomain.CreateDomain("installDomain", AppDomain.CurrentDomain.Evidence, new AppDomainSetup { ConfigurationFile = configFile, AppDomainInitializer = DomainInitializer, AppDomainInitializerArguments = new[]{string.Join(";",args),endpointConfig.AssemblyQualifiedName,endpointName} }); // Call the write config method in that appdomain. var del = new CrossAppDomainDelegate(RunInstall); installDomain.DoCallBack(del); }
/// <summary> /// 跨Appdomain运行代码 /// </summary> private void CrossAppDomain() { Console.WriteLine("CurrentAppDomain start!"); //建立新的应用程序域对象 AppDomain newAppDomain = AppDomain.CreateDomain("newAppDomain"); //绑定CrossAppDomainDelegate的委托方法 CrossAppDomainDelegate crossAppDomainDelegate = new CrossAppDomainDelegate(MyCallBack); //绑定DomainUnload的事件处理方法 newAppDomain.DomainUnload += (obj, e) => { Console.WriteLine("NewAppDomain unload!"); }; //调用委托 newAppDomain.DoCallBack(crossAppDomainDelegate); AppDomain.Unload(newAppDomain); }
/// <summary> /// Invokes the specified delegate in a new <see cref="AppDomain"/>. /// </summary> /// <param name="callBackDelegate">The delegate to invoke in the new <see cref="AppDomain"/>.</param> /// <param name="appDomainData">The optional data to set for the <see cref="AppDomain"/>.</param> /// <param name="configurationFile">The optional name of the configuration file to use.</param> /// <param name="callerMemberName">The optional name of the caller of this method.</param> public static void InvokeInNewAppDomain( CrossAppDomainDelegate callBackDelegate, IDictionary<string, object> appDomainData = null, string configurationFile = null, [CallerMemberName] string callerMemberName = null) { AppDomainSetup info = AppDomain.CurrentDomain.SetupInformation; if (!string.IsNullOrEmpty(configurationFile)) { info.ConfigurationFile = configurationFile; } AppDomain domain = AppDomain.CreateDomain( callerMemberName, null, info); try { if (appDomainData != null) { foreach (var pair in appDomainData) { domain.SetData(pair.Key, pair.Value); } } if (Logger.DefaultLogger.GetType().IsMarshalByRef) { // Create an instance of the type that configures logging in the new AppDomain Type helperType = typeof(LoggingHelper); var handle = domain.CreateInstanceFrom(helperType.Assembly.Location, helperType.FullName); var helper = (LoggingHelper)handle.Unwrap(); helper.SetLogger(Logger.DefaultLogger); } domain.DoCallBack(callBackDelegate); } finally { AppDomain.Unload(domain); } }
public static int Main(string[] args) { AppDomainSetup setup = new AppDomainSetup(); setup.ApplicationBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); _serverAppDomain = AppDomain.CreateDomain("Server", null, setup); _serverAppDomain.Load(typeof(ZyanConnection).Assembly.GetName()); CrossAppDomainDelegate serverWork = new CrossAppDomainDelegate(() => { var server = EventServer.Instance; if (server != null) { Console.WriteLine("Event server started."); } }); _serverAppDomain.DoCallBack(serverWork); // Test IPC Binary int ipcBinaryTestResult = IpcBinaryTest.RunTest(); Console.WriteLine("Passed: {0}", ipcBinaryTestResult == 0); // Test TCP Binary int tcpBinaryTestResult = TcpBinaryTest.RunTest(); Console.WriteLine("Passed: {0}", tcpBinaryTestResult == 0); // Test TCP Custom int tcpCustomTestResult = TcpCustomTest.RunTest(); Console.WriteLine("Passed: {0}", tcpCustomTestResult == 0); // Test TCP Duplex int tcpDuplexTestResult = TcpDuplexTest.RunTest(); Console.WriteLine("Passed: {0}", tcpDuplexTestResult == 0); // Test HTTP Custom int httpCustomTestResult = HttpCustomTest.RunTest(); Console.WriteLine("Passed: {0}", httpCustomTestResult == 0); // Test NULL Channel const string nullChannelResultSlot = "NullChannelResult"; _serverAppDomain.DoCallBack(new CrossAppDomainDelegate(() => { int result = NullChannelTest.RunTest(); AppDomain.CurrentDomain.SetData(nullChannelResultSlot, result); })); var nullChannelTestResult = Convert.ToInt32(_serverAppDomain.GetData(nullChannelResultSlot)); Console.WriteLine("Passed: {0}", nullChannelTestResult == 0); // Stop the event server EventServerLocator locator = _serverAppDomain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, "IntegrationTest_DistributedEvents.EventServerLocator") as EventServerLocator; locator.GetEventServer().Dispose(); Console.WriteLine("Event server stopped."); if (!MonoCheck.IsRunningOnMono || MonoCheck.IsUnixOS) { // Mono/Windows bug: // AppDomain.Unload freezes in Mono under Windows if tests for // System.Runtime.Remoting.Channels.Tcp.TcpChannel were executed. AppDomain.Unload(_serverAppDomain); Console.WriteLine("Server AppDomain unloaded."); } if (ipcBinaryTestResult + tcpBinaryTestResult + tcpCustomTestResult + tcpDuplexTestResult + httpCustomTestResult + nullChannelTestResult == 0) { Console.WriteLine("All tests passed."); return 0; } return 1; }
public void DoCallBack (CrossAppDomainDelegate callBackDelegate) { Contract.Requires(callBackDelegate != null); }
// This method allows you to execute code in the // special HostingEnvironment-enabled AppDomain. private void Execute(CrossAppDomainDelegate testMethod) { this._hostingEnvironmentDomain.DoCallBack(testMethod); }
/// <summary> /// Unregisters an event on all servers. /// </summary> /// <param name="eventName">The event name to unregister.</param> /// <param name="function">The function to register to the event.</param> /// <returns>Unregistration success?</returns> public bool UnregisterEvent(string eventName, CrossAppDomainDelegate function) { for ( int i = 0; i < IModule.MaxServers; i++ ) { IRCEvents serversIrcEvents = (IRCEvents)RequestVariable( Request.IRCEvents, i ); if ( serversIrcEvents == null ) break; int loc = Algorithms.BinarySearch.EventInfoBinarySearch( eventList, eventName ); if ( loc < 0 ) return false; //Get the method we need to create a delegate to. MethodInfo mi = typeof( ModuleEvents ).GetMethod( "On" + eventName ); //Get the event we need to attach the delegate to. EventInfo ei = typeof( IRCEvents ).GetEvent( eventName ); // Servers IRCEvents Object --- CALLS --> OnPing in ModuleEvents ei.AddEventHandler( serversIrcEvents, Delegate.CreateDelegate( ei.EventHandlerType, moduleEvents, mi ) ); // ModuleLoader's ModuleEvents Object ---- CALLS --> 'function' inside the Module. ( typeof( ModuleEvents ).GetEvent( eventName, BindingFlags.Public | BindingFlags.Instance ) ) .RemoveEventHandler( this.moduleEvents, function ); } return true; }
/// <summary> /// Enables a module to register a parse that will be activated on /// the events specified by the parsetype on all servers. /// </summary> /// <param name="parse">The parse to register.</param> /// <param name="d">The function to call.</param> /// <param name="parseType">The events to add the parse to.</param> public void RegisterWildcardParse(string parse, CrossAppDomainDelegate d, IRCEvents.ParseTypes parseType) { IRCEvents.Parse p = new IRCEvents.Parse( parse, d, parseType, instanceOfModule.GetType().GetField( "parseReturns", BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.SetField ), instanceOfModule ); for ( int i = 0; i < IModule.MaxServers; i++ ) { IRCEvents serversIrcEvents = (IRCEvents)RequestVariable( Request.IRCEvents, i ); if ( serversIrcEvents == null ) break; serversIrcEvents.WildcardParses.Add( p ); } }
public Parse(string parse, CrossAppDomainDelegate function, ParseTypes ptypes, FieldInfo fi, Object instanceOf) { this.parse = parse; this.ptypes = ptypes; this.function = function; this.fi = fi; this.instanceOf = instanceOf; }
void RunSample(Control parent, ExampleInfo e) { if (e == null) return; MethodInfo main = e.Example.GetMethod("Main", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) ?? e.Example.GetMethod("Main", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { typeof(object), typeof(object) }, null); if (main != null) { try { if (parent != null) { parent.Visible = false; Application.DoEvents(); } Trace.WriteLine(String.Format("Launching sample: \"{0}\"", e.Attribute.Title)); Trace.WriteLine(String.Empty); AppDomain sandbox = AppDomain.CreateDomain("Sandbox"); sandbox.DomainUnload += HandleSandboxDomainUnload; SampleRunner runner = new SampleRunner(main); CrossAppDomainDelegate cross = new CrossAppDomainDelegate(runner.Invoke); sandbox.DoCallBack(cross); AppDomain.Unload(sandbox); } finally { if (parent != null) { textBoxOutput.Text = File.ReadAllText("debug.log"); parent.Visible = true; Application.DoEvents(); } } } else { MessageBox.Show("The selected example does not define a Main method", "Entry point not found", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
private static void RunInPartialTrust(CrossAppDomainDelegate testMethod) { Assert.IsTrue(Assembly.GetExecutingAssembly().IsFullyTrusted); AppDomainSetup setup = new AppDomainSetup(); setup.ApplicationBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); PermissionSet perms = PermissionsHelper.InternetZone; AppDomain domain = AppDomain.CreateDomain("PartialTrustSandBox", null, setup, perms); domain.DoCallBack(testMethod); }
public static int Main(string[] args) { AppDomainSetup setup = new AppDomainSetup(); setup.ApplicationBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); _serverAppDomain = AppDomain.CreateDomain("Server", null, setup); _serverAppDomain.Load("Zyan.Communication"); CrossAppDomainDelegate serverWork = new CrossAppDomainDelegate(() => { EventServer server = EventServer.Instance; }); _serverAppDomain.DoCallBack(serverWork); //TcpCustomClientProtocolSetup protocol = new TcpCustomClientProtocolSetup(true); MsmqClientProtocolSetup protocol = new MsmqClientProtocolSetup(); //_connection = new ZyanConnection("tcp://localhost:8083/EventTest",protocol); _connection = new ZyanConnection(@"msmq://private$/reqchannel/EventTest", protocol); _proxySingleton = _connection.CreateProxy<IEventComponentSingleton>(); _proxySingleCall = _connection.CreateProxy<IEventComponentSingleCall>(); _proxyCallbackSingleton = _connection.CreateProxy<ICallbackComponentSingleton>(); _proxyCallbackSingleCall = _connection.CreateProxy<ICallbackComponentSingleCall>(); _proxyRequestResponseSingleCall = _connection.CreateProxy<IRequestResponseCallbackSingleCall>(); int successCount = 0; _proxyCallbackSingleton.Out_Callback = CallBackSingleton; _proxyCallbackSingleCall.Out_Callback = CallBackSingleCall; _proxyCallbackSingleton.DoSomething(); if (_callbackCountSingleton == 1) { successCount++; Console.WriteLine("Singleton Callback Test passed."); } _proxyCallbackSingleCall.DoSomething(); if (_callbackCountSingleCall == 1) { successCount++; Console.WriteLine("SingleCall Callback Test passed."); } RegisterEvents(); if (_registrationsSingleton == _proxySingleton.Registrations) successCount++; if (_registrationsSingleCall == _proxySingleCall.Registrations) successCount++; _proxySingleton.TriggerEvent(); if (_firedCountSingleton == 1) { successCount++; Console.WriteLine("Singleton Event Test passed."); } _proxySingleCall.TriggerEvent(); if (_firedCountSingleCall == 1) { successCount++; Console.WriteLine("SingleCall Event Test passed."); } UnregisterEvents(); if (_registrationsSingleton == _proxySingleton.Registrations) successCount++; if (_registrationsSingleCall == _proxySingleCall.Registrations) successCount++; RequestResponseResult requestResponseResult = new RequestResponseResult(); _proxyRequestResponseSingleCall.DoRequestResponse("Success", requestResponseResult.ReceiveResponseSingleCall); Thread.Sleep(1000); if (requestResponseResult.Count == 1) successCount++; _connection.Dispose(); EventServerLocator locator = _serverAppDomain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, "IntegrationTest_DistributedEvents.EventServerLocator") as EventServerLocator; locator.GetEventServer().Dispose(); AppDomain.Unload(_serverAppDomain); if (successCount == 9) return 0; else return 1; }
public void DoCallBack(CrossAppDomainDelegate action) { this.domain.DoCallBack(action); }
public void DoCallBack(CrossAppDomainDelegate callBackDelegate) { }
public static void StopServer() { #region TCP Duplex try { CrossAppDomainDelegate serverWork = new CrossAppDomainDelegate(() => { TcpDuplexServerHostEnvironment.Instance.Dispose(); }); _tcpDuplexServerAppDomain.DoCallBack(serverWork); } finally { AppDomain.Unload(_tcpDuplexServerAppDomain); } #endregion #region TCP Simplex try { CrossAppDomainDelegate serverWork = new CrossAppDomainDelegate(() => { TcpSimplexServerHostEnvironment.Instance.Dispose(); }); _tcpSimplexServerAppDomain.DoCallBack(serverWork); } finally { AppDomain.Unload(_tcpSimplexServerAppDomain); } #endregion }
public void DoCallBack(CrossAppDomainDelegate callBackDelegate) { if (callBackDelegate == null) { throw new ArgumentNullException("callBackDelegate"); } callBackDelegate(); }
public static void StartServers(TestContext ctx) { #region TCP Duplex // Setup TCP Duplex Server AppDomain AppDomainSetup tcpDuplexAppDomainSetup = new AppDomainSetup() { ApplicationBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) }; _tcpDuplexServerAppDomain = AppDomain.CreateDomain("RecreateClientConnectionTests_Server", null, tcpDuplexAppDomainSetup); _tcpDuplexServerAppDomain.Load(typeof(ZyanConnection).Assembly.GetName()); // Start Zyan host inside the TCP Duplex Server AppDomain var tcpDuplexServerWork = new CrossAppDomainDelegate(() => { var server = TcpDuplexServerHostEnvironment.Instance; if (server != null) { Console.WriteLine("TCP Duplex Server running."); } }); _tcpDuplexServerAppDomain.DoCallBack(tcpDuplexServerWork); #endregion #region TCP Simplex // Setup TCP Simplex Server AppDomain AppDomainSetup tcpSimplexAppDomainSetup = new AppDomainSetup() { ApplicationBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) }; _tcpSimplexServerAppDomain = AppDomain.CreateDomain("RecreateClientConnectionTests_Server", null, tcpSimplexAppDomainSetup); _tcpSimplexServerAppDomain.Load(typeof(ZyanConnection).Assembly.GetName()); // Start Zyan host inside the TCP Simplex Server AppDomain var tcpSimplexServerWork = new CrossAppDomainDelegate(() => { var server = TcpSimplexServerHostEnvironment.Instance; if (server != null) { Console.WriteLine("TCP Simplex Server running."); } }); _tcpSimplexServerAppDomain.DoCallBack(tcpSimplexServerWork); #endregion }
private void DoTestWithPartialTrust( CrossAppDomainDelegate test ) { var appDomainSetUp = new AppDomainSetup() { ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase }; var evidence = new Evidence(); evidence.AddHostEvidence( new Zone( SecurityZone.Internet ) ); var permisions = SecurityManager.GetStandardSandbox( evidence ); AppDomain workerDomain = AppDomain.CreateDomain( "PartialTrust", evidence, appDomainSetUp, permisions, GetStrongName( this.GetType() ) ); try { workerDomain.DoCallBack( test ); } finally { AppDomain.Unload( workerDomain ); } }
/// <summary> /// Registers an event to all servers. /// </summary> /// <param name="eventName">The event name to register.</param> /// <param name="function">The function to register to the event.</param> /// <returns>Registration success?</returns> public bool RegisterEvent(string eventName, CrossAppDomainDelegate function) { int loc = Algorithms.BinarySearch.EventInfoBinarySearch( eventList, eventName ); if ( loc < 0 ) return false; //Get the method we need to create a delegate to. MethodInfo mi = typeof( ModuleEvents ).GetMethod( "On" + eventName ); //Get the event we need to attach the delegate to. EventInfo ei = typeof( IRCEvents ).GetEvent( eventName ); for ( int i = 0; i < IModule.MaxServers; i++ ) { IRCEvents serversIrcEvents = (IRCEvents)RequestVariable( Request.IRCEvents, i ); if ( serversIrcEvents == null ) break; //When we add an event from IRCEvents --- CALLS --> OnEvent in ModuleEvents. //We can't let it add twice. ModuleEvents keeps it's own list of methods to call in the module it's on. //So if the method we would add to IRCEvents' handler is found in the IRCEvents.EventName delegate //we should not add it PROVIDING that the moduleEvents target on that handler is the same object as the one //we hold in our current ModuleProxy object. FieldInfo fi = typeof( IRCEvents ).GetField( eventName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField ); object o = fi.GetValue( serversIrcEvents ); Delegate d = (Delegate)o; bool addToIRCEvents = true; if ( d != null ) { Delegate[] invocList = d.GetInvocationList(); foreach ( Delegate invoc in invocList ) { if ( invoc.Method.Equals( mi ) && this.moduleEvents.GetHashCode() == invoc.Target.GetHashCode() ) addToIRCEvents = false; } } if ( addToIRCEvents ) // Servers IRCEvents Object --- CALLS --> OnPing in ModuleEvents ei.AddEventHandler( serversIrcEvents, Delegate.CreateDelegate( ei.EventHandlerType, moduleEvents, mi ) ); // ModuleLoader's ModuleEvents Object ---- CALLS --> 'function' inside the Module. ( typeof( ModuleEvents ).GetEvent( eventName, BindingFlags.Public | BindingFlags.Instance ) ) .AddEventHandler( this.moduleEvents, function ); } return true; }
/// <summary> /// Enables a module to register a parse that will be activated on /// the events specified by the parsetype on all servers. /// </summary> /// <param name="parse">The parse to register.</param> /// <param name="d">The function to call.</param> /// <param name="parseType">The events to add the parse to.</param> public void RegisterParse(string parse, CrossAppDomainDelegate d, IRCEvents.ParseTypes parseType) { IRCEvents.Parse p = new IRCEvents.Parse( parse, d, parseType, instanceOfModule.GetType().GetField( "parseReturns", BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.SetField ), instanceOfModule ); for ( int k = 0; k < IModule.MaxServers; k++ ) { IRCEvents serversIrcEvents = (IRCEvents)RequestVariable( Request.IRCEvents, k ); if ( serversIrcEvents == null ) break; if ( serversIrcEvents.Parses.Count == 0 ) serversIrcEvents.Parses.Add( p ); else { for ( int i = 0; i < serversIrcEvents.Parses.Count; i++ ) if ( serversIrcEvents.Parses[i].ParseString.CompareTo( parse ) >= 0 ) { serversIrcEvents.Parses.Insert( i, p ); //I hope to god this shoves to the right and not the left. return; } serversIrcEvents.Parses.Insert( serversIrcEvents.Parses.Count - 1, p ); } } }
// // AppDomain.DoCallBack works because AppDomain is a MarshalByRefObject // so, when you call AppDomain.DoCallBack, that's a remote call // public void DoCallBack (CrossAppDomainDelegate callBackDelegate) { if (callBackDelegate != null) callBackDelegate (); }
/// <summary> /// Enables a module to register a parse that will be activated on /// the events specified by the parsetype. /// </summary> /// <param name="parse">The parse to register.</param> /// <param name="serverid">The server to register the parse to.</param> /// <param name="d">The function to call.</param> /// <param name="parseType">The events to add the parse to.</param> public void RegisterWildcardParse(string parse, int serverid, CrossAppDomainDelegate d, IRCEvents.ParseTypes parseType) { IRCEvents.Parse p = new IRCEvents.Parse( parse, d, parseType, instanceOfModule.GetType().GetField("parseReturns", BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.SetField ), instanceOfModule ); IRCEvents serversIrcEvents = (IRCEvents)RequestVariable( Request.IRCEvents, serverid ); serversIrcEvents.WildcardParses.Add( p ); }
// This is useful for requesting execution of some code // in another appDomain ... the delegate may be defined // on a marshal-by-value object or a marshal-by-ref or // contextBound object. public void DoCallBack(CrossAppDomainDelegate callBackDelegate) { if (callBackDelegate == null) throw new ArgumentNullException("callBackDelegate"); Contract.EndContractBlock(); callBackDelegate(); }
public void DoCallBack(CrossAppDomainDelegate theDelegate) { // TODO // for now just call it directly theDelegate(); }