public void RestrictedTrust() { var domainSetup = new AppDomainSetup { ApplicationBase = AppDomain.CurrentDomain.BaseDirectory }; var permissions = new PermissionSet(null); permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution)); var domain = AppDomain.CreateDomain("Partial Trust AppDomain", null, domainSetup, permissions); try { var test = (TrustTestClass)domain.CreateInstanceAndUnwrap( typeof(TrustTestClass).Assembly.FullName, typeof(TrustTestClass).FullName ); test.Go(ConnectionString); } finally { AppDomain.Unload(domain); } }
public void TestEqualsPartialTrust() { var appDomainSetUp = new AppDomainSetup() { ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase }; var evidence = new Evidence(); #if MONO || NETFX_35 #pragma warning disable 0612 // TODO: patching // currently, Mono does not declare AddHostEvidence evidence.AddHost(new Zone(SecurityZone.Internet)); #pragma warning restore 0612 var permisions = GetDefaultInternetZoneSandbox(); #else evidence.AddHostEvidence(new Zone(SecurityZone.Internet)); var permisions = SecurityManager.GetStandardSandbox(evidence); #endif // if MONO || NETFX_35 AppDomain workerDomain = AppDomain.CreateDomain("PartialTrust", evidence, appDomainSetUp, permisions, GetStrongName(this.GetType())); try { workerDomain.DoCallBack(TestEqualsWorker); #if !MONO // P/Invoke is not disabled on Mono even if in the InternetZone. Assert.That(( bool )workerDomain.GetData("MessagePackString.IsFastEqualsDisabled"), Is.True); #endif // if !MONO Console.WriteLine("TestEqualsPartialTrust"); ShowResult(workerDomain.GetData("TestEqualsWorker.Performance") as Tuple <double, double, double, double>); } finally { AppDomain.Unload(workerDomain); } }
public async Task ComposableAssembliesLazyLoadedWithGenericTypeArg() { SkipOnMono(); var catalog = TestUtilities.EmptyCatalog.AddParts( await TestUtilities.V2Discovery.CreatePartsAsync(typeof(PartImportingOpenGenericExport), typeof(OpenGenericExport <>))); var catalogCache = await this.SaveCatalogAsync(catalog); var configuration = CompositionConfiguration.Create(catalog); var compositionCache = await this.SaveConfigurationAsync(configuration); // Use a sub-appdomain so we can monitor which assemblies get loaded by our composition engine. var appDomain = AppDomain.CreateDomain("Composition Test sub-domain", null, AppDomain.CurrentDomain.SetupInformation); try { var driver = (AppDomainTestDriver)appDomain.CreateInstanceAndUnwrap(typeof(AppDomainTestDriver).Assembly.FullName, typeof(AppDomainTestDriver).FullName); driver.Initialize(this.cacheManager.GetType(), compositionCache, catalogCache); driver.TestPartThatImportsExportWithGenericTypeArg(typeof(SomeOtherType).Assembly.Location); } finally { AppDomain.Unload(appDomain); } }
private static AppDomain CreateSandbox(bool forTesting) { var permissions = new PermissionSet(PermissionState.None); //if (forTesting) permissions = new PermissionSet(PermissionState.Unrestricted); //permissions.AddPermission(new Permission) permissions.AddPermission( new SecurityPermission(SecurityPermissionFlag.AllFlags)); permissions.AddPermission(new UIPermission(UIPermissionWindow.AllWindows)); permissions.AddPermission( new TypeDescriptorPermission(TypeDescriptorPermissionFlags.RestrictedRegistrationAccess)); permissions.AddPermission( new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, AppDomain.CurrentDomain.BaseDirectory)); permissions.AddPermission(new ReflectionPermission(PermissionState.Unrestricted)); var appinfo = new AppDomainSetup { ApplicationBase = AppDomain.CurrentDomain.BaseDirectory }; return(AppDomain.CreateDomain("Scripting sandbox", null, appinfo, permissions)); }
private static Runtime.AssemblyContextRef CreatePreloadedContextAppDomain(string entryPointArgEx) { string appDomainName = "Domain" + Environment.TickCount + " " + appDomainCount++; AppDomainSetup appDomainSetup = new AppDomainSetup(); appDomainSetup.ApplicationBase = currentAssemblyDirectory; appDomainSetup.ApplicationName = appDomainName; if (ShadowCopyAssembly) { appDomainSetup.ShadowCopyFiles = "true"; // Main assembly must be in the same or sub directory (limitation of PrivateBinPath) string subDirectory; IsSameOrSubDirectory(currentAssemblyDirectory, mainAssemblyDirectory, out subDirectory); if (!string.IsNullOrEmpty(subDirectory)) { appDomainSetup.PrivateBinPath = subDirectory; } } //AppDomain preloadAppDomain = AppDomain.CreateDomain(appDomainName, null, mainAssemblyDirectory, ".", false); AppDomain preloadAppDomain = AppDomain.CreateDomain(appDomainName, null, appDomainSetup); return Runtime.AssemblyContext.Create(preloadAppDomain); }
public async Task ComposableAssembliesLazyLoadedWhenQueried() { SkipOnMono(); var exportedTypes = new List <Type> { typeof(ExternalExport), typeof(YetAnotherExport), typeof(ExternalExportOnMember), }; var catalog = TestUtilities.EmptyCatalog.AddParts(await TestUtilities.V2Discovery.CreatePartsAsync(exportedTypes)); var catalogCache = await this.SaveCatalogAsync(catalog); var configuration = CompositionConfiguration.Create(catalog); var compositionCache = await this.SaveConfigurationAsync(configuration); foreach (var exportedType in exportedTypes) { catalogCache.Position = 0; compositionCache.Position = 0; // Use a sub-appdomain so we can monitor which assemblies get loaded by our composition engine. var appDomain = AppDomain.CreateDomain("Composition Test sub-domain", null, AppDomain.CurrentDomain.SetupInformation); try { var driver = (AppDomainTestDriver)appDomain.CreateInstanceAndUnwrap(typeof(AppDomainTestDriver).Assembly.FullName, typeof(AppDomainTestDriver).FullName); driver.Initialize(this.cacheManager.GetType(), compositionCache, catalogCache); driver.TestExternalExport(exportedType.Assembly.Location, exportedType.FullName); } finally { AppDomain.Unload(appDomain); } } }
/// <summary> /// Компилирует переданный скрипт в отдельном домене. После этого можно вызывать метод Execute. /// Во избежание утечек памяти после окончания использования скрипта следует вызвать Unload для выгрузки домена! /// </summary> /// <param name="script">Скрипт, который необходимо сгенерировать, в виде строки. /// В действительности скрипт является содержимым метода, который будет вызван при Execute. /// Таким образом, в скрипте допустимы только те конструкции, которые допустимы внутри метода C#. /// Нельзя объявлять классы, методы, добавлять using пространства имён и т.д.</param> /// <param name="returnType">Тип возвращаемого скриптом значения в виде строки. /// При несответствии фактическому возвращенному значению выбрасывается исключение с ошибкой компиляции.</param> /// <param name="parameterSignature">Сигнатура параметров метода, в виде строки. /// В скрипте будут доступны переданные параметры. При вызове Execute объект args должен соответствовать сигнатуре.</param> /// <param name="assemblies">Имена файлов сборок (dll, exe), которые должны быть доступны в скрипте.</param> /// <param name="namespaces">Пространства имён, доступные скрипту. (Будут прописаны с директивой using).</param> public void Compile(string script, string returnType, string parameterSignature, string[] assemblies, string[] namespaces) { appDomainSetup = new AppDomainSetup(); appDomainSetup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; appDomainSetup.DisallowBindingRedirects = false; appDomainSetup.DisallowCodeDownload = true; appDomainSetup.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; workerAppDomain = AppDomain.CreateDomain("Compiler", null, appDomainSetup); string usingStatements = string.Empty; if (namespaces != null) { foreach (string ns in namespaces) { usingStatements += "using " + ns + "; "; } } //Чтобы можно было корректно выдать номер строки с ошибкой в скрипте, сам скрипт должен начинаться с первой строки. string code = usingStatements + @"namespace ScriptInterfaceSH { public static class MainDynamicClass { public static " + returnType + " MainDynamicMethod(" + parameterSignature + ") { " + script + " } } }"; //Компилятор создаётся в отдельном домене. Домен можно выгрузить, избежав утечек памяти. //Если компилировать скрипт в основном домене, то скомпилированные сборки невозможно будет выгрузить - это будут утечки памяти. compiler = (DynamicCompiler)workerAppDomain.CreateInstanceAndUnwrap( typeof(DynamicCompiler).Assembly.GetName().Name, typeof(DynamicCompiler).FullName); compiler.Compile(code, assemblies, "MainDynamicMethod"); canExecute = true; }
private AppDomain CreateSandboxDomain(AppDomainSetup adSetup, string templateAssemblyPath) { // Create restricted permissions var permSet = new PermissionSet(PermissionState.None); permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution)); var fperm = new FileIOPermission(PermissionState.None) { AllFiles = FileIOPermissionAccess.NoAccess }; var roAccess = FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery; fperm.AddPathList(roAccess, Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)); // App directory -> Load Dependencies fperm.AddPathList(roAccess, Path.GetDirectoryName(templateAssemblyPath)); // Directory containing templateAssembly permSet.AddPermission(fperm); // StrongNames of FullTrust-Assemblies var sharedAssembly = GetStrongName(typeof(Timetable)); var clientAssembly = GetStrongName(typeof(Template)); // Create new, isolated AppDomain return(AppDomain.CreateDomain("tmpl-run-domain", null, adSetup, permSet, sharedAssembly, clientAssembly)); }
static void MarshalByObjectDemo() { Console.WriteLine("--------MarshalByObjectDemo------------"); // 创建一个新的应用程序域 - NewDomain AppDomain newDomain = AppDomain.CreateDomain("NewDomain"); DemoClass2 obj; DemoClass2 obj2; obj = (DemoClass2)newDomain.CreateInstanceAndUnwrap("ClassLib", "ClassLib.DemoClass2"); obj.ShowAppDomain(); obj.ShowCount("Zhang"); obj.ShowCount("Zhang"); obj2 = (DemoClass2)newDomain.CreateInstanceAndUnwrap("ClassLib", "ClassLib.DemoClass2"); obj2.ShowAppDomain(); obj2.ShowCount("Jimmy"); obj2.ShowCount("Jimmy"); Console.WriteLine("------------End---------------"); }
public ProjectExecutionContext(Project project, IServiceProvider serviceProvider) { Debug.Assert(project != null, "project is null."); Debug.Assert(!VsUtils.IsMiscellaneousProject(project), "project is misc files project."); _domain = AppDomain.CreateDomain( "ProjectExecutionContextDomain", null, new AppDomainSetup { ApplicationBase = VsUtils.GetProjectTargetDir(project, serviceProvider), ConfigurationFile = VsUtils.GetProjectConfigurationFile(project, serviceProvider), ShadowCopyFiles = "true" // Prevents locking }); var dataDirectory = VsUtils.GetProjectDataDirectory(project, serviceProvider); if (dataDirectory != null) { _domain.SetData("DataDirectory", dataDirectory); } _executor = new ExecutorWrapper(_domain, VsUtils.GetProjectTargetFileName(project)); }
public static T Create(string pluginFolderPath, object[] arguments = null, string shadowCopyName = "ShadowCopyCache", string domainName = "Host_AppDomain") { var pluginCacheFolderPath = Path.Combine(pluginFolderPath, shadowCopyName); // Check if plug-in and shadow copy folders already exist, create otherwise. Directory.CreateDirectory(pluginFolderPath); Directory.CreateDirectory(pluginCacheFolderPath); // This creates a ShadowCopy of the MEF DLL's. var setup = new AppDomainSetup { CachePath = pluginCacheFolderPath, ShadowCopyFiles = "true", ShadowCopyDirectories = pluginFolderPath }; // Create separate domain. var domain = AppDomain.CreateDomain(domainName, AppDomain.CurrentDomain.Evidence, setup); // Create new PluginContainer using new separate domain. var pluginProvider = (T)domain.CreateInstanceAndUnwrap(typeof(T).Assembly.FullName, typeof(T).FullName, false, BindingFlags.CreateInstance, null, arguments, null, null); return(pluginProvider); }
//----------------------------------------------------------------------------------------------- // private methods //----------------------------------------------------------------------------------------------- /// <summary> /// Written by Abhishek Kumar on March 05, 2007 /// purpose: to initiate the central Application Domain that /// all Grid Threads will be run on. /// /// Police and permissions will also be set. /// ADV: a crash in this App Domain(because of poor code in GThread) /// does not affect eduGRID's Framework i.e. the Alchemi executor is maintained steady even in error /// /// initially Alchemi created separate app domains for each Gthread it received. /// now, instead, we create 1 appdomain and run all gthreads on it /// the Bot Logic resides in this app domain. /// (this saves the overhead of initializing bot logic for every Gthread (or every query)) /// </summary> private void initialize_GridThreadExecutor() { if (GridThreadExecutor == null) { string appDir = GetApplicationDirectory(_CurTi.ApplicationId); AppDomainSetup info = new AppDomainSetup(); info.PrivateBinPath = appDir; GridThreadApplicationDomain = AppDomain.CreateDomain("Central_AppDomain", null, info); // *** // http://www.dotnetthis.com/Articles/DynamicSandboxing.htm PolicyLevel domainPolicy = PolicyLevel.CreateAppDomainLevel(); AllMembershipCondition allCodeMC = new AllMembershipCondition(); // TODO: 'FullTrust' in the following line needs to be replaced with something like 'AlchemiGridThread' // This permission set needs to be defined and set automatically as part of the installation. PermissionSet internetPermissionSet = domainPolicy.GetNamedPermissionSet("FullTrust"); PolicyStatement internetPolicyStatement = new PolicyStatement(internetPermissionSet); CodeGroup allCodeInternetCG = new UnionCodeGroup(allCodeMC, internetPolicyStatement); domainPolicy.RootCodeGroup = allCodeInternetCG; GridThreadApplicationDomain.SetAppDomainPolicy(domainPolicy); GridThreadExecutor = (AppDomainExecutor)GridThreadApplicationDomain.CreateInstanceFromAndUnwrap(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Alchemi.Executor.dll"), "Alchemi.Executor.AppDomainExecutor"); } if (!GridThreadExecutor.Initialized) { try { GridThreadExecutor.initialize(); } catch (Exception ex) { throw new Exception("Error during initialization of GridThreadExecutor"); } } }
public async Task DisconnectRemoteObjectsAfterCrossDomainCallsOnDispose() { // Arrange var tracker = new InMemoryRemoteObjectTracker(); TrackingServices.RegisterTrackingHandler(tracker); var remote = AppDomain.CreateDomain("Remote", null, AppDomain.CurrentDomain.SetupInformation); // Act try { using (LogContext.PushProperty("Prop1", 42)) { remote.DoCallBack(CallFromRemote); using (LogContext.PushProperty("Prop2", 24)) { remote.DoCallBack(CallFromRemote); } } } finally { AppDomain.Unload(remote); } await Task.Delay(200); // Assert Assert.Equal(2, tracker.DisconnectCount); void CallFromRemote() { } }
public object executeAssembly(string assemblyName, Loader codeLoader, object param) { Evidence e = new Evidence(); e.AddHostEvidence(new Zone(SecurityZone.Intranet)); PermissionSet permSet = SecurityManager.GetStandardSandbox(e); AppDomainSetup ads = new AppDomainSetup(); ads.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; AppDomain tempDomain = AppDomain.CreateDomain(assemblyName + new Random().NextDouble(), e, ads, permSet, null); tempDomain.Load("CodeInterface"); ObjectHandle handle = Activator.CreateInstanceFrom(tempDomain, typeof(Sandboxer).Assembly.ManifestModule.FullyQualifiedName, typeof(Sandboxer).FullName); Sandboxer newDomainInstance = (Sandboxer)handle.Unwrap(); byte[] assemblyBinary = codeLoader.codeDictionary.ReadAssembly(assemblyName); object output = newDomainInstance.ExecuteNewAssembly(assemblyBinary, param); return(output); }
// Create a client, loaded in a new app domain. public T NewClient <T>(string ClusterId, int ClientNumber) where T : ClientWrapperBase { var ci = Clusters[ClusterId]; var name = string.Format("Client-{0}-{1}", ClusterId, ClientNumber); var gatewayport = DetermineGatewayPort(ci.SequenceNumber, ClientNumber); var clientArgs = new object[] { name, gatewayport }; var setup = new AppDomainSetup { ApplicationBase = Environment.CurrentDirectory }; var clientDomain = AppDomain.CreateDomain(name, null, setup); T client = (T)clientDomain.CreateInstanceFromAndUnwrap( Assembly.GetExecutingAssembly().Location, typeof(T).FullName, false, BindingFlags.Default, null, clientArgs, CultureInfo.CurrentCulture, new object[] { }); lock (activeClients) { activeClients.Add(clientDomain); } return(client); }
public static void Main() { // Set the default culture and display the current date in the current application domain. Info info1 = new Info(); SetAppDomainCultures("fr-FR"); // Create a second application domain. AppDomainSetup setup = new AppDomainSetup(); setup.AppDomainInitializer = SetAppDomainCultures; setup.AppDomainInitializerArguments = new string[] { "ru-RU" }; AppDomain domain = AppDomain.CreateDomain("Domain2", null, setup); // Create an Info object in the new application domain. Info info2 = (Info)domain.CreateInstanceAndUnwrap(typeof(Example).Assembly.FullName, "Info"); // Execute methods in the two application domains. info2.DisplayDate(); info2.DisplayCultures(); info1.DisplayDate(); info1.DisplayCultures(); }
public override AppDomain CreateAppDomainWithPolicy(string appDomainName, Evidence evidence, SandboxCasPolicySettings casSettings) { PermissionSet permissionSet = casSettings.BasePermissions; if (permissionSet == null) { permissionSet = new PermissionSet(PermissionState.None); permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution)); } StrongName[] baseFullTrustAssemblies = ControlPolicyManager.GetBaseFullTrustAssemblies(); int num = baseFullTrustAssemblies.Length; if (casSettings.FullTrustAssemblies != null) { num += casSettings.FullTrustAssemblies.Count; } StrongName[] array = new StrongName[num]; Array.Copy(baseFullTrustAssemblies, array, baseFullTrustAssemblies.Length); if (casSettings.FullTrustAssemblies != null) { casSettings.FullTrustAssemblies.CopyTo(array, baseFullTrustAssemblies.Length); } return(AppDomain.CreateDomain(appDomainName)); }
private static bool Create() { AppDomainSetup Setup = new AppDomainSetup { ApplicationName = "CBScriptContainer" + Guid.NewGuid().ToString("X") + "D", ApplicationBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\" }; PermissionSet permissions = new PermissionSet(PermissionState.Unrestricted); permissions.AddPermission(new EnvironmentPermission(EnvironmentPermissionAccess.Read, "USERNAME")); permissions.AddPermission(new FileIOPermission(FileIOPermissionAccess.AllAccess, Assembly.GetExecutingAssembly().Location)); permissions.AddPermission(new ReflectionPermission(PermissionState.Unrestricted)); permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution)); permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.Infrastructure)); permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.RemotingConfiguration)); permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.SerializationFormatter)); permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)); permissions.AddPermission(new UIPermission(PermissionState.Unrestricted)); permissions.AddPermission(new WebPermission(NetworkAccess.Connect, new Regex("https?:\\/\\/(\\w+)\\.carrybuddy\\.net\\/.*"))); Handle = AppDomain.CreateDomain("ScriptContainer", null, Setup, permissions); Execute = (Executer)Activator.CreateInstanceFrom(Handle, Assembly.GetExecutingAssembly().Location, typeof(Executer).FullName).Unwrap(); Execute.AttachToResolve(new ResolveEventHandler(Resolver)); return(Execute != null && Handle != null); }
static void Main(string[] args) { #if USE_INPROC_SILO // The Orleans silo environment is initialized in its own app domain in order to more // closely emulate the distributed situation, when the client and the server cannot // pass data via shared memory. AppDomain hostDomain = AppDomain.CreateDomain("OrleansHost", null, new AppDomainSetup { AppDomainInitializer = InitSilo, AppDomainInitializerArguments = args, }); #endif var config = ClientConfiguration.LocalhostSilo(); GrainClient.Initialize(config); Run().Wait(); Console.WriteLine("Orleans Silo is running.\nPress Enter to terminate..."); Console.ReadLine(); #if USE_INPROC_SILO hostDomain.DoCallBack(ShutdownSilo); #endif }
public void RequestForNameWithoutSectionThrows() { System.Configuration.Configuration configuration = ConfigurationTestHelper.GetConfigurationForCustomFile("test.exe.config"); configuration.Sections.Remove(ConfigurationSourceSection.SectionName); configuration.Save(); AppDomainSetup setupInfo = new AppDomainSetup(); setupInfo.ConfigurationFile = configuration.FilePath; setupInfo.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase; AppDomain newDomain = AppDomain.CreateDomain("test", null, setupInfo); try { ConfigurationSourceFactoryFixtureHelper helper = (ConfigurationSourceFactoryFixtureHelper)newDomain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(ConfigurationSourceFactoryFixtureHelper).FullName); helper.RequestForNameWithoutSectionThrows(); } finally { AppDomain.Unload(newDomain); } }
public async Task <AssemblyReference[]> ResolveReferences(string path) { return(await Task.Run(() => { AssemblyReference[] result; var domainSetup = new AppDomainSetup() { ApplicationBase = Path.GetDirectoryName(path) }; var domain = AppDomain.CreateDomain(Guid.NewGuid().ToString(), null, domainSetup); { var proxy = (AssemblyProxy)domain.CreateInstanceFromAndUnwrap( Assembly.GetExecutingAssembly().Location, typeof(AssemblyProxy).FullName); result = proxy.ResolveReferences(path); } AppDomain.Unload(domain); return result; }) .ConfigureAwait(false)); }
public static int test_0_invoke_after_unload() { AppDomain domain = AppDomain.CreateDomain("DeadInvokeTest"); Bar bar = (Bar)domain.CreateInstanceAndUnwrap(typeof(Tests).Assembly.FullName, "Bar"); int x; if (!RemotingServices.IsTransparentProxy(bar)) { return(3); } AppDomain.Unload(domain); try { x = bar.test(123); if (x == 124) { return(1); } return(2); } catch (Exception e) { return(0); } }
/// <summary> /// 根据Pwmis.core.dll文件所在目录初始化加载器 /// </summary> /// <param name="basePath"></param> public LocalLoader(string basePath) { AppDomainSetup setup = new AppDomainSetup(); setup.ApplicationName = "PdfNetApplication"; setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; setup.PrivateBinPath = Path.Combine(setup.ApplicationBase, "private"); setup.CachePath = setup.ApplicationBase; setup.ShadowCopyFiles = "true"; setup.ShadowCopyDirectories = setup.ApplicationBase; appDomain = AppDomain.CreateDomain("PdfNetDomain", null, setup); string fileName = Path.Combine(basePath, "PWMIS.Core.dll"); //var executeAssembly = Assembly.GetExecutingAssembly(); //string name = executeAssembly.GetName().FullName; //remoteLoader = (RemoteLoader)appDomain.CreateInstanceAndUnwrap( // name, // typeof(RemoteLoader).FullName); remoteLoader = (RemoteLoader)appDomain.CreateInstanceFromAndUnwrap( fileName,//例如: @"E:\SimpleAccessWinForm\bin\Debug\PWMIS.Core.dll", typeof(RemoteLoader).FullName); }
/// <summary> /// Creates a new new keyword map on a new app domain /// </summary> public static KeywordMap CreateDomain(KeywordMapConfig config) { try { log.Debug(String.Format("Creating appDomain for type {0}", config.Type)); //setup domain var kwdomainsetup = new AppDomainSetup(); kwdomainsetup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase; //create domain var kwdomain = AppDomain.CreateDomain(config.Type, null, kwdomainsetup); //get remote builder instance var remotebuilder = (KeywordMapBuilder)kwdomain.CreateInstanceAndUnwrap("NRobotRemote.Domain", typeof(KeywordMapBuilder).FullName); //call remote builder var map = remotebuilder.CreateMap(config); //log keyword names log.Debug(String.Format("Keyword names are, {0}", String.Join(",", map.GetKeywordNames().ToArray()))); return(map); } catch (Exception e) { log.Error(String.Format("Exception creating keyword domain, {0}", e.Message)); throw new KeywordDomainException(e.Message); } }
public static int test_0_appdomain_switch() { // FIXME: The appdomain unload hangs //return 0; AppDomain ad = AppDomain.CreateDomain("foo"); var c = (CallbackClass)ad.CreateInstanceAndUnwrap( typeof(CallbackClass).Assembly.FullName, "Tests/CallbackClass"); c.SetCallback(); int domain_id = AppDomain.CurrentDomain.Id; int new_id = mono_test_marshal_call_callback(); int res = 0; if (new_id == domain_id) { res = 1; } if (AppDomain.CurrentDomain.Id != domain_id) { res = 2; } AppDomain.Unload(ad); return(res); }
/// <summary> /// Application instance that lives in a dedicated app domain /// </summary> /// <param name="parentDirectory"></param> /// <param name="application"></param> /// <param name="instanceGuid"></param> internal AppDomainApplication( IComponentDirectory parentDirectory, ApplicationDesc application, Guid instanceGuid, ulong instanceNumber) { this.instanceGuid = instanceGuid; this.instanceNumber = instanceNumber; string iname = application.Name + " " + instanceGuid.ToString(); appDomain = AppDomain.CreateDomain(iname); /* create instance and unwrap the caller so that all the stuff happens in its own domain */ this.bridge = appDomain.CreateInstanceAndUnwrap( typeof(Bridge).Assembly.FullName, typeof(Bridge).FullName) as Bridge; this.applicationDescriptor = application; /* set up the instance */ this.bridge.Setup(parentDirectory, application, instanceGuid, this, parentDirectory.GetInstance <IAssemblyLoader>()); this.bridge.Callback = this; }
// .NET versions greater than v4.0 report as v4.0, so look at // the TargetFrameworkAttribute on the assembly if it exists private static void SetTargetFramework(string assemblyPath, AppDomainSetup setup) { var property = typeof(AppDomainSetup).GetProperty("TargetFrameworkName", BindingFlags.Public | BindingFlags.Instance); // If property is null, .NET 4.5+ is not installed, so there is no need if (property != null) { var domain = AppDomain.CreateDomain("TargetFrameworkDomain"); try { var agentType = typeof(TargetFrameworkAgent); var agent = domain.CreateInstanceFromAndUnwrap(agentType.Assembly.CodeBase, agentType.FullName) as TargetFrameworkAgent; var targetFramework = agent.GetTargetFrameworkName(assemblyPath); if (!string.IsNullOrEmpty(targetFramework)) { property.SetValue(setup, targetFramework, null); } } finally { AppDomain.Unload(domain); } } }
public static IDictionary <string, IEnumerable <string> > GetBinAssemblyReferences(string appPath, string configPath) { string binDirectory = Path.Combine(appPath, "bin"); if (!Directory.Exists(binDirectory)) { return(null); } AppDomain appDomain = null; try { var appDomainSetup = new AppDomainSetup { ApplicationBase = appPath, ConfigurationFile = configPath, PrivateBinPath = binDirectory, }; appDomain = AppDomain.CreateDomain(typeof(AppDomainHelper).Namespace, AppDomain.CurrentDomain.Evidence, appDomainSetup); var type = typeof(RemoteAssemblyLoader); var instance = (RemoteAssemblyLoader)appDomain.CreateInstanceAndUnwrap(type.Assembly.FullName, type.FullName); return(Directory.EnumerateFiles(binDirectory, "*.dll") .ToDictionary(assemblyPath => assemblyPath, assemblyPath => instance.GetReferences(assemblyPath))); } finally { if (appDomain != null) { AppDomain.Unload(appDomain); } } }
public async Task ComposableAssembliesLazyLoadedWhenCustomMetadataIsRequired() { SkipOnMono(); var catalog = TestUtilities.EmptyCatalog.AddParts( await TestUtilities.V2Discovery.CreatePartsAsync(typeof(ExportWithCustomMetadata), typeof(PartThatLazyImportsExportWithMetadataOfCustomType))); var catalogCache = await this.SaveCatalogAsync(catalog); var configuration = CompositionConfiguration.Create(catalog); var compositionCache = await this.SaveConfigurationAsync(configuration); // Use a sub-appdomain so we can monitor which assemblies get loaded by our composition engine. var appDomain = AppDomain.CreateDomain("Composition Test sub-domain", null, AppDomain.CurrentDomain.SetupInformation); try { var driver = (AppDomainTestDriver)appDomain.CreateInstanceAndUnwrap(typeof(AppDomainTestDriver).Assembly.FullName, typeof(AppDomainTestDriver).FullName); driver.Initialize(this.cacheManager.GetType(), compositionCache, catalogCache); driver.TestPartThatLazyImportsExportWithMetadataOfCustomType(typeof(CustomEnum).Assembly.Location, this is AssembliesLazyLoadedDataFileCacheTests); } finally { AppDomain.Unload(appDomain); } }
public virtual int ExecuteTemplate() { #if USE_APP_DOMAIN // Execute the (initial) template by GenerationHost in separate AppDomain: AppDomain appDomain = null; GenerationHost genHost = null; try { AppDomainSetup info = new AppDomainSetup(); info.ApplicationBase = new FileInfo(Assembly.GetEntryAssembly().Location).Directory.FullName; info.ShadowCopyFiles = "true"; appDomain = AppDomain.CreateDomain("CodeGenSpace", AppDomain.CurrentDomain.Evidence, info); genHost = (GenerationHost)appDomain.CreateInstance(typeof(GenerationHost).Assembly.FullName, typeof(GenerationHost).FullName).Unwrap(); genHost.Initialize(this.Settings); return(this.ExecuteTemplate(genHost)); } finally { if (genHost != null) { genHost.Dispose(); } if (appDomain != null) { AppDomain.Unload(appDomain); } } #else // execute the generationhost locally using (ResourceBasedGenerationHost genHost = new ResourceBasedGenerationHost()) { genHost.Initialize(this.Settings); return(this.ExecuteTemplate(genHost)); } #endif }