public void LaunchAppDomain(int param) { UnloadAppDomain(); QAppDomain = AppDomain.CreateDomain("QAppDomain"); AppDomain.MonitoringIsEnabled = true; string path = Win32Hooks.HookManager.Instance.AssemblyPath; switch (param) { case 0: //QuestorManagerDomain.ExecuteAssembly(assemblyFolder + "\\Questor\\Questor.exe",args: new String[] {"-i"}); t = new Thread(delegate() { QAppDomain.ExecuteAssembly(path + "\\Questor\\Questor.exe", args: new String[] { "-i", "-c", Win32Hooks.HookManager.Instance.CharName, "-u", Win32Hooks.HookManager.Instance.AccountName, "-p", Win32Hooks.HookManager.Instance.Password }); }); t.Start(); break; case 1: t = new Thread(delegate() { QAppDomain.ExecuteAssembly(path + "\\Questor\\QuestorManager.exe", args: new String[] { "-i" }); }); t.Start(); break; case 2: t = new Thread(delegate() { QAppDomain.ExecuteAssembly(path + "\\Questor\\ValueDump.exe", args: new String[] { "-i" }); }); t.Start(); break; default: break; } }
static int Main(string[] args) { switch (args.Length) { case 0: Console.WriteLine("Create a restricted sandbox to execute an assembly."); Console.WriteLine("Usage: mono sandbox.exe [@namedpermissionset | permissionset.xml] assembly.exe [parameters ...]"); return(0); case 1: Console.WriteLine("Using default (current) appdomain to load '{0}'...", args [0]); return(AppDomain.CurrentDomain.ExecuteAssembly(args [0])); case 2: AppDomain ad = CreateRestrictedDomain(args [0]); return(ad.ExecuteAssembly(args [1])); default: ad = CreateRestrictedDomain(args [0]); string[] newargs = new string [args.Length - 2]; for (int i = 2; i < args.Length; i++) { newargs [i - 2] = args [i]; } return(ad.ExecuteAssembly(args [1], null, newargs)); } }
public static void DoScan(TestContext context) { string tempProjectPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); DirectorySecurity directorySecurity = new DirectorySecurity(); directorySecurity.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow)); tempProjectDirectory = Directory.CreateDirectory(tempProjectPath, directorySecurity); AppDomain scanDomain = AppDomain.CreateDomain("Scanner Test Domain"); try { ZipFile.ExtractToDirectory(@"TestApp.zip", tempProjectPath); string executablePath = Path.Combine(tempProjectDirectory.FullName, "QuackHackAdmin.exe"); string outputFilePath = Path.Combine(tempProjectDirectory.FullName, "scanresult.json"); scanDomain.ExecuteAssembly("Scanner.exe", new string[] { executablePath, "-o", outputFilePath }); string scanResultJsonText = File.ReadAllText(outputFilePath); Assert.IsFalse(string.IsNullOrWhiteSpace(scanResultJsonText)); //Construct the Json scanOutputJson = JsonConvert.DeserializeObject <JObject>(scanResultJsonText); } finally { AppDomain.Unload(scanDomain); tempProjectDirectory.Delete(true); } }
public void CanLaunchExeFromWithinSameProcessAsThis() { AppDomain domain = AppDomain.CreateDomain("Testing"); domain.ExecuteAssembly("Eca.Spikes.WinFormsApplication.exe"); AppDomain.Unload(domain); }
static void Main(string[] args) { AppDomain testApp = AppDomain.CreateDomain("testApp"); try { args = new string[] { }; string path = ConfigurationManager.AppSettings.Get("testApp"); //subscribe to ProcessExit before executing the assembly testApp.ProcessExit += (sender, e) => { //do nothing or do anything Console.WriteLine("The appdomain ended"); Console.WriteLine("Press any key to end this program"); Console.ReadKey(); }; testApp.ExecuteAssembly(path); } catch (Exception ex) { //Catch process here } finally { AppDomain.Unload(testApp); } }
[STAThread] // This is needed for WPF apps, not sure about other //TODO: would there be a case where MTA is needed? //"they must protect their internal state against concurrent calls, in case they're loaded in the MTA, but must not block, in case they're loaded in an STA." //http://stackoverflow.com/a/127340/66372 //"If you're only going to consume COM components all that you really need to know is that you have to match the apartment to the component or nasty things will happen." //http://stackoverflow.com/a/485109/66372 static void Main(string[] args) { string OSBOXPARAMS = Environment.GetEnvironmentVariable("OSBOXPARAMS"); int delimPos = OSBOXPARAMS.IndexOf(" "); //TODO: could an access violation exception be coming from .OpenExisting - http://msdn.microsoft.com/en-US/library/530zssyk(v=VS.80).aspx // i.e. "If you run the compiled example from two command windows, the second copy will throw an access violation exception on the call to OpenExisting(String)." EventWaitHandle injectionDone = EventWaitHandle.OpenExisting(OSBOXPARAMS.Substring(0, delimPos)); string assemblyPath = OSBOXPARAMS.Substring(delimPos + 2, OSBOXPARAMS.Length - delimPos - 3); // assumming path is quoted // Waiting until injection is done injectionDone.WaitOne(); AppDomainSetup ads = new AppDomainSetup(); ads.ApplicationBase = System.Environment.CurrentDirectory; ads.ConfigurationFile = assemblyPath + ".config"; AppDomain ad2 = AppDomain.CreateDomain("AD #2", null, ads); // Assembly title = Assembly.LoadFile(assemblyPath); // Removing first item from the list of arguments // args = args.Where((val, idx) => idx > 1).ToArray(); // System.Windows.Forms.MessageBox.Show("before"); ad2.ExecuteAssembly(assemblyPath, args); AppDomain.Unload(ad2); /* object[] parameters = new object[0]; * if (title.EntryPoint.GetParameters().Length > 0) * { * parameters = new object[] { args }; * } * title.EntryPoint.Invoke(null, parameters); */ }
public void ApplicationInitialise(string txtAppPath, string txtAppParam, PermissionSet permSet) { string appFilePath = Path.GetDirectoryName(txtAppPath); string[] appFileParam = txtAppParam.Split(' '); string appAssemblyName = Path.GetFileNameWithoutExtension(txtAppPath); // Application Domain Setup AppDomainSetup adSetup = new AppDomainSetup(); adSetup.ApplicationBase = appFilePath; // Strong Name using 'Sandboxer_Key.snk' StrongName fullTrustAssembly = typeof(Sandboxer).Assembly.Evidence.GetHostEvidence <StrongName>(); // Create Application Domain with a random 'ID' value so not all sandbox domains are the same Random rnd = new Random(); AppDomain newDomain = AppDomain.CreateDomain("Sandbox" + rnd.Next().ToString(), null, adSetup, permSet, fullTrustAssembly); // Object handle ObjectHandle handle = Activator.CreateInstanceFrom( newDomain, typeof(Sandboxer).Assembly.ManifestModule.FullyQualifiedName, typeof(Sandboxer).FullName); // Execute Application code Sandboxer newDomainInstance = (Sandboxer)handle.Unwrap(); Console.WriteLine("--- {0} STARTED ---", appAssemblyName); newDomain.ExecuteAssembly(txtAppPath, appFileParam); Console.WriteLine("--- {0} FINISHED ---\n", appAssemblyName); }
private static Thread RunApp(FileInfo file, Thread oldthread) { string persistenceData = null; if (clientAppDomain != null) { clientAppDomain.DoCallBack(() => Application.Exit()); persistenceData = clientAppDomain.GetData(PERSISTENCE_KEY) as string; AppDomain.Unload(clientAppDomain); oldthread.Join(); } var ads = new AppDomainSetup(); ads.ApplicationBase = file.DirectoryName; ads.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; clientAppDomain = AppDomain.CreateDomain(file.FullName, null, ads); clientAppDomain.SetData(PERSISTENCE_KEY, persistenceData); waitable.Reset(); var thread = new Thread( () => { try { clientAppDomain.ExecuteAssembly(file.FullName); } catch (AppDomainUnloadedException) { } finally { waitable.Set(); } }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); file.Refresh(); lastModified = file.LastWriteTime; return(thread); }
/// <summary> /// To install/uninstall the service, type: "Mod.ServiceHost.exe -Install [-u]" /// </summary> /// <returns>Win32 exit code.</returns> private int RunInstall() { var win32Params = Environment.GetCommandLineArgs(); var serviceParams = new string[win32Params.Length - 1]; // Get the full path to the running assembly Assembly module = System.Reflection.Assembly.GetEntryAssembly(); serviceParams[0] = module.Location; Array.Copy(win32Params, 2, serviceParams, 1, serviceParams.Length - 1); // Create app domain so service installer runs isolated AppDomain srvInstallDomain = AppDomain.CreateDomain("ServiceInstallation"); // Obtain folder where .NET is installed: find mscorlib.dll which holds System.Object Type objectType = typeof(object); String mscorlibPath = objectType.Assembly.Location; // Construct service installation command line var cmdLine = mscorlibPath.Substring(0, mscorlibPath.LastIndexOf("\\", System.StringComparison.Ordinal)); cmdLine += "\\InstallUtil.exe"; // Run service installation in isolated domain return(srvInstallDomain.ExecuteAssembly(cmdLine, serviceParams)); }
void AppDomainSecurity(AppDomain appDomain, IPrincipal principal) // Noncompliant, IPrincipal parameter, see another section with tests { appDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal); // Noncompliant // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ appDomain.SetThreadPrincipal(principal); // Noncompliant appDomain.ExecuteAssembly(""); // Compliant, not one of the tracked methods }
static void Main(string[] args) { // Create a new application domain. AppDomain domain = System.AppDomain.CreateDomain("MyDomain"); // Create a new AppDomain PolicyLevel. PolicyLevel polLevel = PolicyLevel.CreateAppDomainLevel(); // Create a new, empty permission set. PermissionSet permSet = new PermissionSet(PermissionState.None); // Add permission to execute code to the permission set. permSet.AddPermission (new SecurityPermission(SecurityPermissionFlag.Execution)); // Give the policy level's root code group a new policy statement based // on the new permission set. polLevel.RootCodeGroup.PolicyStatement = new PolicyStatement(permSet); // Give the new policy level to the application domain. domain.SetAppDomainPolicy(polLevel); // Try to execute the assembly. try { // This will throw a PolicyException if the executable tries to // access any resources like file I/O or tries to create a window. domain.ExecuteAssembly("Assemblies\\MyWindowsExe.exe"); } catch (PolicyException e) { Console.WriteLine("PolicyException: {0}", e.Message); } AppDomain.Unload(domain); }
static void Main(params string[] args) { var localAppFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); var appDirectory = Directory.CreateDirectory(Path.Combine(localAppFolder, "SPM")); var cachePath = Path.Combine(appDirectory.FullName, "assemblyCache"); var config = Path.Combine(appDirectory.FullName, "App", $"{spmExecutableName}.exe.config"); var executable = Path.Combine(appDirectory.FullName, "App", $"{spmExecutableName}.exe"); AppDomainSetup setup = new AppDomainSetup { ApplicationName = "SPM", ShadowCopyFiles = "true", CachePath = cachePath, ConfigurationFile = config }; AppDomain domain = AppDomain.CreateDomain( "SPM", AppDomain.CurrentDomain.Evidence, setup); domain.ExecuteAssembly(executable, args); AppDomain.Unload(domain); }
public static void Main(string[] args) { // For the purpose of this example, if this assembly is executing // in an AppDomain with the friendly name "NewAppDomain", do not // create a new AppDomain. This avoids an infinite loop of // AppDomain creation. if (AppDomain.CurrentDomain.FriendlyName != "NewAppDomain") { // Create a new application domain. AppDomain domain = AppDomain.CreateDomain("NewAppDomain"); // Execute this assembly in the new application domain and // pass the array of command-line arguments. domain.ExecuteAssembly("Recipe03-06.exe", args); } // Display the command-line arguments to the screen prefixed with // the friendly name of the AppDomain. foreach (string s in args) { Console.WriteLine(AppDomain.CurrentDomain.FriendlyName + " : " + s); } // Wait to continue. if (AppDomain.CurrentDomain.FriendlyName != "NewAppDomain") { Console.WriteLine("\nMain method complete. Press Enter."); Console.ReadLine(); } }
public override void LoadServer(string filename) { if (appDomain != null) { throw new ApplicationException("Server is already loaded"); } appDomain = AppDomain.CreateDomain(Utils.RandomName(15, 20)); thread = new Thread(new ThreadStart(() => { try { appDomain.ExecuteAssembly(filename, null, new string[] { ((int)serviceType).ToString(), ipcName, ipcUri }); } catch (NullReferenceException) { // Here if appDomain was set to null by Dispose() before this thread started } catch (AppDomainUnloadedException) { // Here if it was unloaded by Dispose() } UnloadAppDomain(appDomain); appDomain = null; })); thread.Start(); }
internal void StartFieldWorksThread() { m_FieldWorksDomain = AppDomain.CreateDomain("Running FieldWorks Domain"); GetFieldWorksInfo().PretendNotRunningUnitTests(); // FIXME: use FwAppArgs.kProject and FwAppArgs.kApp m_FieldWorksDomain.ExecuteAssembly(typeof(FieldWorks).Assembly.Location, null, new string[] { "-app", App, "-db", Db }); }
static int RunInAppDomain(string[] Arguments) { // Create application domain setup information. AppDomainSetup Domaininfo = new AppDomainSetup(); Domaininfo.ApplicationBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); Domaininfo.ShadowCopyFiles = "true"; // Create the application domain. AppDomain Domain = AppDomain.CreateDomain("AutomationTool", AppDomain.CurrentDomain.Evidence, Domaininfo); // Execute assembly and pass through command line string UATExecutable = Path.Combine(Domaininfo.ApplicationBase, "AutomationTool.exe"); // Default exit code in case UAT does not even start, otherwise we always return UAT's exit code. int ExitCode = 193; try { ExitCode = Domain.ExecuteAssembly(UATExecutable, Arguments); // Unload the application domain. AppDomain.Unload(Domain); } catch (Exception Ex) { Console.WriteLine(Ex.Message); Console.WriteLine(Ex.StackTrace); // We want to terminate the launcher process regardless of any crash dialogs, threads, etc Environment.Exit(ExitCode); } return(ExitCode); }
/// <summary> /// The main entry point to the console application. /// </summary> /// <param name="args">The command-line arguments.</param> /// <returns><code>0</code> if the application ran successfully with no errors, otherwise <code>1</code>.</returns> public static async Task <int> Main(string[] args) { var debug = IsDebug(); if (debug) { Debugger.Launch(); } // Parse command-line arguments if (!TryParseArguments(args, out (Dictionary <string, string> Options, FileInfo MSBuildExeFilePath, string EntryProjectFilePath, Dictionary <string, string> MSBuildGlobalProperties)arguments)) { return(1); } // Enable MSBuild feature flags MSBuildFeatureFlags.MSBuildExeFilePath = arguments.MSBuildExeFilePath.FullName; MSBuildFeatureFlags.EnableCacheFileEnumerations = true; MSBuildFeatureFlags.LoadAllFilesAsReadonly = true; MSBuildFeatureFlags.SkipEagerWildcardEvaluations = true; #if NETFRAMEWORK if (AppDomain.CurrentDomain.IsDefaultAppDomain()) { // MSBuild.exe.config has binding redirects that change from time to time and its very hard to make sure that NuGet.Build.Tasks.Console.exe.config is correct. // It also can be different per instance of Visual Studio so when running unit tests it always needs to match that instance of MSBuild // The code below runs this EXE in an AppDomain as if its MSBuild.exe so the assembly search location is next to MSBuild.exe and all binding redirects are used // allowing this process to evaluate MSBuild projects as if it is MSBuild.exe var thisAssembly = Assembly.GetExecutingAssembly(); AppDomain appDomain = AppDomain.CreateDomain( thisAssembly.FullName, securityInfo: null, info: new AppDomainSetup { ApplicationBase = arguments.MSBuildExeFilePath.DirectoryName, ConfigurationFile = Path.Combine(arguments.MSBuildExeFilePath.DirectoryName, "MSBuild.exe.config") }); return(appDomain .ExecuteAssembly( thisAssembly.Location, args)); } #endif // Check whether the ask is to generate the restore graph file. if (MSBuildStaticGraphRestore.IsOptionTrue("GenerateRestoreGraphFile", arguments.Options)) { using (var dependencyGraphSpecGenerator = new MSBuildStaticGraphRestore(debug: debug)) { return(dependencyGraphSpecGenerator.WriteDependencyGraphSpec(arguments.EntryProjectFilePath, arguments.MSBuildGlobalProperties, arguments.Options) ? 0 : 1); } } // Otherwise run restore! using (var dependencyGraphSpecGenerator = new MSBuildStaticGraphRestore(debug: debug)) { return(await dependencyGraphSpecGenerator.RestoreAsync(arguments.EntryProjectFilePath, arguments.MSBuildGlobalProperties, arguments.Options) ? 0 : 1); } }
static RunResult testWithAppDomain(String path, String assemblyName) { AppDomain domain = NewDomain(); try { domain.ExecuteAssembly(path); return(RunResult.valid); } catch (InvalidProgramException) { return(RunResult.invalid); } catch (FileLoadException) { return(RunResult.invalid); } catch (VerificationException) { return(RunResult.unverifiable); } catch (TypeInitializationException ve) { if (ve.InnerException is VerificationException) { return(RunResult.unverifiable); } Console.WriteLine("Warning: test {0} thrown exception: {1} ", assemblyName, ve.InnerException); return(RunResult.invalid); } catch (MissingMemberException) { return(RunResult.invalid); } catch (MemberAccessException) { return(RunResult.unverifiable); } catch (TypeLoadException) { return(RunResult.invalid); } catch (BadImageFormatException) { return(RunResult.invalid); } catch (Exception e) { Console.WriteLine("Warning: test {0} thrown exception {1}", assemblyName, e); return(RunResult.valid); } finally { AppDomain.Unload(domain); } }
public object ExecuteMothodEx(string actionName, string baseDirectory, IntPtr hWnd, string methodName = "Main") { object result = null; var setup = new AppDomainSetup(); setup.ApplicationBase = baseDirectory; AppDomain _appDomain = AppDomain.CreateDomain(actionName, null, setup); try { var args = new string[] { actionName, methodName }; var location = typeof(CSharpProxy.ProxyObject).Assembly.Location; CSharpProxy.ProxyObject po = (CSharpProxy.ProxyObject)_appDomain.CreateInstanceFromAndUnwrap(location, typeof(CSharpProxy.ProxyObject).FullName); po.WindowPH = hWnd; result = _appDomain.ExecuteAssembly(Path.Combine(baseDirectory, "CSharpEntry.exe"), args); } catch (Exception ex) { throw ex; } finally { AppDomain.Unload(_appDomain); } return(result); }
private static void DataReceived(object sender, PacketReceivedEventArgs e) { Console.WriteLine($"#Conduit:\tReceived { e.Packet.Data?.Length } bytes."); switch (e.Packet.PacketType) { case ConduitPacketType.Print: Console.WriteLine("#Component:\n->\t" + Encoding.Default.GetString(e.Packet.Data)); break; case ConduitPacketType.Execute: Console.WriteLine($"#Component:\tExecuting assembly."); var path = Encoding.Default.GetString(e.Packet.Data); ScriptDomain = AppDomain.CreateDomain("ScriptDomain"); ScriptDomain.ExecuteAssembly(path); break; case ConduitPacketType.Terminate: Console.WriteLine($"#Component:\tAborting running assembly."); AppDomain.Unload(ScriptDomain); break; } }
internal static int ExecuteNUnitTestProjectSplitter(params string[] rules) { //Assembly assembly = typeof( NUnitTestProjectSplitter.Program ).Assembly; string path = Path.Combine(TestContext.CurrentContext.TestDirectory, "NUnitTestProjectSplitter.exe"); Assembly assembly = Assembly.LoadFile(path); AppDomain appDomain = AppDomain.CreateDomain( friendlyName: TestContext.CurrentContext.Test.Name, securityInfo: AppDomain.CurrentDomain.Evidence, info: new AppDomainSetup { ApplicationBase = Path.GetDirectoryName(assembly.Location) } ); try { var arguments = new[] { "--inputNUnitProject", "NUnitTestProjects.nunit", "--assembliesPath", TestAssembliesPath, "--splitRules", string.Join(";", rules) }; int exitCode = appDomain.ExecuteAssembly(assembly.CodeBase, arguments); return(exitCode); } finally { AppDomain.Unload(appDomain); } }
/// <summary> /// Description: /// This will check the plug-in repository and get the dll's which have the /// implementation of IMFServicePlugin. /// </summary> /// <returns>Returns the valid assemblies.</returns> private static string[] GetAssemblies() { string[] validAssemblies = null; AppDomainSetup oDomainSetup = new AppDomainSetup(); oDomainSetup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; oDomainSetup.ConfigurationFile = AppDomain.CurrentDomain.BaseDirectory + @"\MFPluggerService.exe.config"; // This block will create an application domain, execute the MFAssemblyValidator assembly // and get the name of valid assemblies from repository. if (AppDomain.CurrentDomain.FriendlyName != "AssemblyValidatorDomain") { AppDomain oAppDomain = AppDomain.CreateDomain("AssemblyValidatorDomain", null, oDomainSetup); string pluginsPath = ServiceStartPath + "\\" + ConfigurationManager.AppSettings["PluginsFolderName"]; // Execute the MFAssemblyValidator.exe file. oAppDomain.ExecuteAssembly(AppDomain.CurrentDomain.BaseDirectory + @"\MFAssemblyValidator.exe", null, Directory.GetFiles(pluginsPath, "*.dll")); validAssemblies = (string[])oAppDomain.GetData("AssemblyNames"); AppDomain.Unload(oAppDomain); } return(validAssemblies); }
private Thread PrepareThread() { Thread t = new Thread(() => { string appPath = Path.Combine(_defaultBasePath, AppName); AppDomainSetup setup = new AppDomainSetup() { ApplicationName = AppName }; setup.ShadowCopyFiles = ShadowCopyFiles.ToString(); setup.ApplicationBase = appPath; if (ShadowCopyFiles == true) { setup.CachePath = Path.Combine(_shadowCopiesDirectory, AppName); } _appDomain = AppDomain.CreateDomain(AppDomainName, null, setup); _appDomain.ExecuteAssembly(_appExecutable); _state = ApplicationState.FINISHED; TerminatedApplicationHandler handler = OnTerminatedApplication; if (handler != null) { handler(this, EventArgs.Empty); } }); return(t); }
private void toolStripButton3_Click(object sender, EventArgs e) { #if DEBUG AppDomain domain = AppDomain.CreateDomain("Game Creator Game"); CreateExecutable("game.exe"); #else CreateExecutable("game.exe"); #endif #if !DEBUG System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("game.exe"); psi.RedirectStandardError = true; psi.UseShellExecute = false; // So we can redirect StandardError System.Diagnostics.Process p = System.Diagnostics.Process.Start(psi); #endif FormWindowState ws = WindowState; WindowState = FormWindowState.Minimized; #if DEBUG domain.ExecuteAssembly("game.exe"); AppDomain.Unload(domain); #else p.WaitForExit(); #endif WindowState = ws; #if !DEBUG string err = p.StandardError.ReadToEnd(); if (!string.IsNullOrEmpty(err)) { MessageBox.Show(string.Format("The game exited with errors:\n{0}", err), "Game Creator IDE", MessageBoxButtons.OK, MessageBoxIcon.Warning); } #endif }
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(); }
static void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { //Set up your new app domain, setting ShadowCopyFiles to true so that you can replace // the worker while running AppDomainSetup domaininfo = new AppDomainSetup(); domaininfo.ApplicationBase = Environment.CurrentDirectory; domaininfo.ShadowCopyFiles = "true"; // Create the application domain. _domain = AppDomain.CreateDomain("MyDomain", null, domaininfo); while (true) { //Get your foreman running _domain.ExecuteAssembly("Foreman.exe"); //take a short nap Thread.Sleep(new TimeSpan(0, 0, 1)); //check to see if there is a pending cancelation of this thread, and stop if there is if (_backgroundWorker.CancellationPending) { break; } } }
public static void StartOmniEve() { try { Logging.Log("OmniEveLoader", "------------------------------------------------------", Logging.Debug); Logging.Log("OmniEveLoader", "------------------------------------------------------", Logging.Debug); Logging.Log("OmniEveLoader", "Main._pathToOmniEveEXE [" + Main._pathToOmniEveEXE + "]", Logging.Debug); Logging.Log("OmniEveLoader", "------------------------------------------------------", Logging.Debug); Logging.Log("OmniEveLoader", "------------------------------------------------------", Logging.Debug); AppDomain OmniEvesAppDomain = null; if (EnumAppDomains().All(i => i.FriendlyName != Main._appDomainNameToUse)) { // Create a new AppDomain (what happens if this AppDomain already exists!?!) OmniEvesAppDomain = System.AppDomain.CreateDomain(Main._appDomainNameToUse); Logging.Log("EXEBootStrapper", "AppDomain [" + Main._appDomainNameToUse + "] created", Logging.White); } else { OmniEvesAppDomain = EnumAppDomains().First(i => i.FriendlyName == Main._appDomainNameToUse); Logging.Log("EXEBootStrapper", "AppDomain [" + Main._appDomainNameToUse + "] already exists, reusing.", Logging.White); } // Load the assembly and call the default entry point: try { OmniEvesAppDomain.ExecuteAssembly(Main._pathToOmniEveEXE, new string[] { "-i=" + Main._OmniEveDLLSettingsINI, "-d=" + Logging.ConsoleLogPath, "-f=" + Logging.ConsoleLogFile, "-s=" + Logging.SaveConsoleLog }); } catch (AppDomainUnloadedException) { Logging.Log("EXEBootStrapper", "AppDomain [" + Main._appDomainNameToUse + "] unloaded", Logging.White); } Logging.Log("EXEBootStrapper", "ExecuteAssembly [" + Main._pathToOmniEveEXE + "] finished", Logging.White); //Main.UnthawEVEProcess = true; // Create an instance of MarshalbyRefType in the second AppDomain. // A proxy to the object is returned. CrossDomainTest mbrt = (CrossDomainTest)OmniEvesAppDomain.CreateInstanceAndUnwrap( Main._pathToOmniEveEXE, typeof(CrossDomainTest).FullName ); // Call a method on the object via the proxy, passing the // default AppDomain's friendly name in as a parameter. mbrt.SomeMethod(Main._appDomainNameToUse); } catch (Exception ex) { Logging.Log("EXEBootStrapper", "exception [" + ex + "]", Logging.White); } finally { Logging.Log("EXEBootStrapper", "done.", Logging.White); } }
static void Main(string[] args) { foreach (Process i in Process.GetProcesses()) { Console.WriteLine($"Имя процесса : {i.ProcessName} | ID процесса : {i.Id}"); Console.WriteLine(); } AppDomain domain = AppDomain.CurrentDomain; Console.WriteLine($"Имя домена : {domain.FriendlyName}"); Console.WriteLine($"Базовый каталог : {domain.BaseDirectory}"); Console.WriteLine($"Детали конфигурации : {domain.SetupInformation}"); Assembly[] assemblies = domain.GetAssemblies(); foreach (Assembly i in assemblies) { Console.WriteLine(i.GetName()); } AppDomain newD = AppDomain.CreateDomain("MyDomen"); newD.ExecuteAssembly(@"D:\OOP\Lab_14\Lab_14\bin\Debug\netcoreapp3.1\Lab_14.exe"); AppDomain.Unload(newD); Console.WriteLine("___________________"); Console.WriteLine("Введите число n :"); int n = Int32.Parse(Console.ReadLine()); Thread thread1 = new Thread(() => Number(n)); thread1.Start(); Thread t = Thread.CurrentThread; t.Name = "Поток №1"; Console.WriteLine($"Имя потока : {t.Name}"); Console.WriteLine($"Приотирет потока : {t.Priority}"); Console.WriteLine($"ID потока : {Thread.CurrentThread.ManagedThreadId}"); Thread.Sleep(2000); Console.WriteLine($"Текущее состояние потока : {Thread.CurrentThread.ThreadState}"); Console.WriteLine($"Текущее состояние потока 1 : {thread1.ThreadState}"); Thread thread2 = new Thread(() => EvenNumber(n)); thread2.Start(); Thread thread3 = new Thread(() => UnevenNumber(n)); thread3.Start(); TimerCallback tm = new TimerCallback(EndThis); Timer timer = new Timer(tm, 0, 0, 2000); Console.ReadKey(); }
static void Main(string[] args) { Console.WriteLine("Сейчас будем запускать другую сборку в нашем процессе"); AppDomain ad = AppDomain.CreateDomain("Мой домен"); ad.ExecuteAssembly(@"F:\c#\Thread\DomainTest\bin\Release\DomainTest.exe"); Console.ReadLine(); }
static void Main(string[] args) { Console.WriteLine("I'm running on the domain: {0}", AppDomain.CurrentDomain.FriendlyName); AppDomain second = AppDomain.CreateDomain("Second.exe"); second.ExecuteAssembly("Second.exe"); Console.WriteLine("First domain ending ..."); }