public static DotNetVersion GetVersion(string assemblyPath) { if (string.IsNullOrEmpty(assemblyPath)) { throw new ArgumentException("Argument null or empty", "assemblyPath"); } try { string fileName = assemblyPath.Normalize(); if (!System.IO.File.Exists(fileName)) { return(DotNetVersion.Two); } // TODO: florind: find a safer way to do this, without loading the assembly in RAM AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation; setup.ApplicationBase = Path.GetDirectoryName(assemblyPath); string domainName = Guid.NewGuid().ToString(); AppDomain domain = AppDomain.CreateDomain(domainName, null, setup); LoadAssemblyHelper obj = (LoadAssemblyHelper)domain.CreateInstanceFromAndUnwrap(Assembly.GetExecutingAssembly().Location, "Uhuru.Utilities.LoadAssemblyHelper"); string version = obj.GetDotNetVersion(assemblyPath); AppDomain.Unload(domain); if (Convert.ToInt32(version, CultureInfo.InvariantCulture) < 4) { return(DotNetVersion.Two); } else { return(DotNetVersion.Four); } } catch (System.BadImageFormatException) { return(DotNetVersion.Two); } catch (Exception) { throw; } }
private static Silo LoadSiloInNewAppDomain(string siloName, Silo.SiloType type, ClusterConfiguration config, out AppDomain appDomain) { AppDomainSetup setup = GetAppDomainSetupInfo(); appDomain = AppDomain.CreateDomain(siloName, null, setup); var args = new object[] { siloName, type, config }; var silo = (Silo)appDomain.CreateInstanceFromAndUnwrap( "OrleansRuntime.dll", typeof(Silo).FullName, false, BindingFlags.Default, null, args, CultureInfo.CurrentCulture, new object[] { }); appDomain.UnhandledException += ReportUnobservedException; return(silo); }
public AssemblyExecutor(string fileNname, string domainName) { assemblyFileName = fileNname; AppDomainSetup setup = new AppDomainSetup(); setup.ApplicationBase = Path.GetDirectoryName(assemblyFileName); setup.PrivateBinPath = AppDomain.CurrentDomain.BaseDirectory; setup.ApplicationName = Path.GetFileName(Assembly.GetExecutingAssembly().Location); setup.ShadowCopyFiles = "true"; setup.ShadowCopyDirectories = Path.GetDirectoryName(assemblyFileName); appDomain = AppDomain.CreateDomain(domainName, null, setup); remoteExecutor = (RemoteExecutor) appDomain.CreateInstanceFromAndUnwrap(Assembly.GetExecutingAssembly().Location, typeof(RemoteExecutor).ToString()); }
public static IEnumerable <Output> Inject( string assemblyFile, string typeName, string methodName, string strongNameKeyPair, bool useIsolatedAppDomain, string[] assemblySearchDirs) { Injector injector; if (!useIsolatedAppDomain) { injector = new Injector(); return(injector.DoInject(assemblyFile, typeName, methodName, strongNameKeyPair, assemblySearchDirs)); } AppDomain childDomain = null; try { // Create a child app domain. childDomain = AppDomain.CreateDomain("InjectionDomain"); // Create an instance of the injector object in the new domain. injector = (Injector)childDomain.CreateInstanceFromAndUnwrap( _assemblyFileName, _typeName, false, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.CreateInstance, null, null, null, null); Debug.Assert(injector != null); // Call the DoInject method on the injector in the child domain. return(injector.DoInject(assemblyFile, typeName, methodName, strongNameKeyPair, assemblySearchDirs)); } finally { if (childDomain != null) { AppDomain.Unload(childDomain); } } }
public T CreateAppDomain <T>(string friendlyName, AppDomainSetup setup) where T : MarshalByRefObject, new() { Enforce.ArgumentNotNull <AppDomainSetup>(setup, "setup"); Enforce.ArgumentNotNullOrEmpty(friendlyName, "friendlyName"); Evidence baseEvidence = AppDomain.CurrentDomain.Evidence; Evidence evidence = new Evidence(baseEvidence); //evidence.AddAssembly("(some assembly)"); //evidence.AddHost("(some host)"); AppDomain appDomain = AppDomain.CreateDomain(friendlyName, evidence, setup); T proxyInstance = (T)appDomain.CreateInstanceFromAndUnwrap(typeof(T).Assembly.Location, typeof(T).FullName); LoadedAppDomains.Add(proxyInstance, appDomain); return(proxyInstance); }
// Limit remoting to specific appdomain: Channels cannot be unregistered and ensures that other services // within the application using this library are not exposed by the worker channel. public static WorkerServerClientSideProxy ConnectToWorkerServer(Guid ipcguid) { var t = typeof(WorkerServerClientSideProxy); var remotingDomainDame = string.Format(CultureInfo.InvariantCulture, "{0}_{1}", typeof(WorkerServerClientSideProxy).Name, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); lock (proxyDomainLock) { if (proxyDomainRefCount == 0) { var remotingDomain = AppDomain.CreateDomain(remotingDomainDame, AppDomain.CurrentDomain.Evidence, new AppDomainSetup { ApplicationBase = AppDomain.CurrentDomain.BaseDirectory, LoaderOptimization = LoaderOptimization.MultiDomainHost }, AppDomain.CurrentDomain.PermissionSet, t.GetStrongNameOfAssemblyAsArray()); proxyDomain = remotingDomain; proxyDomainRefCount++; AppDomain.CurrentDomain.AssemblyResolve += ResolveCurrentAssemblyAcrossLoadContext; // Important: Load current assembly based on path to support corner cases with the unblocker // assembly not being available from the assembly search path! try { var setupType = typeof(ProxyDomainSetup); var setup = (ProxyDomainSetup)proxyDomain.CreateInstanceFromAndUnwrap( setupType.Assembly.Location, setupType.FullName); setup.Setup(); } catch (Exception) { DecrementProxyRef(true); throw; } } try { var proxy = (WorkerServerClientSideProxy)proxyDomain.CreateInstanceFromAndUnwrap( t.Assembly.Location, t.FullName); proxy.Connect(ipcguid); return(proxy); } catch (Exception) { DecrementProxyRef(true); throw; } } }
/// <summary> /// Event Handler which resolves the assembly full name to an assembly, using the calling assembly path as a /// search folder. /// </summary> /// <param name="basePath">Base Path where an assembly with a given Full Name is searched in</param> /// <param name="assemblyFullName">Assembly Full Name</param> /// <returns></returns> internal static Assembly ResolveByFullAssemblyNameInternal(string basePath, string assemblyFullName) { if (string.IsNullOrWhiteSpace(basePath)) { return(null); } AppDomain newDomain = null; try { var newDomainSetup = new AppDomainSetup() { ApplicationBase = AppDomain.CurrentDomain.BaseDirectory }; newDomain = AppDomain.CreateDomain(Guid.NewGuid().ToString("N"), null, newDomainSetup); var instanceInNewDomain = (ResolverAppDomainAgent)newDomain.CreateInstanceFromAndUnwrap( typeof(ResolverAppDomainAgent).Assembly.Location, typeof(ResolverAppDomainAgent).FullName, true, BindingFlags.Default, null, null, null, null); var files = Directory.GetFiles(basePath, "*.*"); var assemblyPath = files.FirstOrDefault(p => instanceInNewDomain.CompareAssemblyFullName(p, assemblyFullName)); return(!string.IsNullOrWhiteSpace(assemblyPath) ? (basePath == AppDomain.CurrentDomain.BaseDirectory ? Assembly.LoadFrom(assemblyPath) : Assembly.LoadFile(assemblyPath)) : null); } finally { if (newDomain != null) { AppDomain.Unload(newDomain); } } }
private bool RunTemplate(string assemblyPath, Config config) { AppDomain domain = null; try { var setup = new AppDomainSetup { ApplicationBase = Path.GetDirectoryName(typeof(Runner).Assembly.Location), ConfigurationFile = $"{assemblyPath}.config", LoaderOptimization = LoaderOptimization.MultiDomain }; Log.LogMessage($"Creating app domain for: {assemblyPath}"); domain = AppDomain.CreateDomain(Path.GetFileNameWithoutExtension(assemblyPath) + "MteDomain", null, setup); // ////domain = AppDomain.CreateDomain(Path.GetFileNameWithoutExtension(assemblyPath) + "MteDomain"); // //Log.LogMessage($"MTE.Internal: {typeof(Runner).Assembly.Location}"); // var runner = (Runner)domain.CreateInstanceFromAndUnwrap(typeof(Runner).Assembly.Location, typeof(Runner).FullName); Log.LogMessage("Created runner"); TemplateResult result = runner.Run(config, assemblyPath); Log.LogMessage($"Got TemplateResult {result.Success}"); foreach (var message in result.Messages ?? Enumerable.Empty <string>()) { Log.LogMessage($" ==> {message}"); } if (result.Success) { RemoveItems = result.RemovedItems.ToArray(); NewItems = result.AddedItems.Select(x => new TaskItem(x.FilePath)).Cast <ITaskItem>().ToArray(); } return(true); } finally { if (domain != null) { AppDomain.Unload(domain); } } }
/// <summary> /// Entity Framework Migration /// </summary> /// <param name="assemblyPath">full path to the assembly</param> /// <param name="qualifiedDbConfigName">Name of the DbConfiguration class to use for the migrations</param> /// <param name="appConfigPath">App.Config or Web.config file path</param> /// <param name="connectionString">Connectionsting name of actually connection string</param> /// <param name="connectionProvider">Name of the connection string provider</param> /// <param name="logger">Logger to write items to the console</param> /// <param name="allowDataLossOnMigrations">Determines whether to allow dataloss during the migration</param> public EfMigrator(string assemblyPath, string qualifiedDbConfigName, string appConfigPath, string connectionString, string connectionProvider, ILogger logger, bool allowDataLossOnMigrations) { _logger = logger; _logger.Information($"Connection string being used is: {connectionString}"); appConfigPath = Path.GetFullPath(appConfigPath); if (!File.Exists(appConfigPath)) { throw new EfMigrationException($"The {nameof(appConfigPath)} '{appConfigPath}' must exist."); } var domainSetup = AppDomain.CurrentDomain.SetupInformation; domainSetup.ConfigurationFile = appConfigPath; _logger.Debug($"Prepared AppDomain setup using {appConfigPath} as the appconfig."); var domainName = $"EfMigrator:{Guid.NewGuid()}"; _domain = AppDomain.CreateDomain(domainName, null, domainSetup); _logger.Debug($"Created new AppDomain named {domainName}."); var type = typeof(EfMigratorBackend); var fullPath = Assembly.GetAssembly(typeof(EfMigratorBackend)).Location; Debug.Assert(fullPath != null, "fullPath != null"); var migrator = (EfMigratorBackend)_domain.CreateInstanceFromAndUnwrap(fullPath, type.FullName); _logger.Debug("Created new instance."); migrator.Initialize(assemblyPath, qualifiedDbConfigName, connectionString, connectionProvider, appConfigPath); _logger.Debug($"Initialized new {nameof(EfMigratorBackend)} within {domainName}."); CurrentMigration = migrator.GetCurrentMigration() ?? InitialDatabase; var currentMigrationStr = CurrentMigration == InitialDatabase ? "$InitialDatabase" : CurrentMigration; _logger.Information($"Current Migration is {currentMigrationStr}."); migrator.SetAllowDataLossOnMigrations(allowDataLossOnMigrations); _migratorBackend = migrator; }
public CallUnitTestGeneratorResponse CallUnitTestGeneratorInIsolateAppDomain(CallUnitTestGeneratorRequest request) { AppDomain appDomain = null; var response = new CallUnitTestGeneratorResponse { IsSuccess = true, ErrorMessage = string.Empty }; try { var generatorType = typeof(UnitTestGenerator); var assembly = Assembly.GetAssembly(generatorType); appDomain = AppDomain.CreateDomain("AppDomain for UnitTestGenerator"); var generatorProxy = appDomain.CreateInstanceFromAndUnwrap(assembly.Location, generatorType.FullName) as UnitTestGenerator; if (generatorProxy != null) { var generatorResponse = generatorProxy.Generate(request.Request); response.Response = generatorResponse; if (!generatorResponse.IsSuccess) { response.IsSuccess = false; response.ErrorMessage = "Some error happened in execution of generator."; } } else { response.IsSuccess = false; response.ErrorMessage = $"Fail to create generator {generatorType.FullName} in assembly {assembly.FullName}."; } } finally { if (appDomain != null) { AppDomain.Unload(appDomain); } } return(response); }
internal List <Job.Base.Job> FindJobsIn(AppDomain appDom) { var jobs = new List <Job.Base.Job>(); var loader = GetLoader(appDom); var jobTypes = loader.GetJobTypes(); foreach (var jobType in jobTypes) { var job = appDom.CreateInstanceFromAndUnwrap(jobType.Item1, jobType.Item2) as Job.Base.Job; if (job != null) { jobs.Add(job); } } return(jobs); }
public Isolator(Type type, string methodName) { var runnerType = typeof(IsolatorRunner); var runnerAssemblyPath = runnerType.Assembly.Location; var runnerAssemblyContents = File.ReadAllBytes(runnerAssemblyPath); var runnerAssemblyFolder = Path.GetDirectoryName(runnerAssemblyPath); _appDomain = AppDomain.CreateDomain($"Foo_Isolated_AppDomain_{Guid.NewGuid()}", null, new AppDomainSetup() { ApplicationBase = runnerAssemblyFolder }); var cTorArgs = new object[] { runnerAssemblyContents, type.FullName, methodName }; _runner = (IsolatorRunner)_appDomain.CreateInstanceFromAndUnwrap(runnerAssemblyPath, runnerType.FullName, false , BindingFlags.CreateInstance | BindingFlags.Public | BindingFlags.Instance , null, cTorArgs, null, null); }
private static void TimerProcAssemblyLoad(object state) { AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve); Console.WriteLine("Hello from timer!"); String appDomainName = "TemporaryApplicationDomain"; AppDomain applicationDomain = System.AppDomain.CreateDomain(appDomainName); var assmblyLoaderType = typeof(AssemblyLoaderProxy); var assemblyLoader = (IAssemblyLoader)applicationDomain.CreateInstanceFromAndUnwrap(assmblyLoaderType.Assembly.Location, assmblyLoaderType.FullName); assemblyLoader.Load((byte[])state); Console.WriteLine("Dynamic assembly has been loaded in new AppDomain " + appDomainName); AppDomain.Unload(applicationDomain); Console.WriteLine("New AppDomain has been unloaded"); Timer t = new Timer(new TimerCallback(TimerProcAssemblyLoad), state, 1000, 0); }
private void SetupStuff(string name) { // This setup is to force the release of DLL file handles // when the domain is unloaded AppDomainSetup setup = new AppDomainSetup(); setup.LoaderOptimization = LoaderOptimization.MultiDomainHost; domain = AppDomain.CreateDomain(name, null, setup); loader = (RemoteLoader <TInterface>)domain.CreateInstanceFromAndUnwrap( Assembly.GetExecutingAssembly().CodeBase, typeof(RemoteLoader <TInterface>).FullName); sponsor = new Sponsor(); ILease lease = (ILease)loader.GetLifetimeService(); lease.Register(sponsor); }
public static IsolatedStringAndReflectionBasedMixinChecker Create(string workingDirectory, string remotionInterfacesFullName) { var setupInfo = AppDomain.CurrentDomain.SetupInformation; setupInfo.ApplicationBase = workingDirectory; AppDomain newDomain = AppDomain.CreateDomain("MixinConfiguration checker", null, setupInfo); var checker = (IsolatedStringAndReflectionBasedMixinChecker)newDomain.CreateInstanceFromAndUnwrap( typeof(IsolatedStringAndReflectionBasedMixinChecker).Assembly.CodeBase, typeof(IsolatedStringAndReflectionBasedMixinChecker).FullName, false, BindingFlags.Public | BindingFlags.Instance, null, new[] { remotionInterfacesFullName }, null, null); return(checker); }
public static T CreateObject <T>(this AppDomain domain, params object[] args) { var objectType = typeof(T); if (objectType.FullName == null) { throw new InvalidOperationException(); } return((T)domain.CreateInstanceFromAndUnwrap(objectType.Assembly.Location, objectType.FullName, false, BindingFlags.Default, null, args, null, null)); }
static void Main() { Console.WriteLine("Test_AppDomain_04 : use of AppDomain.CreateInstanceAndUnwrap"); AppDomain domain = AppDomain.CreateDomain("New Domain"); object otest03 = domain.CreateInstanceAndUnwrap(typeof(test_03).Assembly.FullName, typeof(test_03).FullName); // Exception: System.IO.FileNotFoundException: Could not load file or assembly 'file:///...\Test_AppDomain_04, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified. object otest03_2 = domain.CreateInstanceFromAndUnwrap("Test_AppDomain_04.exe", typeof(test_03).FullName); Console.WriteLine("typeof(test_03).Assembly.FullName : {0}", typeof(test_03).Assembly.FullName); Console.WriteLine("typeof(test_03).FullName : {0}", typeof(test_03).FullName); Console.WriteLine("otest03.GetType().FullName : {0}", otest03.GetType().Assembly.FullName); Console.WriteLine("otest03.GetType().FullName : {0}", otest03.GetType().FullName); test_03 test03 = (test_03)otest03; Console.WriteLine("test03.GetMessage() : {0}", test03.GetMessage()); Console.WriteLine("test03_2.GetMessage() : {0}", ((test_03)otest03_2).GetMessage()); AppDomain.Unload(domain); }
public override bool Execute() { AppDomain domain = AppDomain.CreateDomain("reflectionRomain"); try { dynamic obj = domain.CreateInstanceFromAndUnwrap(this.GetType().Assembly.Location, "Signum.TSGenerator.ProxyGenerator"); foreach (var file in Directory.EnumerateFiles(Directory.GetCurrentDirectory(), "*.t4s", SearchOption.AllDirectories)) { try { Log.LogMessage($"Reading {file}"); string result = obj.Process(file, References, this.BuildEngine.ProjectFileOfTaskNode); var targetFile = Path.ChangeExtension(file, ".ts"); if (File.Exists(targetFile) && File.ReadAllText(targetFile) == result) { Log.LogMessage($"Skipping {targetFile} (Up to date)"); } else { Log.LogMessage($"Writing {targetFile}"); File.WriteAllText(targetFile, result); } } catch (LoggerException ex) { Log.LogError(null, ex.ErrorCode, ex.HelpKeyword, file, (int)ex.Data["LineNumber"], 0, 0, 0, ex.Message); } catch (Exception ex) { Log.LogError(null, null, null, file, 0, 0, 0, 0, ex.Message); } } } finally { AppDomain.Unload(domain); } return(!Log.HasLoggedErrors); }
private void Create(bool recreate = false) { if (domain == null || recreate) { if (domain != null) { frm.Hide(); AppDomain.Unload(domain); domain = null; } var myLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var info = new AppDomainSetup { ShadowCopyFiles = "true" }; domain = AppDomain.CreateDomain("TranscodingDomain", null, info); frm = (RemoteImageViewer)domain.CreateInstanceFromAndUnwrap(typeof(RemoteImageViewer).Assembly.Location, typeof(RemoteImageViewer).FullName); frm.InitPlugin(pluginPath); } frm.SetFramesPerSecond(framesPerSecond); frm.SetOnError(onError); if (sessionDataPath != null) { frm.SetSessionDataPath(sessionDataPath); } if (backgroundImage != null) { frm.SetBackgroundImage(backgroundImage); } frm.ClientSize = clientSize; frm.SetPosition(left, top); frm.SetPlaybackSpeed(playbackSpeed); frm.SetOnAnimationTick(onAnimationTick); frm.SetDrawAction(drawAction); frm.SetPaused(isPaused); frm.Refresh(); }
private void RunApplication(string action) { if (watcher == null) { watcher = new FileSystemWatcher(AppDomain.CurrentDomain.BaseDirectory, "*.dll"); watcher.Changed += delegate(object sender, FileSystemEventArgs e) { StopRunner(string.Format(System.Globalization.CultureInfo.CurrentCulture, "One or more DLLs have changed - waiting {0}s", restartTime)); waitTimer.Stop(); waitTimer.Start(); }; watcher.EnableRaisingEvents = true; watcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite | NotifyFilters.Size; } // Allow the user to turn shadow-copying off var setting = ConfigurationManager.AppSettings["ShadowCopy"] ?? string.Empty; var useShadowCopying = !(string.Equals(setting, "off", StringComparison.InvariantCultureIgnoreCase) || string.Equals(setting, "false", StringComparison.InvariantCultureIgnoreCase)); try { this.runnerDomain = CreateNewDomain(useShadowCopying); } catch (FileLoadException) { // Unable to use shadow-copying (no user profile?), therefore turn off shadow-copying useShadowCopying = false; this.runnerDomain = CreateNewDomain(useShadowCopying); } runner = runnerDomain.CreateInstanceFromAndUnwrap(Assembly.GetExecutingAssembly().Location, typeof(AppRunner).FullName) as AppRunner; try { runner.Run(action, useShadowCopying); } catch (SerializationException) { var configFilename = ConfigurationManager.AppSettings["ccnet.config"]; configFilename = string.IsNullOrEmpty(configFilename) ? Path.Combine(Environment.CurrentDirectory, "ccnet.log") : configFilename; throw new ApplicationException( string.Format(System.Globalization.CultureInfo.CurrentCulture, "A fatal error has occurred while starting CCService. Please check '{0}' for any details.", configFilename)); } }
public virtual PluginInfoList Probe(string pluginFolderPath, SearchOption scanDeapth) { AppDomain domain = null; PluginInfoList infoList = new PluginInfoList(); domain = AppDomain.CreateDomain("PluginLoaderBase.Probe"); Type t = this.GetType(); PluginLoaderBase loader = (PluginLoaderBase)domain.CreateInstanceFromAndUnwrap(t.Assembly.Location, t.FullName); infoList = loader.OnProbeWrapper(pluginFolderPath, scanDeapth); AppDomain.Unload(domain); ProbeCompleteEventArgs probeCompleteArgs = new ProbeCompleteEventArgs(infoList); this.OnProbeComplete(probeCompleteArgs); return(infoList); }
/// <summary> /// Searches for plugin types from assemblies in the application's startup path in a second AppDomain /// </summary> /// <returns></returns> internal static TypeCollection SearchForPluginTypes() { // create a new appdomain where we'll try and load the plugins AppDomain domain = AppDomain.CreateDomain(Guid.NewGuid().ToString()); string typeName = typeof(TypeLoader).FullName ?? string.Empty; // create an instance of the plugin loader in the new appdomain var loader = (TypeLoader)domain.CreateInstanceFromAndUnwrap(Assembly.GetExecutingAssembly().Location, typeName); // use the loader to search for plugins inside the second appdomain TypeCollection types = loader.InternalSearchForPluginTypes(); // unload the appdomain AppDomain.Unload(domain); // return the plugin descriptors that were found return(types); }
public AppDomainIsolation() { var setup = new AppDomainSetup { ShadowCopyFiles = "true" }; _domain = AppDomain.CreateDomain("AppDomainIsolation:" + Guid.NewGuid(), null, setup); var type = typeof(T); try { _object = (T)_domain.CreateInstanceAndUnwrap(type.Assembly.FullName, type.FullName); } catch { _object = (T)_domain.CreateInstanceFromAndUnwrap(type.Assembly.Location, type.FullName); } }
/// <summary> /// 加载应用程序域,获取相应实例 /// </summary> /// <param name="dllpath"></param> /// <param name="classpath"></param> /// <param name="domain"></param> /// <returns></returns> public T Load(string dllpath, string classpath, out AppDomain domain) { try { if (File.Exists(dllpath)) { AppDomainSetup setup = new AppDomainSetup(); if (File.Exists(dllpath + ".config")) { setup.ConfigurationFile = dllpath + ".config"; log.Debug(string.Format("[QMAppDomainLoader] 加载config file:{0}", setup.ConfigurationFile)); } setup.ApplicationBase = Path.GetDirectoryName(dllpath); log.Debug(string.Format("[QMAppDomainLoader] 加载目录:{0}", setup.ApplicationBase)); setup.CachePath = setup.ApplicationBase; setup.ShadowCopyFiles = "true"; setup.ShadowCopyDirectories = setup.ApplicationBase; //setup.ApplicationName = "Dynamic"; domain = AppDomain.CreateDomain(Path.GetFileName(dllpath), null, setup); AppDomain.MonitoringIsEnabled = true; T obj = (T)domain.CreateInstanceFromAndUnwrap(dllpath, classpath); return(obj); } else { log.Error(string.Format("[QMAppDomainLoader] 加载 file 不存在!:{0}", dllpath)); } } catch (QMException ex) { log.Error(ex.Message); } domain = null; T obj1 = null; return(obj1); }
/// <summary> /// 加载应用程序域,获取相应实例 /// </summary> /// <param name="dllpath"></param> /// <param name="classpath"></param> /// <param name="domain"></param> /// <returns></returns> public T Load(string dllpath, string classpath, out AppDomain domain) { AppDomainSetup setup = new AppDomainSetup(); if (System.IO.File.Exists(dllpath + ".config")) { setup.ConfigurationFile = dllpath + ".config"; } setup.ShadowCopyFiles = "true"; setup.ApplicationBase = System.IO.Path.GetDirectoryName(dllpath); domain = AppDomain.CreateDomain(System.IO.Path.GetFileName(dllpath), null, setup); // domain.UnhandledException += Domain_UnhandledException; AppDomain.MonitoringIsEnabled = true; T obj = (T)domain.CreateInstanceFromAndUnwrap(dllpath, classpath); return(obj); }
protected override void InstantiateWorker() { AppDomainSetup appDomainSetup = new AppDomainSetup(); Evidence adevidence = AppDomain.CurrentDomain.Evidence; appDomainSetup.ApplicationBase = WorkerManagerFolder; appDomainSetup.PrivateBinPath = WorkerFolder; appDomainSetup.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; appDomainSetup.ApplicationName = WorkAssignment.WorkerId; AppDomain appDomain = AppDomain.CreateDomain(WorkAssignment.WorkerId, adevidence, appDomainSetup); if (appDomain == null) { Tracer.Error("Failed to CrateDomain for worker {0}", WorkAssignment.WorkerId); return; } object obj = null; try { obj = appDomain.CreateInstanceFromAndUnwrap(WorkerCard.AssemblyPath, WorkerCard.TypeName); } catch (Exception ex) { Tracer.Error("Failed to load type {0} from assembly {1}. Exception: {2}", WorkerCard.TypeName, WorkerCard.AssemblyPath, ex); return; } if (obj == null) { Tracer.Error("WorkerManager failed to load type {0} from assembly {1}", WorkerCard.TypeName, WorkerCard.AssemblyPath); return; } WorkerBaseInstance = obj as WorkerBase; if (WorkerBaseInstance == null) { Tracer.Error("Failed to cast the type {0} from assembly {1} to WorkerBase", WorkerCard.TypeName, WorkerCard.AssemblyPath); return; } }
private void init() { baseFolder = loadConfigValues(configFile); if (baseFolder == null) { return; } AppDomain rootDomain = AppDomain.CurrentDomain; try { if (domain == null) { AppDomainSetup domainSetup = new AppDomainSetup(); domainSetup.ConfigurationFile = Path.GetFullPath(configFile); domainSetup.ApplicationBase = baseFolder; domainSetup.ShadowCopyFiles = "true"; string name = configFile.Replace(".config", ""); name = name.Substring(name.LastIndexOf('/') + 1); domain = AppDomain.CreateDomain(name, null, domainSetup); } string assembly = GetType().Assembly.Location; Object[] args = new Object[] { rootDomain }; DB.Print("Creating root", Levels.SCRIPTS); proxy = (Root)domain.CreateInstanceFromAndUnwrap(assembly, "scripts.Root", false, BindingFlags.CreateInstance, null, args, null, null, null); if (proxy.Shutdown) { unloadDomain("Shutdown flagged after creating root"); } else { DB.Print("Root created", Levels.SCRIPTS); } } catch (Exception e) { DB.Exception(e, "Problem creating root", Levels.SCRIPTS); unloadDomain("Exception creating root"); } }
public SectionResponseEnum Execute(PackageClass packageClass, ActionItem actionItem) { if (packageClass.Silent) { return(SectionResponseEnum.Ok); } try { if (!packageClass.Silent && File.Exists(MpeInstaller.TransformInRealPath(actionItem.Params[Const_APP].Value))) { string assemblyFileName = MpeInstaller.TransformInRealPath(actionItem.Params[Const_APP].Value); AppDomainSetup setup = new AppDomainSetup(); setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; setup.PrivateBinPath = Path.GetDirectoryName(assemblyFileName); setup.ApplicationName = Path.GetFileName(Assembly.GetExecutingAssembly().Location); setup.ShadowCopyFiles = "true"; setup.ShadowCopyDirectories = Path.GetDirectoryName(assemblyFileName); AppDomain appDomain = AppDomain.CreateDomain("pluginDomain", null, setup); PluginLoader remoteExecutor = (PluginLoader) appDomain.CreateInstanceFromAndUnwrap(Assembly.GetExecutingAssembly().Location, typeof(PluginLoader).ToString()); remoteExecutor.Load(assemblyFileName); remoteExecutor.Dispose(); AppDomain.Unload(appDomain); } } catch (Exception) { if (ItemProcessed != null) { ItemProcessed(this, new InstallEventArgs("Error to configure plugin")); } return(SectionResponseEnum.Ok); } if (ItemProcessed != null) { ItemProcessed(this, new InstallEventArgs("Plugin configuration donne")); } return(SectionResponseEnum.Ok); }
private static void ExecuteRemotely(Action <AppDomainWorker> workerAction) { AppDomain domain = AppDomain.CreateDomain("CodeInvoker"); try { // load CodeExecutor.dll into the other app domain domain.Load(typeof(RemoteCodeExecutor).Assembly.GetName()); var worker = (AppDomainWorker)domain.CreateInstanceFromAndUnwrap( Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CodeExecutor.dll"), "CodeExecutor.AppDomainWorker"); workerAction(worker); } finally { AppDomain.Unload(domain); } }
private ICustomOperation CreateProxyInstanceForOperation() { string basePath = Path.GetDirectoryName(this.AssemblyFullPath); AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation; setup.ApplicationName = "OperationFactoryTemp"; setup.ApplicationBase = basePath; setup.PrivateBinPath = basePath; setup.ShadowCopyFiles = "true"; setup.ShadowCopyDirectories = this.WorkRootDirectory; setup.CachePath = this.WorkRootDirectory; //setup.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; //Evidence evidence = new Evidence(AppDomain.CurrentDomain.Evidence); //PermissionSet grantSet = new PermissionSet(PermissionState.Unrestricted); AppDomain sandboxDomain = AppDomain.CreateDomain($"{setup.ApplicationName}_Domain_{Guid.NewGuid()}", null, setup); return(sandboxDomain.CreateInstanceFromAndUnwrap(this.AssemblyFullPath, this.ClassName, true, BindingFlags.Default, null, null, null, null) as ICustomOperation); }