public void ConfigurationFile_Absolute_NoApplicationBase () { AppDomainSetup setup = new AppDomainSetup(); string configFile = Path.GetFullPath("blar.config"); setup.ConfigurationFile = configFile; Assert.AreEqual(configFile, setup.ConfigurationFile); }
// This method is called from unmanaged code in a temporary AppDomain, just to be able to call // the right AppDomain.CreateDomain overload. public static AppDomain CreateFullTrustSandbox() { try { Debug.Print("CreateSandboxAndInitialize - in loader AppDomain with Id: " + AppDomain.CurrentDomain.Id); PermissionSet pset = new PermissionSet(PermissionState.Unrestricted); AppDomainSetup loaderAppDomainSetup = AppDomain.CurrentDomain.SetupInformation; AppDomainSetup sandboxAppDomainSetup = new AppDomainSetup(); sandboxAppDomainSetup.ApplicationName = loaderAppDomainSetup.ApplicationName; sandboxAppDomainSetup.ConfigurationFile = loaderAppDomainSetup.ConfigurationFile; sandboxAppDomainSetup.ApplicationBase = loaderAppDomainSetup.ApplicationBase; sandboxAppDomainSetup.ShadowCopyFiles = loaderAppDomainSetup.ShadowCopyFiles; sandboxAppDomainSetup.ShadowCopyDirectories = loaderAppDomainSetup.ShadowCopyDirectories; // create the sandboxed domain AppDomain sandbox = AppDomain.CreateDomain( "FullTrustSandbox(" + AppDomain.CurrentDomain.FriendlyName + ")", null, sandboxAppDomainSetup, pset); Debug.Print("CreateFullTrustSandbox - sandbox AppDomain created. Id: " + sandbox.Id); return sandbox; } catch (Exception ex) { Debug.Print("Error during CreateFullTrustSandbox: " + ex.ToString()); return AppDomain.CurrentDomain; } }
private static AppDomain CreateRestrictedDomain(string domainName) { // Default to all code getting nothing PolicyStatement emptyPolicy = new PolicyStatement(new PermissionSet(PermissionState.None)); UnionCodeGroup policyRoot = new UnionCodeGroup(new AllMembershipCondition(), emptyPolicy); // Grant all code the named permission set for the test PermissionSet partialTrustPermissionSet = new PermissionSet(PermissionState.None); partialTrustPermissionSet.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.AllFlags)); partialTrustPermissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution | SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)); PolicyStatement permissions = new PolicyStatement(partialTrustPermissionSet); policyRoot.AddChild(new UnionCodeGroup(new AllMembershipCondition(), permissions)); // Create an AppDomain policy level for the policy tree PolicyLevel appDomainLevel = PolicyLevel.CreateAppDomainLevel(); appDomainLevel.RootCodeGroup = policyRoot; // Set the Application Base correctly in order to find the test assembly AppDomainSetup ads = new AppDomainSetup(); ads.ApplicationBase = Environment.CurrentDirectory; AppDomain restrictedDomain = AppDomain.CreateDomain(domainName, null, ads); restrictedDomain.SetAppDomainPolicy(appDomainLevel); return restrictedDomain; }
public void LoadModule(string filename) { if (LoadedModules.ContainsKey(filename)) UnloadModule(filename); var setup = new AppDomainSetup { ApplicationBase = appDirectory }; var domain = AppDomain.CreateDomain(filename, null, setup); try { var path = Path.Combine(modulesDirectory, filename + ".dll"); var loader = (ModuleLoader)domain.CreateInstanceAndUnwrap(typeof(ModuleLoader).Assembly.FullName, typeof(ModuleLoader).FullName); var module = loader.LoadModule(path); if (module != null) { module.ModuleManager = this; module.Client = client; LoadedModules.Add(filename, new LoadedModule { Domain = domain, Module = module }); Console.WriteLine("Loaded {0}", filename); } else AppDomain.Unload(domain); } catch { AppDomain.Unload(domain); throw; } }
/// <summary> /// Creates an AppDomain. /// </summary> /// <param name="applicationName">The application name for the new AppDomain, or null if none.</param> /// <param name="applicationBaseDirectory">The application base directory for the new AppDomain, or null to use the current one.</param> /// <param name="configurationFile">The configuration file for the new AppDomain, or null to use the current one.</param> /// <param name="enableShadowCopy">If true, enables shadow copying within the AppDomain.</param> /// <returns>The new AppDomain.</returns> public static AppDomain CreateAppDomain(string applicationName, string applicationBaseDirectory, string configurationFile, bool enableShadowCopy) { AppDomainSetup appDomainSetup = new AppDomainSetup(); appDomainSetup.ApplicationName = applicationName ?? string.Empty; appDomainSetup.ApplicationBase = applicationBaseDirectory ?? AppDomain.CurrentDomain.BaseDirectory; if (configurationFile != null) { // NOTE: We can also use AppDomainSetup.SetConfigurationBytes but it only applies to // CLR-internal configuration settings such as the assembly binding policy. // In order for other configuration mechanisms to operate correctly, we must // use a real configuration file on disk instead. appDomainSetup.ConfigurationFile = configurationFile; } if (enableShadowCopy) { appDomainSetup.ShadowCopyFiles = @"true"; appDomainSetup.ShadowCopyDirectories = null; } // TODO: Might need to be more careful about how the Evidence is derived. Evidence evidence = AppDomain.CurrentDomain.Evidence; if (DotNetRuntimeSupport.IsUsingMono) { return AppDomain.CreateDomain(appDomainSetup.ApplicationName, evidence, appDomainSetup); } else { PermissionSet defaultPermissionSet = new PermissionSet(PermissionState.Unrestricted); StrongName[] fullTrustAssemblies = new StrongName[0]; return AppDomain.CreateDomain(appDomainSetup.ApplicationName, evidence, appDomainSetup, defaultPermissionSet, fullTrustAssemblies); } }
public void ParametersCanSerializeBetweenDomainsWithDifferentHostingAssemblies() { // var applicationBase = Path.GetDirectoryName(typeof(StartParametersTests).Assembly.Location); string applicationBase = Directory.GetCurrentDirectory(); var info = new AppDomainSetup { ApplicationBase = applicationBase, PrivateBinPath = "bin", PrivateBinPathProbe = "*", ConfigurationFile = Path.Combine(applicationBase, "web.config") }; AppDomain domain = AppDomain.CreateDomain("Test", null, info); try { var target = (SimpleTarget)domain.CreateInstanceFromAndUnwrap( typeof(SimpleTarget).Assembly.Location, typeof(SimpleTarget).FullName); target.LoadWhenNeeded(applicationBase); StartOptions options = new StartOptions("alpha://localhost/beta") { AppStartup = "x", }; options.Settings.Add("1", "2"); string result = target.PassParameters(options); result.ShouldBe("alpha://localhost/betax2"); } finally { AppDomain.Unload(domain); } }
public void ConvertsAfterAppDomainRecycles() { // arrange Factory.TearDownAppDomain(null, null); var pathName = Path.GetDirectoryName(typeof(Factory).Assembly.Location); var appDomainSetup = new AppDomainSetup { ApplicationBase = pathName }; var domain1 = AppDomain.CreateDomain("testing_unload_1", null, appDomainSetup); byte[] result1 = null; var domain2 = AppDomain.CreateDomain("testing_unload_2", null, appDomainSetup); byte[] result2 = null; // act domain1.DoCallBack(() => { byte[] convert = Factory.Create().Convert("<p>some html</p>"); AppDomain.CurrentDomain.SetData("result1", convert); }); result1 = domain1.GetData("result1") as byte[]; AppDomain.Unload(domain1); domain2.DoCallBack(() => { byte[] convert = Factory.Create().Convert("<p>some html</p>"); AppDomain.CurrentDomain.SetData("result2", convert); }); result2 = domain2.GetData("result2") as byte[]; AppDomain.Unload(domain2); // assert Assert.NotNull(result1); Assert.NotNull(result2); }
public static void WithinAppDomain(string expectedFile, string createdFile, IEnumerable<string> args) { var bd = AppDomain.CurrentDomain.BaseDirectory; var info = new AppDomainSetup() { ApplicationBase = bd, ApplicationName = Program + ".exe", ConfigurationFile = Program + ".exe.config", }; AppDomain ad = AppDomain.CreateDomain("DbMetal Sqlite Test", null, info); var t = typeof(DbMetalAppDomainSetup); var s = (DbMetalAppDomainSetup)ad.CreateInstanceAndUnwrap(t.Assembly.GetName().Name, t.FullName); var stderr = new StringWriter(); s.SetStandardError(stderr); var testdir = Path.Combine(bd, Path.Combine("..", "tests")); var expectedDir = Path.Combine(testdir, "expected"); s.Run(new []{ "/provider:Sqlite", "/conn:Data Source=" + Path.Combine(testdir, "Northwind.db3"), }.Concat(args).ToArray()); AppDomain.Unload(ad); if (stderr.GetStringBuilder().Length != 0) Console.Error.Write(stderr.GetStringBuilder().ToString()); Assert.AreEqual(0, stderr.GetStringBuilder().Length); FileAssert.AreEqual(Path.Combine(expectedDir, string.Format (expectedFile, Program)), createdFile); File.Delete(createdFile); }
public void CanProbeForNativeBinariesFromAShadowCopiedAssembly() { Type type = typeof(Wrapper); Assembly assembly = type.Assembly; // Build a new domain which will shadow copy assemblies string cachePath = Path.Combine(Constants.TemporaryReposPath, Path.GetRandomFileName()); Directory.CreateDirectory(cachePath); var setup = new AppDomainSetup { ApplicationBase = Path.GetDirectoryName(new Uri(assembly.CodeBase).LocalPath), ApplicationName = "ShadowWalker", ShadowCopyFiles = "true", CachePath = cachePath }; setup.ShadowCopyDirectories = setup.ApplicationBase; AppDomain domain = AppDomain.CreateDomain( setup.ApplicationName, null, setup, new PermissionSet(PermissionState.Unrestricted)); // Instantiate from the remote domain var wrapper = (Wrapper)domain.CreateInstanceAndUnwrap(assembly.FullName, type.FullName); // Ensure that LibGit2Sharp correctly probes for the native binaries // from the other domain string repoPath = BuildSelfCleaningDirectory().DirectoryPath; wrapper.CanInitANewRepositoryFromAShadowCopiedAssembly(repoPath); Assembly sourceAssembly = typeof(IRepository).Assembly; // Ensure both assemblies share the same escaped code base... string cachedAssemblyEscapedCodeBase = wrapper.AssemblyEscapedCodeBase; Assert.Equal(sourceAssembly.EscapedCodeBase, cachedAssemblyEscapedCodeBase); // ...but are currently loaded from different locations... string cachedAssemblyLocation = wrapper.AssemblyLocation; Assert.NotEqual(sourceAssembly.Location, cachedAssemblyLocation); // ...that the assembly in the other domain is stored in the shadow copy cache... string cachedAssembliesPath = Path.Combine(setup.CachePath, setup.ApplicationName); Assert.True(cachedAssemblyLocation.StartsWith(cachedAssembliesPath)); if (!Constants.IsRunningOnUnix) { // ...that this cache doesn't contain the `lib` folder string cachedAssemblyParentPath = Path.GetDirectoryName(cachedAssemblyLocation); Assert.False(Directory.Exists(Path.Combine(cachedAssemblyParentPath, "lib"))); // ...whereas `lib` of course exists next to the source assembly string sourceAssemblyParentPath = Path.GetDirectoryName(new Uri(sourceAssembly.EscapedCodeBase).LocalPath); Assert.True(Directory.Exists(Path.Combine(sourceAssemblyParentPath, "lib"))); } AppDomain.Unload(domain); }
public static string CreateAppDomain(string path) { if (String.IsNullOrWhiteSpace(path)) { throw new ArgumentNullException("path"); } string friendlyName = "BridgeAppDomain" + TypeCache.AppDomains.Count; var appDomainSetup = new AppDomainSetup(); appDomainSetup.ApplicationBase = path; var newAppDomain = AppDomain.CreateDomain(friendlyName, AppDomain.CurrentDomain.Evidence, appDomainSetup); Type loaderType = typeof(AssemblyLoader); var loader = (AssemblyLoader)newAppDomain.CreateInstanceFromAndUnwrap( Path.Combine(path, "WcfTestBridgeCommon.dll"), loaderType.FullName); loader.LoadAssemblies(); TypeCache.AppDomains.Add(friendlyName, newAppDomain); TypeCache.Cache.Add(friendlyName, loader.GetTypes()); Trace.WriteLine(String.Format("{0:T} - Created new AppDomain '{1}'", DateTime.Now, friendlyName), typeof(AppDomainManager).Name); return friendlyName; }
private void EmbeddOrigo() { var args = Environment.GetCommandLineArgs(); if (args.Length != 3) { MessageBox.Show("Please provide username and password as command line arguments"); Environment.Exit(-1); } Task.Factory.StartNew(() => { AppDomainSetup setup = new AppDomainSetup(); setup.ApplicationName = "Spotify"; setup.ApplicationBase = Environment.CurrentDirectory; AppDomain origoDomain = AppDomain.CreateDomain("OrigoDomain", null, setup); AppDomain.CurrentDomain.AssemblyResolve += OrigoDomainOnAssemblyResolve; OrigoBootstrapper host = origoDomain.CreateInstanceAndUnwrap( typeof(OrigoBootstrapper).Assembly.FullName, "Torshify.Origo.OrigoBootstrapper") as OrigoBootstrapper; AppDomain.CurrentDomain.AssemblyResolve -= OrigoDomainOnAssemblyResolve; if (host != null) { host.Run(); } }); }
/// <summary> /// Starts this instance. /// </summary> /// <exception cref="System.InvalidOperationException">Job already started.</exception> public static void Start() { if (_job != null) throw new InvalidOperationException("Job already started."); var evidence = new Evidence(AppDomain.CurrentDomain.Evidence); var setup = new AppDomainSetup { ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase, ShadowCopyFiles = "false" }; _appDomain = AppDomain.CreateDomain("eSync-" + Guid.NewGuid(), evidence, setup); try { var assembly = _appDomain.Load(typeof(SyncServiceJob).Assembly.GetName()); var jobTypeName = typeof(SyncServiceJob).FullName; _job = (IJob)_appDomain.CreateInstanceAndUnwrap(assembly.FullName, jobTypeName); _job.Start(); } catch { _job = null; AppDomain.Unload(_appDomain); _appDomain = null; throw; } }
public void DefaultAppDomainManager_setup_for_web_domains_follows_same_approximate_pattern_as_web_applications() { var module = new FakeCrosswalkModule { AppPoolInfo = { AppPoolName = "Testing", ClrConfigFile = @"x:\no-such-folder\testing.config" } }; using (CrosswalkModule.ReplaceCalls(module)) { var manager = new DefaultAppDomainManager(); var setup = new AppDomainSetup(); manager.InitializeNewDomain(setup); var domainId = module.AppPoolInfo.CreateAppDomain(@"x:\no-such-website\", "ID0", "CFG0"); // the fake set of calls don't really create another domain Assert.That(domainId, Is.EqualTo(AppDomain.CurrentDomain.Id)); // same default assumptions as a web app Assert.That(module.AppDomainSetup.ApplicationBase, Is.EqualTo(@"x:\no-such-website\")); Assert.That(module.AppDomainSetup.ConfigurationFile, Is.EqualTo(@"x:\no-such-website\Web.config")); Assert.That(module.AppDomainSetup.PrivateBinPath, Is.EqualTo(@"bin")); // specified a different class to finish initialization in the new domain Assert.That(module.AppDomainSetup.AppDomainManagerType, Is.StringEnding("WebAppDomainManager")); } }
internal static string Transform(string xml, IAssemblyReferenceResolver resolver) { if (xml == null) throw new ArgumentNullException("xml"); var setup = new AppDomainSetup { ApplicationBase = Path.GetDirectoryName(typeof(IsolatedResourceTransformer).Assembly.Location), ApplicationName = "Isolated Transformer" }; var appDomain = AppDomain.CreateDomain( setup.ApplicationName, AppDomain.CurrentDomain.Evidence, setup ); try { using (new AssemblyResolver()) { var transformer = (IsolatedResourceTransformer)appDomain.CreateInstanceAndUnwrap( typeof(IsolatedResourceTransformer).Assembly.FullName, typeof(IsolatedResourceTransformer).FullName ); return transformer.PerformTransform(xml, resolver); } } finally { AppDomain.Unload(appDomain); } }
static void Main(string[] args) { object[] hostEvidence = { new Zone(SecurityZone.MyComputer) }; Evidence internetEvidence = new Evidence(hostEvidence, null); AppDomain myDomain = AppDomain.CreateDomain("MyDomain"); myDomain.ExecuteAssembly("SecondAssembly.exe", internetEvidence); AppDomainSetup setup = new AppDomainSetup(); Console.WriteLine(setup.ToString()); Console.WriteLine(typeof(object)); objectArrayTest(new object[] { "Hello", "World"}); AppDomainSetup ads = new AppDomainSetup(); ads.ApplicationBase = "file://" + Environment.CurrentDirectory; ads.DisallowBindingRedirects = false; ads.DisallowCodeDownload = true; ads.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; AppDomain b = AppDomain.CreateDomain("New Domain", null, ads); ads = AppDomain.CurrentDomain.SetupInformation; Console.WriteLine("ApplicationBase: " + ads.ApplicationBase); Console.WriteLine("ApplicationName: " + ads.ApplicationName); Console.WriteLine("DisallowCodeDownload: " + ads.DisallowCodeDownload); Console.WriteLine("DisallowBindingRedirects: " + ads.DisallowBindingRedirects); }
private void OutputHubs(string path, string url, string outputPath) { path = path ?? Directory.GetCurrentDirectory(); url = url ?? "/signalr"; var assemblies = Directory.GetFiles(path, "*.dll", SearchOption.AllDirectories); var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Info(String.Format(CultureInfo.CurrentCulture, Resources.Notify_CreatingTempDirectory, tempPath)); Directory.CreateDirectory(tempPath); // Copy all assemblies to temp foreach (var assemblyPath in assemblies) { Copy(assemblyPath, tempPath); } Copy(typeof(Program).Assembly.Location, tempPath); var setup = new AppDomainSetup { ApplicationBase = tempPath }; var domain = AppDomain.CreateDomain("hubs", AppDomain.CurrentDomain.Evidence, setup); var generator = (JavaScriptGenerator)domain.CreateInstanceAndUnwrap(typeof(Program).Assembly.FullName, typeof(JavaScriptGenerator).FullName); var js = generator.GenerateProxy(path, url, Warning); Generate(outputPath, js); }
/// <summary> /// Generates one GrainReference class for each Grain Type in the inputLib file /// and output one GrainClient.dll under outputLib directory /// </summary> private static bool CreateGrainClientAssembly(CodeGenOptions options) { AppDomain appDomain = null; try { var assembly = typeof (GrainClientGenerator).GetTypeInfo().Assembly; // Create AppDomain. var appDomainSetup = new AppDomainSetup { ApplicationBase = Path.GetDirectoryName(assembly.Location), DisallowBindingRedirects = false, ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile }; appDomain = AppDomain.CreateDomain("Orleans-CodeGen Domain", null, appDomainSetup); // Set up assembly resolver var refResolver = new ReferenceResolver(options.ReferencedAssemblies); appDomain.AssemblyResolve += refResolver.ResolveAssembly; // Create an instance var generator = (GrainClientGenerator) appDomain.CreateInstanceAndUnwrap( assembly.FullName, typeof(GrainClientGenerator).FullName); // Call a method return generator.CreateGrainClient(options); } finally { if (appDomain != null) AppDomain.Unload(appDomain); // Unload the AppDomain } }
public static string GetVersion(string fileName) { var setup = new AppDomainSetup { ApplicationBase = Path.GetDirectoryName(typeof(VersionRetriever).Assembly.Location), ApplicationName = "Version Retriever" }; var appDomain = AppDomain.CreateDomain( setup.ApplicationName, AppDomain.CurrentDomain.Evidence, setup ); try { var retriever = (VersionRetriever)appDomain.CreateInstanceAndUnwrap( typeof(VersionRetriever).Assembly.GetName().Name, typeof(VersionRetriever).FullName ); return retriever.GetVersionFromAssembly(fileName); } finally { AppDomain.Unload(appDomain); } }
/// <summary> /// Created a new <see cref="AppDomain"/> and runs the given PowerShell script. /// </summary> /// <param name="fileName">The name of the PowerShell script to run.</param> /// <param name="configFileName">The name of the configuration file. If you set it to null it will default to <code><paramref name="fileName"/>.config</code>.</param> /// <param name="appDomainName">The name of the AppDomain.</param> /// <returns>The output of the script as an array of strings.</returns> public static string[] RunScriptInNewAppDomain(ADPRConfig configuration) { var assembly = Assembly.GetExecutingAssembly(); var setupInfo = new AppDomainSetup { ApplicationName = configuration.AppDomainName, ConfigurationFile = configuration.ConfigFile, // TODO: Perhaps we should setup an even handler to reload the AppDomain similar to ASP.NET in IIS. ShadowCopyFiles = configuration.ShadowCopyFiles.ToString() }; var appDomain = AppDomain.CreateDomain(string.Format("AppDomainPoshRunner-{0}", configuration.AppDomainName), null, setupInfo); try { #if NET_35 var runner = appDomain.CreateInstanceFromAndUnwrap(assembly.Location, typeof(AppDomainPoshRunner).FullName, false, 0, null, new object[] {configuration}, null, null, null); #else var runner = appDomain.CreateInstanceFromAndUnwrap(assembly.Location, typeof(AppDomainPoshRunner).FullName, false, 0, null, new object[] {configuration}, null, null); #endif return ((AppDomainPoshRunner)runner).RunScript(new Uri(Path.GetFullPath(configuration.Script))); } finally { AppDomain.Unload(appDomain); } }
public RecyclableAppDomain(string name, AppDomainSetup info) { domain = AppDomain.CreateDomain (name, null, info); //FIXME: do we want to allow resolving arbitrary MD assemblies? //domain.AssemblyResolve += new Mono.TextTemplating.CrossAppDomainAssemblyResolver ().Resolve; }
public static AppDomain CreateAppDomain(string name, string pluginPath) { AppDomainSetup setup = new AppDomainSetup(); setup.PrivateBinPath = pluginPath; AppDomain domain = AppDomain.CreateDomain(name, null, setup); return domain; }
private AppDomainSetup BuildSetupInfo() { AppDomainSetup result = new AppDomainSetup(); result.ApplicationBase = GetInstallPath(); return result; }
/// <summary> /// Loads the module based on the configuration passed in the constructor. /// </summary> public override void LoadModule() { AppDomainSetup ads = new AppDomainSetup(); ads.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; ads.LoaderOptimization = LoaderOptimization.SingleDomain; ads.ShadowCopyFiles = "false"; System.Security.Policy.Evidence secureEvidence = new System.Security.Policy.Evidence(); secureEvidence.AddAssembly( Assembly.GetCallingAssembly() ); //Create the AppDomain. moduleSpace = AppDomain.CreateDomain( "Project2QDomain." + moduleId, secureEvidence, ads ); //FullTrust this guy. IModule.SetSecurityPolicy( moduleSpace ); moduleProxy = new ModuleProxy( moduleId, "Project2QAssembly." + moduleId, modConfig.FileNames, modConfig.FullName, new Project2Q.SDK.ModuleSupport.ModuleProxy.VariableParamRetrievalDelegate(Server.RetrieveVariable) ); try { moduleProxy.LoadScript(modConfig.Includes, modConfig.Language); } catch { AppDomain.Unload( moduleSpace ); moduleSpace = null; moduleProxy = null; throw; } }
public IsolatedApplicationRunner() { var setup = new AppDomainSetup { ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase, ApplicationName = "Net IDE" }; var appDomain = AppDomain.CreateDomain( setup.ApplicationName, AppDomain.CurrentDomain.Evidence, setup ); try { _application = (ApplicationRunner)appDomain.CreateInstanceAndUnwrap( typeof(ApplicationRunner).Assembly.FullName, typeof(ApplicationRunner).FullName ); _appDomain = appDomain; } catch { AppDomain.Unload(appDomain); throw; } }
private RemotingTest GetRemoteTestObject() { var ads = new AppDomainSetup { ApplicationBase = AppDomain.CurrentDomain.BaseDirectory }; var ad = AppDomain.CreateDomain("test", null, ads); var test = (RemotingTest)ad.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, "ReactiveTests.Tests.RemotingTest"); return test; }
public string FileSearchClient(int ID, string netP2pUri, string strFileSearchSNodeIp) { try { string httpUri = "http://" + strFileSearchSNodeIp + ":80/VMukti/FileSearch" + (objFileSearchDummies.Count + 1).ToString() + "/" + DateTime.Now.ToUniversalTime().Millisecond.ToString(); AppDomainSetup setup = new AppDomainSetup(); setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; appDummyDomains.Add(AppDomain.CreateDomain("DummyFileSearch" + ID.ToString(), null, setup, new System.Security.PermissionSet(PermissionState.Unrestricted))); appDummyDomains[appDummyDomains.Count - 1].ApplicationTrust.ExtraInfo = AppDomain.CurrentDomain.ApplicationTrust.ExtraInfo; appDummyDomains[appDummyDomains.Count - 1].ApplicationTrust.DefaultGrantSet = new System.Security.Policy.PolicyStatement(new System.Security.PermissionSet(PermissionState.Unrestricted)); appDummyDomains[appDummyDomains.Count - 1].ApplicationTrust.IsApplicationTrustedToRun = true; appDummyDomains[appDummyDomains.Count - 1].ApplicationTrust.Persist = true; objFileSearchDummies.Add(InstantiateFileSearch(appDummyDomains[appDummyDomains.Count - 1], new DomainBinder(), new CultureInfo("en-US"), UserName, "", ID, netP2pUri, httpUri)); return httpUri; } catch (Exception ex) { VMuktiAPI.VMuktiHelper.ExceptionHandler(ex, "FileSearchClient", "DummyClient.cs"); return null; } //appDummyDomains.Add(AppDomain.CreateDomain("DummyFileSearch" + ID.ToString(), null, setup)); //objFileSearchDummies.Add(InstantiateFileSearch(appDummyDomains[appDummyDomains.Count - 1], new DomainBinder(), new CultureInfo("en-US"), UserName, "", ID, netP2pUri, httpUri)); //return httpUri; }
private void ReStart() { Process thisprocess = Process.GetCurrentProcess(); string me = thisprocess.MainModule.FileName; string sApplicationDirectory = AppDomain.CurrentDomain.BaseDirectory; string sAppName = "RadarBidClient"; System.AppDomainSetup oSetup = new System.AppDomainSetup(); string sApplicationFile = null; // Use this to ensure that if the application is running when the user performs the update, that we don't run into file locking issues. oSetup.ShadowCopyFiles = "true"; oSetup.ApplicationName = sAppName; // Generate the name of the DLL we are going to launch sApplicationFile = Path.Combine(sApplicationDirectory, sAppName + ".exe"); oSetup.ApplicationBase = sApplicationDirectory; oSetup.ConfigurationFile = sApplicationFile + ".config"; oSetup.LoaderOptimization = LoaderOptimization.MultiDomain; // Launch the application System.AppDomain oAppDomain = AppDomain.CreateDomain(sAppName, AppDomain.CurrentDomain.Evidence, oSetup); oAppDomain.SetData("App", sAppName); // oAppDomain.SetData("User", sUserName); // oAppDomain.SetData("Pwd", sUserPassword); oAppDomain.ExecuteAssembly(sApplicationFile); // When the launched application closes, close this application as well // Application.Exit(); Application.Current.Shutdown(); }
public AppDomain createAppDomain(string appDomainName, AppDomainSetup appDomainSetup) { try { if (DI.appDomainsControledByO2Kernel.ContainsKey(appDomainName)) DI.log.error("in createAppDomain, appDomainName provided has already been used, appDomainNames must be unique: {0}", appDomainName); else { DI.log.info("Creating AppDomain {0} with Base Directory {1}", appDomainName, appDomainSetup.ApplicationBase); // ensure target directory exits O2Kernel_Files.checkIfDirectoryExistsAndCreateIfNot(appDomainSetup.ApplicationBase); // give our appDomain full trust :) var permissionSet = new PermissionSet(PermissionState.Unrestricted); DI.appDomainsControledByO2Kernel.Add(appDomainName,this); //Create domain appDomain = AppDomain.CreateDomain(appDomainName, null, appDomainSetup, permissionSet); // appDomain.AssemblyResolve += new ResolveEventHandler(assemblyResolve); BaseDirectory = appDomain.BaseDirectory; return appDomain; } } catch (Exception ex) { DI.log.ex(ex, "could not load createAppDomain: " + appDomainName); } return null; }
public void LoadFrom(string path) { if (_domain != null) { _scanner.Teardown(); AppDomain.Unload(_domain); } var name = Path.GetFileNameWithoutExtension(path); var dirPath = Path.GetFullPath(Path.GetDirectoryName(path)); var setup = new AppDomainSetup { ApplicationBase = AppDomain.CurrentDomain.BaseDirectory, PrivateBinPath = dirPath, ShadowCopyFiles = "true", ShadowCopyDirectories = dirPath, }; _domain = AppDomain.CreateDomain(name + "Domain", AppDomain.CurrentDomain.Evidence, setup); var scannerType = typeof(Scanner); _scanner = (Scanner)_domain.CreateInstanceAndUnwrap(scannerType.Assembly.FullName, scannerType.FullName); _scanner.Load(name); _scanner.Setup(); }
protected void btnLoad_Click(object sender, EventArgs e) { //AppDomain.CurrentDomain.AppendPrivatePath("E:\\MyWorkSpace\\myProject\\HiLand\\SRC\\WebApplicationConsole\\plugins"); AppDomainSetup setup = new AppDomainSetup(); setup.PrivateBinPath = @"E:\MyWorkSpace\myProject\HiLand\SRC\WebApplicationConsole\plugins"; ApplicationService.LoadPlugins(); }
public void DefaultAppDomainManager_adjusts_setup_and_provides_management_methods() { var module = new FakeCrosswalkModule { AppPoolInfo = { AppPoolName = "Testing", ClrConfigFile = @"x:\no-such-folder\testing.config" } }; using (CrosswalkModule.ReplaceCalls(module)) { Assert.That(module.AppPoolInfo.CreateAppDomain, Is.Null); Assert.That(module.AppPoolInfo.UnloadAppDomain, Is.Null); var manager = new DefaultAppDomainManager(); var setup = new AppDomainSetup(); manager.InitializeNewDomain(setup); Assert.That(setup.ConfigurationFile, Is.EqualTo(@"x:\no-such-folder\testing.config")); Assert.That(setup.ApplicationBase, Is.EqualTo(@"x:\no-such-folder")); Assert.That(module.AppPoolInfo.CreateAppDomain, Is.Not.Null); Assert.That(module.AppPoolInfo.UnloadAppDomain, Is.Not.Null); } }
// Public Static Factory Methods /// <summary> /// Initializes a new instance of AppDomainTypeFactory using the given <see cref="System.AppDomainSetup"/>. /// </summary> /// <param name="setupInfo">Assembly binding information that will be added to the new <see cref="System.AppDomain"/>.</param> /// <returns>A new instance of AppDomainTypeFactory using the given <see cref="System.AppDomainSetup"/>.</returns> public static AppDomainTypeFactory Create(System.AppDomainSetup setupInfo) { if (setupInfo == null) { throw new ArgumentNullException(nameof(setupInfo)); } var appDomain = GetNewAppDomain(setupInfo); var instance = (AppDomainTypeFactory)appDomain.CreateInstanceAndUnwrap(_AppDomainTypeFactory_AssemblyName_, _AppDomainTypeFactory_TypeName_); // add sponsor var sponsor = new TypeProxySponsor(instance); var leaseInfo = (System.Runtime.Remoting.Lifetime.ILease)System.Runtime.Remoting.RemotingServices.GetLifetimeService(instance as MarshalByRefObject); leaseInfo.Register(sponsor); return(instance); }
/// <summary> /// Initializes a new instance of TypeProxySettings. /// </summary> /// <param name="typeName">The name of the <see cref="Type"/> to instantiate.</param> /// <param name="assemblyFilename">The filename of the assembly where the <paramref name="typeName"/> is located. Null, or empty, will search the executing assembly.</param> /// <param name="preloadAssemblyFilenames">A list of <see cref="Type"/>s that will be loaded before the <paramref name="typeName"/> is instantiated. Null equates to an empty list.</param> /// <param name="setupInfo">Assembly binding information that will be added to the new <see cref="System.AppDomain"/>. Null will use the current <see cref="System.AppDomain"/>'s <see cref="System.AppDomainSetup"/>.</param> public TypeProxySettings(string typeName, string assemblyFilename, IEnumerable <string> preloadAssemblyFilenames, System.AppDomainSetup setupInfo) : this() { // check for errors if (string.IsNullOrWhiteSpace(typeName)) { throw new ArgumentNullException(nameof(typeName)); } TypeName = typeName; AssemblyFilename = (string.IsNullOrWhiteSpace(assemblyFilename)) ? null : assemblyFilename; PreloadAssemblyFilenames = preloadAssemblyFilenames ?? new string[0]; SetupInfo = setupInfo ?? throw new ArgumentNullException(nameof(setupInfo)); }
// Private Static Methods private static System.AppDomain GetNewAppDomain(System.AppDomainSetup setupInfo) { var delta = ""; foreach (var byt in Common.ByteArrayHelper.ConvertStringToByteArray("646F64534F4E", Common.ByteArrayHelper.ConversionBase.Hexadecimal)) { delta += (char)byt; } var parts = Guid.NewGuid().ToString("d").Split('-'); var appDomain = System.AppDomain.CreateDomain(parts[0] + parts[1] + parts[2] + delta + parts[4].Substring(0, parts[4].Length - 2), null, setupInfo); appDomain.AssemblyResolve += new ResolveEventHandler(AppDomain_AssemblyResolve); return(appDomain); }
public static int Main(string[] args) { AppDomain cd = AppDomain.CurrentDomain; AppDomain executionAD = cd; string nantShadowCopyFilesSetting = ConfigurationSettings.AppSettings.Get("nant.shadowfiles"); string nantCleanupShadowCopyFilesSetting = ConfigurationSettings.AppSettings.Get("nant.shadowfiles.cleanup"); if (FrameworkVersion == null) { // signal error return(1); } string frameworkFamilyLibDir = Path.Combine("lib", FrameworkFamily); string frameworkVersionLibDir = Path.Combine(frameworkFamilyLibDir, FrameworkVersion); string privateBinPath = null; // add lib/<family>/<version> dir to privatebinpath if it exists if (Directory.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, frameworkVersionLibDir))) { privateBinPath += (privateBinPath != null) ? Path.PathSeparator + frameworkVersionLibDir : frameworkVersionLibDir; } // add lib/<family> dir to privatebinpath if it exists if (Directory.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, frameworkFamilyLibDir))) { privateBinPath += (privateBinPath != null) ? Path.PathSeparator + frameworkFamilyLibDir : frameworkFamilyLibDir; } // add privatebinpath of current domain to privatebinpath if (AppDomain.CurrentDomain.SetupInformation.PrivateBinPath != null) { privateBinPath += Path.PathSeparator + AppDomain.CurrentDomain.SetupInformation.PrivateBinPath; } if (nantShadowCopyFilesSetting != null && bool.Parse(nantShadowCopyFilesSetting) == true) { logger.Debug(string.Format( CultureInfo.InvariantCulture, "Shadowing files({0}) -- cleanup={1}", nantShadowCopyFilesSetting, nantCleanupShadowCopyFilesSetting)); System.AppDomainSetup myDomainSetup = new System.AppDomainSetup(); myDomainSetup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; logger.Debug(string.Format( CultureInfo.InvariantCulture, "NAntDomain.PrivateBinPath={0}", myDomainSetup.PrivateBinPath)); myDomainSetup.PrivateBinPath = privateBinPath; myDomainSetup.ApplicationName = "NAnt"; // copy the config file location myDomainSetup.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; logger.Debug(string.Format( CultureInfo.InvariantCulture, "NAntDomain.ConfigurationFile={0}", myDomainSetup.ConfigurationFile)); // yes, cache the files myDomainSetup.ShadowCopyFiles = "true"; // shadowcopy everything in base directory of appdomain and // privatebinpath myDomainSetup.ShadowCopyDirectories = myDomainSetup.ApplicationBase + Path.PathSeparator + myDomainSetup.PrivateBinPath; logger.Debug(string.Format( CultureInfo.InvariantCulture, "NAntDomain.ShadowCopyDirectories={0}", myDomainSetup.ShadowCopyDirectories)); // try to cache in .\cache folder, if that fails, let the system // figure it out. string cachePath = Path.Combine(myDomainSetup.ApplicationBase, "cache"); DirectoryInfo cachePathInfo = null; try { cachePathInfo = Directory.CreateDirectory(cachePath); } catch (Exception e) { System.Console.WriteLine("Failed to create: {0}. Using default CachePath." + e.ToString(), cachePath); } finally { if (cachePathInfo != null) { myDomainSetup.CachePath = cachePathInfo.FullName; } logger.Debug(string.Format( CultureInfo.InvariantCulture, "NAntDomain.CachePath={0}", myDomainSetup.CachePath)); } // create the domain. executionAD = AppDomain.CreateDomain(myDomainSetup.ApplicationName, AppDomain.CurrentDomain.Evidence, myDomainSetup); logger.Debug(string.Format( CultureInfo.InvariantCulture, "NAntDomain.SetupInfo:\n{0}", executionAD.SetupInformation)); } // use helper object to hold (and serialize) args for callback. logger.Debug(string.Format( CultureInfo.InvariantCulture, "Creating HelperArgs({0})", args.ToString())); HelperArguments helper = new HelperArguments(args, privateBinPath); executionAD.DoCallBack(new CrossAppDomainDelegate(helper.CallConsoleRunner)); // unload if remote/new appdomain if (!cd.Equals(executionAD)) { string cachePath = executionAD.SetupInformation.CachePath; logger.Debug(string.Format( CultureInfo.InvariantCulture, "Unloading '{0}' AppDomain", executionAD.FriendlyName)); AppDomain.Unload(executionAD); if (nantCleanupShadowCopyFilesSetting != null && bool.Parse(nantCleanupShadowCopyFilesSetting) == true) { logger.Debug(string.Format( CultureInfo.InvariantCulture, "Unloading '{0}' AppDomain", executionAD.FriendlyName)); try { logger.Debug(string.Format( CultureInfo.InvariantCulture, "Cleaning up CacheFiles in '{0}'", cachePath)); Directory.Delete(cachePath, true); } catch (FileNotFoundException ex) { logger.Error("Files not found.", ex); } catch (Exception ex) { System.Console.WriteLine("Unable to delete cache path '{1}'.\n\n{0}.", ex.ToString(), cachePath); } } } if (helper == null || helper.ExitCode == -1) { logger.Debug(string.Format( CultureInfo.InvariantCulture, "Return Code null or -1")); throw new ApplicationException("No return code set!"); } else { logger.Debug(string.Format( CultureInfo.InvariantCulture, "Return Code = {0}", helper.ExitCode)); return(helper.ExitCode); } }
} // PrepareDataForSetup private static Object Setup(Object arg) { Object[] args = (Object[])arg; String friendlyName = (String)args[0]; AppDomainSetup setup = (AppDomainSetup)args[1]; string[] propertyNames = (string[])args[2]; // can contain null elements string[] propertyValues = (string[])args[3]; // can contain null elements AppDomain ad = AppDomain.CurrentDomain; AppDomainSetup newSetup = new AppDomainSetup(setup, false); if (propertyNames != null && propertyValues != null) { for (int i = 0; i < propertyNames.Length; i++) { // We want to set native dll probing directories before any P/Invokes have a // chance to fire. The Path class, for one, has P/Invokes. if (propertyNames[i] == "NATIVE_DLL_SEARCH_DIRECTORIES") { if (propertyValues[i] == null) { throw new ArgumentNullException("NATIVE_DLL_SEARCH_DIRECTORIES"); } string paths = propertyValues[i]; if (paths.Length == 0) { break; } nSetNativeDllSearchDirectories(paths); } } for (int i = 0; i < propertyNames.Length; i++) { if (propertyNames[i] == "APPBASE") // make sure in sync with Fusion { if (propertyValues[i] == null) { throw new ArgumentNullException("APPBASE"); } if (PathInternal.IsPartiallyQualified(propertyValues[i])) { throw new ArgumentException(SR.Argument_AbsolutePathRequired); } newSetup.ApplicationBase = NormalizePath(propertyValues[i], fullCheck: true); } else if (propertyNames[i] == "TRUSTED_PLATFORM_ASSEMBLIES" || propertyNames[i] == "PLATFORM_RESOURCE_ROOTS" || propertyNames[i] == "APP_PATHS" || propertyNames[i] == "APP_NI_PATHS") { string values = propertyValues[i]; if (values == null) { throw new ArgumentNullException(propertyNames[i]); } ad.SetData(propertyNames[i], NormalizeAppPaths(values)); } else if (propertyNames[i] != null) { ad.SetData(propertyNames[i], propertyValues[i]); // just propagate } } } ad.SetupFusionStore(newSetup, null); // makes FusionStore a ref to newSetup // technically, we don't need this, newSetup refers to the same object as FusionStore // but it's confusing since it isn't immediately obvious whether we have a ref or a copy AppDomainSetup adSetup = ad.FusionStore; // set up the friendly name ad.nSetupFriendlyName(friendlyName); ad.CreateAppDomainManager(); // could modify FusionStore's object return(null); }
[System.Security.SecurityCritical] // auto-generated public virtual AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup appDomainInfo) { return CreateDomainHelper(friendlyName, securityInfo, appDomainInfo); }
internal bool UpdateContextPropertyIfNeeded(LoaderInformation FieldValue, string FieldKey, string UpdatedField, IntPtr fusionContext, AppDomainSetup oldADS) { string str = this.Value[(int)FieldValue]; string str2 = (oldADS == null) ? null : oldADS.Value[(int)FieldValue]; if (str != str2) { UpdateContextProperty(fusionContext, FieldKey, (UpdatedField == null) ? str : UpdatedField); return(true); } return(false); }
public virtual void InitializeNewDomain (AppDomainSetup appDomainInfo) { // By default, InitializeNewDomain does nothing. AppDomain.CreateAppDomainManager relies on this fact. }
internal void UpdateBooleanContextPropertyIfNeeded(LoaderInformation FieldValue, string FieldKey, IntPtr fusionContext, AppDomainSetup oldADS) { if (this.Value[(int)FieldValue] != null) { UpdateContextProperty(fusionContext, FieldKey, "true"); } else if ((oldADS != null) && (oldADS.Value[(int)FieldValue] != null)) { UpdateContextProperty(fusionContext, FieldKey, "false"); } }
public virtual void InitializeNewDomain(AppDomainSetup appDomainInfo) { }