/// <summary> /// 在指定AppDomain内创建一个指定type类型的实例,并返回为指定类型T(接口) /// </summary> /// <typeparam name="T">返回的类型,建议为接口</typeparam> /// <param name="appDomain">指定的应用程序域</param> /// <param name="type">将要运行在新AppDomain的类型</param> /// <param name="paramList">构造函数的参数</param> /// <returns></returns> public static T CreateToAppDomain <T>(this Type type, AppDomain appDomain, params object[] paramList) { var assemblyName = type.Assembly.GetName().FullName; var typeName = typeof(T).FullName; //var appDomain = createNewDomain(""); appDomain.AppendPrivatePath(Path.GetDirectoryName(type.Assembly.Location)); appDomain.AppendPrivatePath(Path.GetDirectoryName(typeof(T).Assembly.Location)); try { var retInterface = (T)appDomain.CreateInstanceAndUnwrap(assemblyName, typeName , false , BindingFlags.Default , null , paramList , Thread.CurrentThread.CurrentCulture , null , null); return(retInterface); } catch (Exception) { throw; } }
static void Main(string[] args) { AppDomainSetup setup = new AppDomainSetup(); // Shadow copying will not work unless the application has a name. setup.ApplicationName = "MyApplication"; //Create evidence for the new application domain from evidence of // current application domain. Evidence adevidence = AppDomain.CurrentDomain.Evidence; // Create a new application domain. AppDomain domain = AppDomain.CreateDomain("MyDomain", adevidence, setup); // MyAssembly.dll is located in the Assemblies subdirectory. domain.AppendPrivatePath("Assemblies"); // MyOtherAssembly.dll and MyThirdAssembly.dll are located in the // MoreAssemblies subdirectory. domain.AppendPrivatePath("MoreAssemblies"); // Display the relative search path. Console.WriteLine("RelativeSearchPath: " + domain.RelativeSearchPath); // Because Load returns an Assembly object, the assemblies must be // loaded into the current domain as well. This will fail unless the // current domain also has these directories in its search path. AppDomain.CurrentDomain.AppendPrivatePath("Assemblies"); AppDomain.CurrentDomain.AppendPrivatePath("MoreAssemblies"); // Save shadow copies to C:\Cache domain.SetCachePath("C:\\Cache"); // Shadow copy only the assemblies in the Assemblies directory. domain.SetShadowCopyPath(domain.BaseDirectory + "Assemblies"); // Turn shadow copying on. domain.SetShadowCopyFiles(); Console.WriteLine("ShadowCopyFiles turned on: " + domain.ShadowCopyFiles); // This will be copied. // You must supply a valid fully qualified assembly name here. domain.Load("Assembly1 text name, Version, Culture, PublicKeyToken"); // This will not be copied. // You must supply a valid fully qualified assembly name here. domain.Load("Assembly2 text name, Version, Culture, PublicKeyToken"); // When the shadow copy path is cleared, the CLR will make shadow copies // of all private assemblies. domain.ClearShadowCopyPath(); // MoreAssemblies\MyThirdAssembly.dll should be shadow copied this time. // You must supply a valid fully qualified assembly name here. domain.Load("Assembly3 text name, Version, Culture, PublicKeyToken"); // Unload the domain. AppDomain.Unload(domain); }
public static void Main() { //Create evidence for new appdomain. Evidence adevidence = AppDomain.CurrentDomain.Evidence; //Create the new application domain. AppDomain domain = AppDomain.CreateDomain("MyDomain", adevidence); //Display the current relative search path. Console.WriteLine("Relative search path is: " + domain.RelativeSearchPath); //Append the relative path. String Newpath = "www.code.microsoft.com"; domain.AppendPrivatePath(Newpath); //Display the new relative search path. Console.WriteLine("Relative search path is: " + domain.RelativeSearchPath); //Clear the private search path. domain.ClearPrivatePath(); //Display the new relative search path. Console.WriteLine("Relative search path is now: " + domain.RelativeSearchPath); AppDomain.Unload(domain); }
private Dictionary <string, List <string> > LoadPluginAssemblies(AppDomain appDomain, IEnumerable <string> pluginAssemblyFiles) { var cache = new Dictionary <string, List <string> >(); var exceptions = new List <Exception>(); foreach (var pluginAssemblyFile in pluginAssemblyFiles) { try { // Append private path to temporary and main AppDomain. // Yes, AppendPrivatePath is obsolete, but netstandard 2.0 // DOES NOT PROVIDE AN ALTERNATIVE! Thanks a bunch! #pragma warning disable CS0618 appDomain.AppendPrivatePath(Path.GetDirectoryName(pluginAssemblyFile)); AppDomain.CurrentDomain.AppendPrivatePath(Path.GetDirectoryName(pluginAssemblyFile)); #pragma warning restore CS0618 var name = AssemblyName.GetAssemblyName(pluginAssemblyFile); var assembly = appDomain.Load(name); DiscoverPluginTypes(assembly, ref cache); } catch (Exception ex) { exceptions.Add(ex); } } if (exceptions.Any()) { throw new AggregateException("One or more plugins could not be loaded.", exceptions); } return(cache); }
//----< Create AppDomain in which to run tests >----------------- void CreateAppDomain() { AppDomainSetup domainInfo = new AppDomainSetup(); domainInfo.ApplicationName = "TestDomain"; Evidence evidence = AppDomain.CurrentDomain.Evidence; ad = AppDomain.CreateDomain("TestDomain", evidence, domainInfo); ad.AppendPrivatePath(pathToLoader_); }
/// <summary> /// set up the AppDomain for the type to map in the containing assembly assemblyToMap /// </summary> /// <param name="assemblyToMap">the assembly containing the type to map</param> private static void SetupAppDomain(Assembly assemblyToMap) { AppDomain curDomain = AppDomain.CurrentDomain; curDomain.AppendPrivatePath(curDomain.BaseDirectory); // directory of the assembly containing the typ to map // make sure to probe in directory containing type to map, if not found itself ... string directoryName = new FileInfo(assemblyToMap.Location).DirectoryName; CustomAssemblyResolver resolver = new CustomAssemblyResolver(directoryName); ResolveEventHandler hndlr = new ResolveEventHandler(resolver.AssemblyResolve); curDomain.AssemblyResolve += hndlr; }
internal static void SetPrivatePath(string pluginFile, AppDomain appDomain) { string[] parts; appDomain = appDomain ?? AppDomain.CurrentDomain; if (string.IsNullOrEmpty(appDomain.SetupInformation.PrivateBinPath)) { parts = new string[0]; } else { parts = appDomain.SetupInformation.PrivateBinPath.Split(';'); } string privatePath = GetPrivatePath(pluginFile, appDomain.SetupInformation.ApplicationBase, path => { return(!Array.Exists(parts, item => string.Equals(path, item, StringComparison.OrdinalIgnoreCase))); }); appDomain.AppendPrivatePath(privatePath); }
/// <summary>setup assembly resolution: consider all directories of /r files /// and current directory as assembly containing directories</summary> private void SetupAssemblyResolver() { ArrayList searchDirectoryList = new ArrayList(); searchDirectoryList.Add(new DirectoryInfo(".").FullName); foreach (Assembly refAsm in m_commandLine.ReferencedAssemblies) { string asmDir = new FileInfo(refAsm.Location).Directory.FullName; if (!searchDirectoryList.Contains(asmDir)) { searchDirectoryList.Add(asmDir); } } AppDomain curDomain = AppDomain.CurrentDomain; curDomain.AppendPrivatePath(curDomain.BaseDirectory); CustomAssemblyResolver resolver = new CustomAssemblyResolver(searchDirectoryList); ResolveEventHandler hndlr = new ResolveEventHandler(resolver.AssemblyResolve); curDomain.AssemblyResolve += hndlr; }
protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); if (mutex.WaitOne(TimeSpan.Zero, true)) { #if DEBUG Global.isDebug = true; #endif Global.Initialize(); string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); Directory.SetCurrentDirectory(path); string logiDll = Path.Combine(path, "LogitechLed.dll"); if (File.Exists(logiDll)) { File.Delete(logiDll); } StringBuilder systeminfo_sb = new StringBuilder(string.Empty); systeminfo_sb.Append("\r\n========================================\r\n"); try { var win_reg = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"); string productName = (string)win_reg.GetValue("ProductName"); systeminfo_sb.AppendFormat("Operation System: {0}\r\n", productName); } catch (Exception exc) { systeminfo_sb.AppendFormat("Operation System: Could not be retrieved. [Exception: {0}]\r\n", exc.Message); } systeminfo_sb.AppendFormat("System Architecture: " + (Environment.Is64BitOperatingSystem ? "64 bit" : "32 bit") + "\r\n"); systeminfo_sb.AppendFormat("Environment OS Version: {0}\r\n", Environment.OSVersion); systeminfo_sb.AppendFormat("System Directory: {0}\r\n", Environment.SystemDirectory); systeminfo_sb.AppendFormat("Executing Directory: {0}\r\n", Global.ExecutingDirectory); systeminfo_sb.AppendFormat("Launch Directory: {0}\r\n", Directory.GetCurrentDirectory()); systeminfo_sb.AppendFormat("Processor Count: {0}\r\n", Environment.ProcessorCount); //systeminfo_sb.AppendFormat("User DomainName: {0}\r\n", Environment.UserDomainName); //systeminfo_sb.AppendFormat("User Name: {0}\r\n", Environment.UserName); systeminfo_sb.AppendFormat("SystemPageSize: {0}\r\n", Environment.SystemPageSize); systeminfo_sb.AppendFormat("Environment Version: {0}\r\n", Environment.Version); System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent(); System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity); systeminfo_sb.AppendFormat("Is Elevated: {0}\r\n", principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator)); systeminfo_sb.AppendFormat("Aurora Assembly Version: {0}\r\n", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version); systeminfo_sb.AppendFormat("Aurora File Version: {0}\r\n", System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).FileVersion); systeminfo_sb.Append("========================================\r\n"); Global.logger.Info(systeminfo_sb.ToString()); string arg = ""; for (int arg_i = 0; arg_i < e.Args.Length; arg_i++) { arg = e.Args[arg_i]; switch (arg) { case ("-debug"): Global.isDebug = true; Global.logger.Info("Program started in debug mode."); break; case ("-silent"): isSilent = true; Global.logger.Info("Program started with '-silent' parameter"); break; case ("-ignore_update"): ignore_update = true; Global.logger.Info("Program started with '-ignore_update' parameter"); break; case ("-delay"): isDelayed = true; if (arg_i + 1 < e.Args.Length && int.TryParse(e.Args[arg_i + 1], out delayTime)) { arg_i++; } else { delayTime = 5000; } Global.logger.Info("Program started with '-delay' parameter with delay of " + delayTime + " ms"); break; case ("-install_logitech"): Global.logger.Info("Program started with '-install_logitech' parameter"); try { InstallLogitech(); } catch (Exception exc) { System.Windows.MessageBox.Show("Could not patch Logitech LED SDK. Error: \r\n\r\n" + exc, "Aurora Error"); } Environment.Exit(0); break; } } AppDomain currentDomain = AppDomain.CurrentDomain; if (!Global.isDebug) { currentDomain.UnhandledException += CurrentDomain_UnhandledException; } if (isDelayed) { System.Threading.Thread.Sleep((int)delayTime); } this.ShutdownMode = ShutdownMode.OnExplicitShutdown; //AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit); if (Environment.Is64BitProcess) { currentDomain.AppendPrivatePath("x64"); } else { currentDomain.AppendPrivatePath("x86"); } Global.StartTime = Utils.Time.GetMillisecondsSinceEpoch(); Global.dev_manager = new DeviceManager(); Global.effengine = new Effects(); //Load config Global.logger.Info("Loading Configuration"); try { Global.Configuration = ConfigManager.Load(); } catch (Exception exc) { Global.logger.Error("Exception during ConfigManager.Load(). Error: " + exc); System.Windows.MessageBox.Show("Exception during ConfigManager.Load().Error: " + exc.Message + "\r\n\r\n Default configuration loaded.", "Aurora - Error"); Global.Configuration = new Configuration(); } Global.Configuration.PropertyChanged += (sender, eventArgs) => { ConfigManager.Save(Global.Configuration); }; Process.GetCurrentProcess().PriorityClass = Global.Configuration.HighPriority ? ProcessPriorityClass.High : ProcessPriorityClass.Normal; if (Global.Configuration.updates_check_on_start_up && !ignore_update) { string updater_path = System.IO.Path.Combine(Global.ExecutingDirectory, "Aurora-Updater.exe"); if (File.Exists(updater_path)) { try { ProcessStartInfo updaterProc = new ProcessStartInfo(); updaterProc.FileName = updater_path; updaterProc.Arguments = "-silent"; Process.Start(updaterProc); } catch (Exception exc) { Global.logger.Error("Could not start Aurora Updater. Error: " + exc); } } } Global.logger.Info("Loading Plugins"); (Global.PluginManager = new PluginManager()).Initialize(); Global.logger.Info("Loading KB Layouts"); Global.kbLayout = new KeyboardLayoutManager(); Global.kbLayout.LoadBrandDefault(); Global.logger.Info("Loading Input Hooking"); Global.InputEvents = new InputEvents(); Global.Configuration.PropertyChanged += SetupVolumeAsBrightness; SetupVolumeAsBrightness(Global.Configuration, new PropertyChangedEventArgs(nameof(Global.Configuration.UseVolumeAsBrightness))); Utils.DesktopUtils.StartSessionWatch(); Global.key_recorder = new KeyRecorder(Global.InputEvents); Global.logger.Info("Loading RazerSdkManager"); if (RzHelper.IsSdkVersionSupported(RzHelper.GetSdkVersion())) { try { Global.razerSdkManager = new RzSdkManager() { KeyboardEnabled = true, MouseEnabled = true, MousepadEnabled = true, AppListEnabled = true, }; Global.logger.Info("RazerSdkManager loaded successfully!"); } catch (Exception exc) { Global.logger.Fatal("RazerSdkManager failed to load!"); Global.logger.Fatal(exc.ToString()); } } else { Global.logger.Warn("Currently installed razer sdk version \"{0}\" is not supported by the RazerSdkManager!", RzHelper.GetSdkVersion()); } Global.logger.Info("Loading Applications"); (Global.LightingStateManager = new LightingStateManager()).Initialize(); if (Global.Configuration.GetPointerUpdates) { Global.logger.Info("Fetching latest pointers"); Task.Run(() => Utils.PointerUpdateUtils.FetchDevPointers("master")); } Global.logger.Info("Loading Device Manager"); Global.dev_manager.RegisterVariables(); Global.dev_manager.Initialize(); /*Global.logger.LogLine("Starting GameEventHandler", Logging_Level.Info); * Global.geh = new GameEventHandler(); * if (!Global.geh.Init()) * { * Global.logger.LogLine("GameEventHander could not initialize", Logging_Level.Error); * return; * }*/ Global.logger.Info("Starting GameStateListener"); try { Global.net_listener = new NetworkListener(9088); Global.net_listener.NewGameState += new NewGameStateHandler(Global.LightingStateManager.GameStateUpdate); Global.net_listener.WrapperConnectionClosed += new WrapperConnectionClosedHandler(Global.LightingStateManager.ResetGameState); } catch (Exception exc) { Global.logger.Error("GameStateListener Exception, " + exc); System.Windows.MessageBox.Show("GameStateListener Exception.\r\n" + exc); Environment.Exit(0); } if (!Global.net_listener.Start()) { Global.logger.Error("GameStateListener could not start"); System.Windows.MessageBox.Show("GameStateListener could not start. Try running this program as Administrator.\r\nExiting."); Environment.Exit(0); } Global.logger.Info("Listening for game integration calls..."); Global.logger.Info("Loading ResourceDictionaries..."); this.Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri("Themes/MetroDark/MetroDark.MSControls.Core.Implicit.xaml", UriKind.Relative) }); this.Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri("Themes/MetroDark/MetroDark.MSControls.Toolkit.Implicit.xaml", UriKind.Relative) }); Global.logger.Info("Loaded ResourceDictionaries"); Global.logger.Info("Loading ConfigUI..."); MainWindow = new ConfigUI(); ((ConfigUI)MainWindow).Display(); //Debug Windows on Startup if (Global.Configuration.BitmapWindowOnStartUp) { Window_BitmapView.Open(); } if (Global.Configuration.HttpWindowOnStartUp) { Window_GSIHttpDebug.Open(); } } else { try { NamedPipeClientStream client = new NamedPipeClientStream(".", "aurora\\interface", PipeDirection.Out); client.Connect(30); if (!client.IsConnected) { throw new Exception(); } byte[] command = System.Text.Encoding.ASCII.GetBytes("restore"); client.Write(command, 0, command.Length); client.Close(); } catch { //Global.logger.LogLine("Aurora is already running.", Logging_Level.Error); System.Windows.MessageBox.Show("Aurora is already running.\r\nExiting.", "Aurora - Error"); } } }
public static void MiMi() { //Console.WriteLine("=37="); Console.WriteLine("My Pid {0}", Process.GetCurrentProcess().Id); Console.WriteLine("[press enter to create new AppDomain]"); if (Enter) { Console.ReadLine(); } string NDomain = RandomString(16); string DBase = Assembly.GetExecutingAssembly().Location.Substring(0, Assembly.GetExecutingAssembly().Location.LastIndexOf("NewApproach.exe") - 1); Console.WriteLine(DBase); Evidence adevidence = AppDomain.CurrentDomain.Evidence; AppDomainSetup domainSetup = new AppDomainSetup() { //ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase, ApplicationBase = DBase, ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile, ApplicationName = AppDomain.CurrentDomain.SetupInformation.ApplicationName, LoaderOptimization = LoaderOptimization.MultiDomain, PrivateBinPath = @"http://ts-dc1.enterprise.lab/" }; PermissionSet permissionSet = new PermissionSet(PermissionState.Unrestricted); AppDomain ad = AppDomain.CreateDomain(NDomain, adevidence, domainSetup, permissionSet); Console.WriteLine("++++++++++ Parent => Child Domains LoaderOptimization ++++++++++"); Console.WriteLine(AppDomain.CurrentDomain.SetupInformation.LoaderOptimization.ToString()); Console.WriteLine(ad.SetupInformation.LoaderOptimization.ToString()); Console.WriteLine("++++++++++ Parent => Child Domains ApplicationBase ++++++++++"); Console.WriteLine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase.ToString()); Console.WriteLine(ad.SetupInformation.ApplicationBase.ToString()); Console.WriteLine("++++++++++ Parent => Child Domains PrivateBinPath ++++++++++"); Console.WriteLine(AppDomain.CurrentDomain.SetupInformation.PrivateBinPath?.ToString() ?? ""); Console.WriteLine(ad.SetupInformation.PrivateBinPath?.ToString() ?? ""); Console.WriteLine("+++++++++++++++++++++++++++++++++++++++++++++"); Console.WriteLine("New AppDomain {0} just was created\nAnd everything stay clear, because now AppDomain is empty\n[press enter]", NDomain); if (Enter) { Console.ReadLine(); } try { object[] parameters = { Properties.Resources.KatzAssembly }; string LoaderAssemblyName = typeof(AssemblyLoader).Assembly.FullName; string LoaderClassName = typeof(AssemblyLoader).FullName; Console.WriteLine("loading loader {0} {1}", LoaderClassName, LoaderClassName); ad.AppendPrivatePath(@"http://ts-dc1.enterprise.lab/"); /*object assloader =*/ ad.CreateInstanceAndUnwrap( LoaderAssemblyName, LoaderClassName, true, BindingFlags.CreateInstance, null, parameters, null, null); } catch (FileNotFoundException e) { Console.WriteLine("Error working with loader\n{0}!", e.Message, e.FileName); Console.ReadLine(); } Console.WriteLine("Appdomain {0} finished its work (no active thread)", NDomain); Console.WriteLine("But still alive and store some artifacts"); Console.WriteLine("We should do memory scan NOW, when resive module=>assembly=>appdomain unload events to collect&detect memory artifacts, before GC clear em"); Console.WriteLine("[Press enter to clear Appdomain]\n(generate AppDomain, Assembly & Module Unload events)"); if (Enter) { Console.ReadLine(); } AppDomain.Unload(ad); ad = null; GC.Collect(); GC.WaitForFullGCComplete(); Console.ResetColor(); Console.WriteLine("Appdomain cleared, no any artifacts, but app still running :-)", Console.ForegroundColor = ConsoleColor.Gray); if (Enter) { Console.ReadLine(); } }