コード例 #1
0
        private void ExecuteInSeparateAppDomain(CrossAppDomainDelegate test)
        {
            AppDomain appDomain = null;

            try
            {
                var appDomainSetup = new AppDomainSetup();
                appDomainSetup.ApplicationName = "Test";
                appDomainSetup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                appDomainSetup.PrivateBinPath  = _searchPathForDllsBuildOutputManager.BuildOutputDirectory + ";" + _searchPathForExesBuildOutputManager.BuildOutputDirectory;
                appDomainSetup.DynamicBase     = _dynamicDirectoryBuildOutputManager.BuildOutputDirectory;
                appDomainSetup.ShadowCopyFiles = AppDomain.CurrentDomain.SetupInformation.ShadowCopyFiles;

                appDomain = AppDomain.CreateDomain("Test", null, appDomainSetup);

                appDomain.DoCallBack(test);
            }
            finally
            {
                if (appDomain != null)
                {
                    AppDomain.Unload(appDomain);
                }
            }
        }
コード例 #2
0
        private void AksForInstance()
        {
            tiaPortal = new Siemens.Engineering.TiaPortal(Siemens.Engineering.TiaPortalMode.WithoutUserInterface);

            var       processes           = TiaPortal.GetProcesses().ToArray();
            var       sLst                = processes.Select(x => "Projekt : " + (x.ProjectPath != null ? x.ProjectPath.ToString() : "-")).ToArray();
            AppDomain domain              = AppDomain.CreateDomain("another domain");
            CrossAppDomainDelegate action = () =>
            {
                var app = new Application();
                var ask = new SelectPortalInstance();
                var p   = AppDomain.CurrentDomain.GetData("processes") as string[];
                ask.lstInstances.ItemsSource = p;
                app.Run(ask);
                AppDomain.CurrentDomain.SetData("idx", ask.lstInstances.SelectedIndex);
            };

            domain.SetData("processes", sLst);
            domain.DoCallBack(action);
            var idx = (int)domain.GetData("idx");

            tiaPortal        = processes[idx].Attach();
            tiapProject      = tiaPortal.Projects[0];
            this.ProjectFile = processes[idx].ProjectPath.ToString();
        }
コード例 #3
0
        static void Main()
        {
            //var app = new App();
            //app.MainWindow = new Window1();
            //app.MainWindow.Show();
            //app.Run();

            var domain  = AppDomain.CreateDomain("first domain");
            var domain2 = AppDomain.CreateDomain("second domain");

            domain2.UnhandledException += (sender, args) =>
            {
                Debug.WriteLine("domain2 exception");
            };
            CrossAppDomainDelegate action = () =>
            {
                var thread = new Thread(() =>
                {
                    var app = new App {
                        MainWindow = new Window1()
                    };
                    app.MainWindow.Show();
                    app.Run();
                });
                thread.SetApartmentState(ApartmentState.STA);
                thread.Start();
            };

            CrossAppDomainDelegate action2 = () =>
            {
                var thread = new Thread(() =>
                {
                    var app = new App {
                        MainWindow = new Window2()
                    };

                    app.DispatcherUnhandledException += (sender, args) =>
                    {
                        //args.Handled = true;
                        Debug.WriteLine("DispatcherUnhandledException");
                    };

                    app.MainWindow.Show();
                    app.Run();
                });
                thread.SetApartmentState(ApartmentState.STA);
                thread.Start();
            };

            domain.DoCallBack(action);
            domain2.DoCallBack(action2);

            var a = new App
            {
                MainWindow = new Window1()
            };

            a.MainWindow.Show();
            a.Run();
        }
コード例 #4
0
        static void Main(string[] args)
        {
            // Read the main configuration file
            var xmlDoc = ReadConfiguration();

            // if MQ is installed, we need to inject in the configuration file
            // the necessary bindingredirect to use the amqmdnet installed in the GAC (even if older than the one ship with the tool)
            string mqVersion;
            bool   mqInstalled = CheckMqInstalled(out mqVersion);

            if (mqInstalled)
            {
                AddBindingRedirect(xmlDoc, mqVersion);
            }

            // Prepare a new application domain setup with the modified configuration file
            var config = xmlDoc.ToString();
            var setup  = new AppDomainSetup();

            setup.SetConfigurationBytes(Encoding.Default.GetBytes(config));
            var newdomain = AppDomain.CreateDomain("MQExplorerPlusWithRightAPI", new Evidence(), setup);

            CrossAppDomainDelegate startupaction = () =>
            {
                Thread thread = new Thread(() =>
                {
                    App.Main();
                });
                thread.SetApartmentState(
                    ApartmentState.STA);
                thread.Start();
            };

            newdomain.DoCallBack(startupaction);
        }
コード例 #5
0
        private void LoadFileRenamer()
        {
            //if (application == null)
            // {
            //     application = new FileRenamer.App { ShutdownMode = System.Windows.ShutdownMode.OnExplicitShutdown };
            // }

            //application.StartFromExtension(SelectedItemPaths);

            var domain1 = AppDomain.CreateDomain("FileRenamer");
            CrossAppDomainDelegate action = () =>
            {
                Thread thread = new Thread(() =>
                {
                    App app = new App();
                    app.StartFromExtension(SelectedItemPaths);
                    //app.MainWindow = new Window1();
                    //app.MainWindow.Show();
                    app.Run();
                });
                thread.SetApartmentState(
                    ApartmentState.STA);
                thread.Start();
            };
        }
コード例 #6
0
        /// <summary>
        /// Warning! Very expensive. Creates an appdomain, unpacks a mod, and inspects its contents
        /// to get a list of all files in the mod. Then it builds the metadata from the information.
        /// </summary>
        public static ModMetadata CreateMetadata(string modFile, bool verifySafe)
        {
            if (_cache.ContainsKey(modFile.ToLower()))
            {
                return(_cache[modFile.ToLower()]);
            }

            ModMetadata meta = null;

            var domain = AppDomain.CreateDomain($"__Temp__ModMetadata::CreateMetadata({modFile})");

            domain.Load(new System.Reflection.AssemblyName(typeof(ModMetadata).Assembly.FullName));

            domain.SetData("__create__modFile", modFile);
            domain.SetData("__create__verifySafe", verifySafe);
            //Flag the domain for special case usage - avoid loading the entire metadata cache which we will not use.
            domain.SetData("__metadata__creation__domain", "not null, i swear");
            var crossDomainTarget = new CrossAppDomainDelegate(Create);

            domain.DoCallBack(crossDomainTarget);
            meta = DeepClone((ModMetadata)domain.GetData("__create__return__metadata"));

            AppDomain.Unload(domain);

            _cache.Add(modFile.ToLower(), meta);
            Save();

            return(meta);
        }
コード例 #7
0
 public static void ExecuteInCloneDomainScope(CrossAppDomainDelegate action, TimeSpan?disposeDelay = null, bool suppressUnloadErrors = false)
 {
     using (var cloneDomainContext = AppDomain.CurrentDomain.CloneScope(disposeDelay: disposeDelay, suppressUnloadErrors: suppressUnloadErrors))
     {
         cloneDomainContext.CloneDomain.DoCallBack(action);
     }
 }
コード例 #8
0
 //
 // 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();
     }
 }
コード例 #9
0
        static void Main()
        {
            Console.WriteLine(AppDomain.CurrentDomain.FriendlyName);

            // Create a new AppDoamin
            AppDomain ad = AppDomain.CreateDomain("Playground Domain");

            // Register domain event handlers
            ad.AssemblyLoad += new AssemblyLoadEventHandler(AssemblyLoadHandler);
            ad.DomainUnload += new EventHandler(DomainUnloadHandler);

            // Exchange data between AppDomains
            ad.SetData("Creator", AppDomain.CurrentDomain);

            // Load and execute assembly in domain
            ad.ExecuteAssembly("Playground.exe");

            // Execute some code in a different AppDomain
            CrossAppDomainDelegate cadd = new CrossAppDomainDelegate(CrossAppDomainCallback);

            ad.DoCallBack(cadd);

            // Create object in another AppDomain
            string   path = Path.Combine(Directory.GetCurrentDirectory(), "DomainMasterSample.exe");
            Assembly a    = Assembly.LoadFile(path);

            ad.Load(a.GetName());
            AppDomainExplorer ade = ad.CreateInstanceAndUnwrap(a.GetName().FullName, "DomainMasterSample.AppDomainExplorer") as AppDomainExplorer;

            ade.Explore();

            // Unload the domain
            AppDomain.Unload(ad);
            Console.ReadLine();
        }
コード例 #10
0
        private static void Main()
        {
            Console.Write("===== AUTOFOOD v1.4.6 =====");

            var domain = AppDomain.CreateDomain(Guid.NewGuid().ToString());

            var controle = new ControleDeAlimentos.ControleDeAlimentos();

            controle.CriaEstoque();

            CrossAppDomainDelegate action = () =>
            {
                var thread = new Thread(() =>
                {
                    ControleDePedido.App app = new ControleDePedido.App();
                    app.InitializeComponent();
                    app.Run();
                });
                thread.SetApartmentState(ApartmentState.STA);

                thread.Start();
            };

            domain.DoCallBack(action);

            Console.ReadKey();
        }
コード例 #11
0
ファイル: frmMenu.cs プロジェクト: bugbit/AprenderAProgramar
        private void Run(Type argPrgType)
        {
            var pMain =
                argPrgType.GetMethod("Main", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) ??
                argPrgType.GetMethod("Main", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] {
                typeof(object),
                typeof(object)
            }, null);

            if (pMain == null)
            {
                return;
            }

            try
            {
                Visible = false;

                var pSandbox = AppDomain.CreateDomain("Sandbox");
                var pRunner  = new ProgramRunner(pMain);
                var pCross   = new CrossAppDomainDelegate(pRunner.Invoke);

                pSandbox.DoCallBack(pCross);
                AppDomain.Unload(pSandbox);
            }
            finally
            {
                Visible = true;
            }
        }
コード例 #12
0
 private void ExecuteInitializer(CrossAppDomainDelegate executor)
 {
     try
     {
         this.appDomain.DoCallBack(executor);
     }
     catch (ThreadAbortException)
     {
         Thread.ResetAbort();
     }
     catch (Exception value)
     {
         if (this.ExceptionOccur != null)
         {
             this.ExceptionOccur(this, new EventArgs <Exception>(value));
         }
     }
     finally
     {
         try
         {
             AppDomain.Unload(this.appDomain);
         }
         catch
         {
         }
         if (this.Finalized != null)
         {
             this.Finalized(this, EventArgs.Empty);
         }
     }
 }
コード例 #13
0
ファイル: sgen-domain-unload.cs プロジェクト: Zman0169/mono
	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);
		}
	}
コード例 #14
0
        /// <summary>
        /// Extends BeginInvoke so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// crossappdomaindelegate.BeginInvoke(callback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginInvoke(this CrossAppDomainDelegate crossappdomaindelegate, AsyncCallback callback)
        {
            if (crossappdomaindelegate == null)
            {
                throw new ArgumentNullException("crossappdomaindelegate");
            }

            return(crossappdomaindelegate.BeginInvoke(callback, null));
        }
コード例 #15
0
        public static void ExecuteCallbackInChildAppDomain(string[] args, CrossAppDomainDelegate callback)
        {
            var domain = CreateDomain(args);

            if (domain != null)
            {
                domain.DoCallBack(callback);
            }
        }
コード例 #16
0
ファイル: ServiceWaitForm.cs プロジェクト: WORawSon/VhdAttach
        public ServiceWaitForm(string title, CrossAppDomainDelegate action)
        {
            InitializeComponent();
            this.Font = SystemFonts.MessageBoxFont;
            this.ControlBox = false;

            this.Text = title;
            bw.RunWorkerAsync(action);
        }
コード例 #17
0
        private void Run(CrossAppDomainDelegate a)
        {
            var domain = AppDomain.CreateDomain(Guid.NewGuid().ToString(), null, new AppDomainSetup {
                ApplicationBase = AppDomain.CurrentDomain.BaseDirectory
            });

            domain.DoCallBack(a);
            AppDomain.Unload(domain);
        }
コード例 #18
0
        public ServiceWaitForm(string title, CrossAppDomainDelegate action)
        {
            InitializeComponent();
            this.Font       = SystemFonts.MessageBoxFont;
            this.ControlBox = false;

            this.Text = title;
            bw.RunWorkerAsync(action);
        }
コード例 #19
0
 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);
     }
 }
コード例 #20
0
        private static void RunInPartialTrust(CrossAppDomainDelegate testMethod)
        {
            Assert.True(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);
        }
コード例 #21
0
    static void CrossDomainTest(string name, CrossAppDomainDelegate dele)
    {
        TestTimeout timeout = TestTimeout.Start(TimeSpan.FromSeconds(TestTimeout.IsStressTest ? 60 : 5));

        Console.WriteLine("----Testing {0}----", name);
        for (int i = 0; timeout.HaveTimeLeft; ++i)
        {
            var ad = AppDomain.CreateDomain(string.Format("domain-{0}-{1}", name, i));
            ad.DoCallBack(dele);
            AppDomain.Unload(ad);
        }
    }
コード例 #22
0
        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);
        }
コード例 #23
0
        public void Test()
        {
            //进程下加载的模块
            var moduleList = Process.GetCurrentProcess().Modules;

            foreach (ProcessModule module in moduleList)
            {
                Console.WriteLine(string.Format("{0}\n  URL:{1}\n  Version:{2}",
                                                module.ModuleName, module.FileName, module.FileVersionInfo.FileVersion));
            }

            var appDomain = AppDomain.CreateDomain("NewAppDomain");

            appDomain.Load("UtilsLib");
            appDomain.DomainUnload += (s, e) =>
            {
                Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " " + AppDomain.CurrentDomain.Id + AppDomain.CurrentDomain.FriendlyName + " unload");
            };

            foreach (var assembly in appDomain.GetAssemblies())
            {
                Console.WriteLine(string.Format("{0}\n----------------------------", assembly.FullName));
            }

            CrossAppDomainDelegate crossAppDomainDelegate = DoAppDomainCallBack;

            appDomain.DoCallBack(crossAppDomainDelegate);
            AppDomain.Unload(appDomain);

            //ContextBound contextBound = new ContextBound();
            //Task.Factory.StartNew(() =>
            //{
            //    contextBound.GetMoney(600);
            //});
            //Task.Factory.StartNew(() =>
            //{
            //    contextBound.GetMoney(600);
            //});

            NormalMoney normalMoney = new NormalMoney();

            Task.Factory.StartNew(() =>
            {
                normalMoney.GetMoney(600);
            });
            Task.Factory.StartNew(() =>
            {
                normalMoney.GetMoney(600);
            });
        }
コード例 #24
0
        /// <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);
        }
コード例 #25
0
        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
        }
コード例 #26
0
ファイル: ExampleBrowser.cs プロジェクト: zero10/scallion
        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);
            }
        }
コード例 #27
0
        public static void Main0()
        {
            AppDomain domainA;

            domainA = AppDomain.CreateDomain("MyDomainA");
            string stringA = "DomainA Value";

            domainA.SetData("DomainKey", stringA);

            CommonCallBack();
            CrossAppDomainDelegate delegateA =
                new CrossAppDomainDelegate(CommonCallBack);

            domainA.DoCallBack(CommonCallBack);
        }
コード例 #28
0
        /// <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);
        }
コード例 #29
0
        static void Main()
        {
            AppDomain DomainA;

            DomainA = AppDomain.CreateDomain("MyDomainA");
            string StringA = "DomainA Value";

            DomainA.SetData("DomainKey", StringA);

            CommonCallBack();
            CrossAppDomainDelegate delegateA = new CrossAppDomainDelegate(CommonCallBack);

            DomainA.DoCallBack(delegateA);
            Console.ReadLine();
        }
コード例 #30
0
        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);
        }
コード例 #31
0
 /// <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);
 }
コード例 #32
0
        /// <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);
                    }
                }

                ILogger logger = Logger.DefaultLogger.Value;

                if (logger.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);
                }

                domain.DoCallBack(callBackDelegate);
            }
            finally
            {
                AppDomain.Unload(domain);
            }
        }
コード例 #33
0
ファイル: GeneralTests.cs プロジェクト: tloy1966/TuesPechkin
        public void ConvertsAfterAppDomainRecycles()
        {
            // arrange
            var domain1 = this.GetAppDomain("testing_unload_1");

            byte[] result1 = null;
            var    domain2 = this.GetAppDomain("testing_unload_2");

            byte[] result2 = null;
            CrossAppDomainDelegate callback = () =>
            {
                var dllPath = AppDomain.CurrentDomain.GetData("dllpath") as string;

                var converter =
                    new ThreadSafeConverter(
                        new RemotingToolset <PdfToolset>(
                            new StaticDeployment(dllPath)));

                var document = new HtmlToPdfDocument
                {
                    Objects =
                    {
                        new ObjectSettings {
                            PageUrl = "www.google.com"
                        }
                    }
                };

                AppDomain.CurrentDomain.SetData("result", converter.Convert(document));
            };

            // act
            domain1.SetData("dllpath", GetDeploymentPath());
            domain1.DoCallBack(callback);
            result1 = domain1.GetData("result") as byte[];
            AppDomain.Unload(domain1);

            domain2.SetData("dllpath", GetDeploymentPath());
            domain2.DoCallBack(callback);
            result2 = domain2.GetData("result") as byte[];
            AppDomain.Unload(domain2);

            // assert
            Assert.IsNotNull(result1);
            Assert.IsNotNull(result2);
        }
コード例 #34
0
    static void Main(string[] args)
    {
        // Setup information for the new appdomain.
        AppDomainSetup setup = new AppDomainSetup();

        setup.ConfigurationFile = "C:\\my.config";
        // Create the new appdomain with the new config.
        AppDomain d2 = AppDomain.CreateDomain("customDomain", AppDomain.CurrentDomain.Evidence, setup);
        // Call the write config method in that appdomain.
        CrossAppDomainDelegate del = new CrossAppDomainDelegate(WriteConfig);

        d2.DoCallBack(del);

        // Call the write config in our appdomain.
        WriteConfig();
        Console.ReadLine();
    }
コード例 #35
0
        public static void StopServer()
        {
            Trace.WriteLine("** Stopping the server! **");

            try
            {
                CrossAppDomainDelegate serverWork = new CrossAppDomainDelegate(() =>
                {
                    TcpDuplexServerHostEnvironment.Instance.Dispose();
                });
                _tcpDuplexServerAppDomain.DoCallBack(serverWork);
            }
            finally
            {
                AppDomain.Unload(_tcpDuplexServerAppDomain);
            }
        }
コード例 #36
0
ファイル: Helpers.cs プロジェクト: gitter-badger/sqllocaldb
        /// <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);
            }
        }
コード例 #37
0
ファイル: IRCEvents.cs プロジェクト: aarondl/Project-2Q
 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;
 }
コード例 #38
0
ファイル: ModuleProxy.cs プロジェクト: aarondl/Project-2Q
        /// <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;
        }
コード例 #39
0
ファイル: Program.cs プロジェクト: yallie/zyan
        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://*****:*****@"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;
        }
コード例 #40
0
ファイル: ModuleProxy.cs プロジェクト: aarondl/Project-2Q
        /// <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 );
                }

            }
        }
コード例 #41
0
ファイル: ModuleProxy.cs プロジェクト: aarondl/Project-2Q
        /// <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 );
        }
コード例 #42
0
        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);
            }
        }
コード例 #43
0
ファイル: ModuleProxy.cs プロジェクト: aarondl/Project-2Q
        /// <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 );
            }
        }
コード例 #44
0
ファイル: Program.cs プロジェクト: yallie/zyan
        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;
        }
コード例 #45
0
ファイル: ModuleProxy.cs プロジェクト: aarondl/Project-2Q
        /// <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;
        }
コード例 #46
0
ファイル: AppDomain.cs プロジェクト: rabink/mono
		//
		// 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 ();
		}
コード例 #47
0
 // This method allows you to execute code in the
 // special HostingEnvironment-enabled AppDomain.
 private void Execute(CrossAppDomainDelegate testMethod)
 {
     this._hostingEnvironmentDomain.DoCallBack(testMethod);
 }
コード例 #48
0
		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 );
			}
		}
コード例 #49
0
        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
        }
コード例 #50
0
        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);
        }
コード例 #51
0
        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
        }
コード例 #52
0
 public void DoCallBack (CrossAppDomainDelegate callBackDelegate) {
     Contract.Requires(callBackDelegate != null);
 }
コード例 #53
0
 public void DoCallBack(CrossAppDomainDelegate callBackDelegate)
 {
 }
コード例 #54
0
ファイル: AppDomain.cs プロジェクト: randomize/VimConfig
 public void DoCallBack(CrossAppDomainDelegate callBackDelegate)
 {
     if (callBackDelegate == null)
     {
         throw new ArgumentNullException("callBackDelegate");
     }
     callBackDelegate();
 }
コード例 #55
0
ファイル: DisposableDomain.cs プロジェクト: Brar/entlib
 public void DoCallBack(CrossAppDomainDelegate action)
 {
     this.domain.DoCallBack(action);
 }
コード例 #56
0
        // 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();        
        }
コード例 #57
0
	public void DoCallBack(CrossAppDomainDelegate theDelegate)
			{
				// TODO
				// for now just call it directly
				theDelegate();
			}