public IEnumerable<ExpressionResult> ExecuteSpecifications(string path, string example = null) { var name = Guid.NewGuid().ToString(); var domainSetup = new AppDomainSetup { ApplicationName = name, ApplicationBase = Path.GetDirectoryName(path), ConfigurationFile = string.Concat(Path.GetFileName(path), ".config") }; var domain = AppDomain.CreateDomain(name, null, domainSetup); try { var assembly = (SpecificationAssembly)domain.CreateInstanceAndUnwrap( typeof(SpecificationAssembly).Assembly.FullName, typeof(SpecificationAssembly).FullName, false, BindingFlags.Default, null, new object[] { runner }, CultureInfo.CurrentCulture, null); return assembly.ExecuteSpecifications(path, example); } 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 static void RunInSeparateAppDomain(AppDomainSetup setup, Action action) { var dir = Path.GetDirectoryName(typeof(AppDomainUtils).Assembly.CodeBase).Replace("file:\\", ""); setup.PrivateBinPath = dir; setup.ApplicationBase = dir; setup.ApplicationName = Guid.NewGuid().ToString(); setup.ShadowCopyFiles = "true"; setup.ShadowCopyDirectories = setup.ApplicationBase; setup.CachePath = Path.Combine(Path.GetTempPath(), setup.ApplicationName); AppDomain appDomain = null; try { appDomain = AppDomain.CreateDomain(setup.ApplicationName, null, setup); AppDomainHelper helper = appDomain.CreateInstanceAndUnwrap(typeof(AppDomainUtils).Assembly.FullName, typeof(AppDomainHelper).FullName) as AppDomainHelper; helper.Run(action); } finally { if (appDomain != null) { AppDomain.Unload(appDomain); } } }
static void Main(String[] args) { if (args.Length < 2) { Console.WriteLine("Usage: sandbox <directory> <assembly> [allowed_files ...]"); return; } AppDomainSetup adSetup = new AppDomainSetup(); adSetup.ApplicationBase = Path.GetFullPath(args[0]); PermissionSet permSet = new PermissionSet(PermissionState.None); permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution)); permSet.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess)); permSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, Path.GetFullPath(args[1]))); for (int i = 2; i < args.Length; ++i) permSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, args[i])); StrongName fullTrustAssembly = typeof(Sandboxer).Assembly.Evidence.GetHostEvidence<StrongName>(); AppDomain newDomain = AppDomain.CreateDomain("Sandbox", null, adSetup, permSet, fullTrustAssembly); ObjectHandle handle = Activator.CreateInstanceFrom( newDomain, typeof(Sandboxer).Assembly.ManifestModule.FullyQualifiedName, typeof(Sandboxer).FullName ); Sandboxer newDomainInstance = (Sandboxer) handle.Unwrap(); Environment.Exit(newDomainInstance.ExecuteUntrustedCode(Path.GetFullPath(args[1]))); }
void ExecuteInOwnAppDomain() { if (WeaversHistory.HasChanged(Weavers.Select(x => x.AssemblyPath)) || appDomain == null) { if (appDomain != null) { AppDomain.Unload(appDomain); } var appDomainSetup = new AppDomainSetup { ApplicationBase = AssemblyLocation.CurrentDirectory(), }; appDomain = AppDomain.CreateDomain("Fody", null, appDomainSetup); } var innerWeaver = (IInnerWeaver) appDomain.CreateInstanceAndUnwrap("FodyIsolated", "InnerWeaver"); innerWeaver.AssemblyPath = AssemblyPath; innerWeaver.References = References; innerWeaver.KeyFilePath = KeyFilePath; innerWeaver.Logger = Logger; innerWeaver.AssemblyPath = AssemblyPath; innerWeaver.Weavers = Weavers; innerWeaver.IntermediateDir = IntermediateDir; innerWeaver.Execute(); }
static void Main () { AppDomainSetup setup = new AppDomainSetup (); setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; setup.ApplicationName = "test"; AppDomain newDomain = AppDomain.CreateDomain ("test", AppDomain.CurrentDomain.Evidence, setup); StringCollection probePaths = new StringCollection (); probePaths.Add (Path.Combine (AppDomain.CurrentDomain.BaseDirectory, "lib")); // create an instance of our custom Assembly Resolver in the target domain. newDomain.CreateInstanceFrom (Assembly.GetExecutingAssembly ().CodeBase, typeof (AssemblyResolveHandler).FullName, false, BindingFlags.Public | BindingFlags.Instance, null, new object[] { probePaths }, CultureInfo.InvariantCulture, null, AppDomain.CurrentDomain.Evidence); Helper helper = new Helper (); newDomain.DoCallBack (new CrossAppDomainDelegate (helper.Test)); }
protected static ObjectHandle CreateInstanceHelper (AppDomainSetup adSetup) { if (adSetup == null) throw new ArgumentNullException ("adSetup"); if (adSetup.ActivationArguments == null) { string msg = Locale.GetText ("{0} is missing it's {1} property"); throw new ArgumentException (String.Format (msg, "AppDomainSetup", "ActivationArguments"), "adSetup"); } HostSecurityManager hsm = null; if (AppDomain.CurrentDomain.DomainManager != null) hsm = AppDomain.CurrentDomain.DomainManager.HostSecurityManager; else hsm = new HostSecurityManager (); // default Evidence applicationEvidence = new Evidence (); applicationEvidence.AddHost (adSetup.ActivationArguments); TrustManagerContext context = new TrustManagerContext (); ApplicationTrust trust = hsm.DetermineApplicationTrust (applicationEvidence, null, context); if (!trust.IsApplicationTrustedToRun) { string msg = Locale.GetText ("Current policy doesn't allow execution of addin."); throw new PolicyException (msg); } // FIXME: we're missing the information from the manifest AppDomain ad = AppDomain.CreateDomain ("friendlyName", null, adSetup); return ad.CreateInstance ("assemblyName", "typeName", null); }
static int Main () { AppDomainSetup setup = new AppDomainSetup(); setup.ConfigurationFile = "application.configfile"; AppDomain domain = AppDomain.CreateDomain("ConfigurationFileDomain", null, setup); CrossDomainTester cdt = CreateCrossDomainTester (domain); return cdt.Run (); }
AppDomain CreateDomain() { Logger.LogDebug("Creating a new AppDomain"); var appDomainSetup = new AppDomainSetup { ApplicationBase = AssemblyLocation.CurrentDirectory, }; return AppDomain.CreateDomain($"Fody Domain for '{SolutionDirectory}'", null, appDomainSetup); }
AppDomain CreateDomain() { Logger.LogInfo("Creating a new AppDomian"); var appDomainSetup = new AppDomainSetup { ApplicationBase = AssemblyLocation.CurrentDirectory(), }; return AppDomain.CreateDomain(string.Format("Fody Domain for '{0}'", SolutionDirectoryPath), null, appDomainSetup); }
public override void InitializeNewDomain(AppDomainSetup appDomainInfo) { _info.Main = Main; BindApplicationMain(ref _info); if (!string.IsNullOrEmpty(_info.ApplicationBase)) { appDomainInfo.ApplicationBase = _info.ApplicationBase; } }
static ContainsTypeChecker() { var appDomainSetup = new AppDomainSetup { ApplicationBase = AssemblyLocation.CurrentDirectory(), }; var appDomain = AppDomain.CreateDomain("Fody.ContainsTypeChecker", null, appDomainSetup); var instanceAndUnwrap = appDomain.CreateInstanceAndUnwrap("FodyIsolated", "IsolatedContainsTypeChecker"); containsTypeChecker = (IContainsTypeChecker)instanceAndUnwrap; }
static ContainsTypeChecker() { var appDomainSetup = new AppDomainSetup { ApplicationBase = AssemblyLocation.CurrentDirectory, }; var appDomain = AppDomain.CreateDomain("Fody.ContainsTypeChecker", null, appDomainSetup); var assemblyFile = Path.Combine(AssemblyLocation.CurrentDirectory, "FodyIsolated.dll"); var instanceAndUnwrap = appDomain.CreateInstanceFromAndUnwrap(assemblyFile, "IsolatedContainsTypeChecker"); containsTypeChecker = (IContainsTypeChecker)instanceAndUnwrap; }
public static int Main () { var setup = new AppDomainSetup(); setup.ApplicationBase = System.Environment.CurrentDirectory; AppDomain d = AppDomain.CreateDomain ("foo", AppDomain.CurrentDomain.Evidence, setup); Test t = (Test) d.CreateInstanceAndUnwrap (Assembly.GetExecutingAssembly().FullName, typeof (Test).FullName); t.Stamp = new DateTime (1968, 1, 3); Console.WriteLine (t.Stamp); return 0; }
public static void Main() { // Get and display the friendly name of the default AppDomain. Console.WriteLine("Get and display the friendly name of the default AppDomain:"); string callingDomainName = Thread.GetDomain().FriendlyName; Console.WriteLine(callingDomainName); // Get and display the full name of the EXE assembly. Console.WriteLine("Get and display the full name of the EXE assembly:"); string exeAssembly = Assembly.GetEntryAssembly().FullName; Console.WriteLine(exeAssembly); // Construct and initialize settings for a second AppDomain. AppDomainSetup ads = new AppDomainSetup(); ads.ApplicationBase = System.Environment.CurrentDirectory; ads.DisallowBindingRedirects = false; ads.DisallowCodeDownload = true; ads.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; // Create the second AppDomain. AppDomain ad2 = AppDomain.CreateDomain("AD #2", null, ads); // Create an instance of MarshalbyRefType in the second AppDomain. // A proxy to the object is returned. MarshalByRefType mbrt = (MarshalByRefType)ad2.CreateInstanceAndUnwrap( exeAssembly, typeof(MarshalByRefType).FullName ); // Call a method on the object via the proxy, passing the // default AppDomain's friendly name in as a parameter. mbrt.SomeMethod(callingDomainName); // Unload the second AppDomain. This deletes its object and // invalidates the proxy object. AppDomain.Unload(ad2); try { // Call the method again. Note that this time it fails // because the second AppDomain was unloaded. mbrt.SomeMethod(callingDomainName); Console.WriteLine("Sucessful call."); } catch (AppDomainUnloadedException) { Console.WriteLine("Failed call; this is expected."); } Console.ReadKey(); }
public static ShadowCopyTester GetRemote (string base_dir, string cache_dir) { AppDomainSetup setup = new AppDomainSetup (); setup.ApplicationBase = base_dir; setup.CachePath = cache_dir; setup.ShadowCopyFiles = "true"; setup.ApplicationName = "ShadowCopyTest"; AppDomain domain = AppDomain.CreateDomain ("shadow", null, setup); return (ShadowCopyTester) domain.CreateInstanceFromAndUnwrap ( typeof (ShadowCopyTester).Assembly.Location, typeof (ShadowCopyTester).FullName); }
/// Run the code with less permissions than usual /// (so it can't read/write to files). /// This is a false sense of security... the program can still run unmanaged /// code. But shhh don't worry about that. static int Main(string[] args) { String path = args[0]; PermissionSet ps = new PermissionSet(PermissionState.None); AppDomainSetup setup = new AppDomainSetup(); Evidence ev = new Evidence(); AppDomain sandbox = AppDomain.CreateDomain("Sandbox", ev, setup, ps); sandbox.ExecuteAssembly(path); return 0; }
public virtual ObjectHandle CreateInstance (ActivationContext activationContext, string[] activationCustomData) { if (activationContext == null) throw new ArgumentNullException ("activationContext"); // TODO : compare activationContext with the one from this domain // and use it if it match // TODO : we must pass the activationCustomData in the AppDomainSetup // even if the activationCustomData don't match ??? AppDomainSetup setup = new AppDomainSetup (activationContext); return CreateInstanceHelper (setup); }
public override void InitializeNewDomain(AppDomainSetup appDomainInfo) { // Do nothing if this isn't the default app domain if (!AppDomain.CurrentDomain.IsDefaultAppDomain()) { return; } _info.Main = Main; BindApplicationMain(ref _info); appDomainInfo.ApplicationBase = _info.RuntimeDirectory; appDomainInfo.TargetFrameworkName = DetermineAppDomainTargetFramework(_info.Framework); appDomainInfo.ConfigurationFile = Path.Combine(_info.ApplicationBase, Constants.AppConfigurationFileName); }
public static void Main () { AppDomainSetup setup = new AppDomainSetup (); setup.PrivateBinPath = "ab"; AppDomain domain = AppDomain.CreateDomain ("test", AppDomain.CurrentDomain.Evidence, setup); Helper helper = (Helper) domain.CreateInstanceAndUnwrap ( typeof (EntryPoint).Assembly.FullName, typeof (Helper).FullName, false, BindingFlags.Public | BindingFlags.Instance, null, new object [0], CultureInfo.InvariantCulture, new object [0], AppDomain.CurrentDomain.Evidence); helper.Test (); }
static int Main() { int res; AppDomainSetup setup = new AppDomainSetup (); setup.ApplicationBase = "."; Console.WriteLine (AppDomain.CurrentDomain.FriendlyName); AppDomain newDomain = AppDomain.CreateDomain ("NewDomain", null, setup); string[] args = { "1", "2", "3"}; res = newDomain.ExecuteAssembly ("appdomain-client.exe", null, args); if (res != arg_sum (args)) return 1; Console.WriteLine ("test-ok"); return 0; }
public void Do () { AppDomainSetup setup = new AppDomainSetup (); setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; setup.ApplicationName = "test bug"; AppDomain newDomain = AppDomain.CreateDomain ( setup.ApplicationName, AppDomain.CurrentDomain.Evidence, setup); CrossDomainTesterB testerB = (CrossDomainTesterB) newDomain.CreateInstanceAndUnwrap (typeof (CrossDomainTesterB).Assembly.FullName, typeof (CrossDomainTesterB).FullName, false, BindingFlags.Public | BindingFlags.Instance, null, new object [] { new StringCollection () }, CultureInfo.InvariantCulture, new object [0], AppDomain.CurrentDomain.Evidence); testerB.GetTypedValue (new StringCollection (), new StringCollection (), null, null); }
public override void InitializeNewDomain(AppDomainSetup appDomainInfo) { // Do nothing if this isn't the default app domain if (!AppDomain.CurrentDomain.IsDefaultAppDomain()) { return; } _info.Main = Main; BindApplicationMain(ref _info); if (!string.IsNullOrEmpty(_info.ApplicationBase)) { Environment.SetEnvironmentVariable(EnvironmentNames.AppBase, _info.ApplicationBase); } appDomainInfo.ApplicationBase = Environment.GetEnvironmentVariable(EnvironmentNames.DefaultLib); appDomainInfo.TargetFrameworkName = ".NETFramework,Version=v4.5.1"; }
public override void InitializeNewDomain(AppDomainSetup appDomainInfo) { // Do nothing if this isn't the default app domain if (!AppDomain.CurrentDomain.IsDefaultAppDomain()) { return; } _info.Main = Main; BindApplicationMain(ref _info); if (!string.IsNullOrEmpty(_info.ApplicationBase)) { Environment.SetEnvironmentVariable(EnvironmentNames.AppBase, _info.ApplicationBase); } appDomainInfo.ApplicationBase = Environment.GetEnvironmentVariable(EnvironmentNames.DefaultLib); appDomainInfo.TargetFrameworkName = DetermineAppDomainTargetFramework(); appDomainInfo.ConfigurationFile = Path.Combine(_info.ApplicationBase, Constants.AppConfigurationFileName); }
void IConfigManager.Load(string path) { try { AppDomain current = AppDomain.CurrentDomain; string name = Path.GetFileNameWithoutExtension(path); AppDomainSetup info = new AppDomainSetup(); info.ApplicationBase = current.BaseDirectory; info.ApplicationName = name; info.DynamicBase = serverPath; info.CachePath = serverPath; info.ShadowCopyFiles = "true"; Evidence securityInfo = new Evidence(current.Evidence); var app = AppDomain.CreateDomain(name, securityInfo, info); if (app != null) { lock (domains) { AppDomain old; if (domains.TryGetValue(path, out old)) { if (domains.Remove(path)) { AppDomain.Unload(old); LogWrapper.Warn("Load.UnloadSuccess:" + path); } } domains.Add(path, app); string exeFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "FrontServer.exe"); app.ExecuteAssembly(exeFile, new string[] { path }); } LogWrapper.Warn("Load.LoadSuccess:" + path); } } catch (System.Exception ex) { LogWrapper.Error("Load.LoadFail", ex); } }
static int Main () { string dir = AppDomain.CurrentDomain.BaseDirectory; if (dir.EndsWith (Path.DirectorySeparatorChar.ToString ())) dir = dir.Substring (0, dir.Length - 1); Assert.AreEqual (dir, Application.StartupPath, "#A1"); Assert.AreEqual (Path.Combine (dir, "apptest.exe"), Application.ExecutablePath, "#A2"); AppDomainSetup domainsetup = new AppDomainSetup (); domainsetup.ShadowCopyFiles = "true"; AppDomain plugindomain = AppDomain.CreateDomain ("BugTest", null, domainsetup); RemotingObject assldr = (RemotingObject) plugindomain.CreateInstanceAndUnwrap ( typeof (RemotingObject).Assembly.FullName, typeof (RemotingObject).FullName); Assert.AreEqual (dir, assldr.StartupPath, "#B1"); Assert.AreEqual (Path.Combine (dir, "apptest.exe"), assldr.ExecutablePath, "#B2"); return 0; }
public ToolingFacade( string migrationsAssemblyName, string contextAssemblyName, string configurationTypeName, string workingDirectory, string configurationFilePath, string dataDirectory, DbConnectionInfo connectionStringInfo) { Check.NotEmpty(migrationsAssemblyName, "migrationsAssemblyName"); _migrationsAssemblyName = migrationsAssemblyName; _contextAssemblyName = contextAssemblyName; _configurationTypeName = configurationTypeName; _connectionStringInfo = connectionStringInfo; var info = new AppDomainSetup { ShadowCopyFiles = "true" }; if (!string.IsNullOrWhiteSpace(workingDirectory)) { info.ApplicationBase = workingDirectory; } _configurationFile = new ConfigurationFileUpdater().Update(configurationFilePath); info.ConfigurationFile = _configurationFile; var friendlyName = "MigrationsToolingFacade" + Convert.ToBase64String(Guid.NewGuid().ToByteArray()); _appDomain = AppDomain.CreateDomain(friendlyName, null, info); if (!string.IsNullOrWhiteSpace(dataDirectory)) { _appDomain.SetData("DataDirectory", dataDirectory); } }
static void Main () { string basedir = AppDomain.CurrentDomain.BaseDirectory; Assert.IsNotNull (basedir, "#1"); int len = basedir.Length; Assert.IsTrue (len > 0, "#2"); Assert.AreEqual (Path.DirectorySeparatorChar, basedir [len -1], "#3"); string subdir = Path.Combine (basedir, "sub"); File.Copy (Path.Combine (basedir, "remote.dll"), Path.Combine (subdir, "remote.dll"), true); AppDomainSetup setup = new AppDomainSetup (); setup.ApplicationBase = subdir; AppDomain domain; domain = AppDomain.CreateDomain ("test", AppDomain.CurrentDomain.Evidence, setup); try { RemoteTester remote = (RemoteTester) domain.CreateInstanceAndUnwrap ( typeof (RemoteTester).Assembly.FullName, typeof (RemoteTester).FullName); Assert.AreEqual (subdir, remote.GetBaseDirectory (), "#4"); } finally { AppDomain.Unload (domain); } domain = AppDomain.CreateDomain ("test", AppDomain.CurrentDomain.Evidence, null); try { RemoteTester remote = (RemoteTester) domain.CreateInstanceAndUnwrap ( typeof (RemoteTester).Assembly.FullName, typeof (RemoteTester).FullName); Assert.AreEqual (basedir, remote.GetBaseDirectory (), "#5"); } finally { AppDomain.Unload (domain); } }
public override void InitializeNewDomain(AppDomainSetup appDomainInfo) { // Do nothing if this isn't the default app domain if (!AppDomain.CurrentDomain.IsDefaultAppDomain()) { return; } _info.Main = Main; BindApplicationMain(ref _info); if (!string.IsNullOrEmpty(_info.ApplicationBase)) { Environment.SetEnvironmentVariable(EnvironmentNames.AppBase, _info.ApplicationBase); } var version = DetermineDnxVersion(_info.ApplicationBase); _dnxTfm = new FrameworkName(FrameworkNames.LongNames.Dnx, version); Logger.TraceInformation($"[{nameof(DomainManager)}] Using Desktop CLR v{version}"); appDomainInfo.ApplicationBase = Environment.GetEnvironmentVariable(EnvironmentNames.DefaultLib); appDomainInfo.TargetFrameworkName = FrameworkNames.LongNames.NetFramework + ", Version=v" + version.ToString(); }
static int Main () { Console.WriteLine ("Friendly name: " + AppDomain.CurrentDomain.FriendlyName); AppDomainSetup setup = new AppDomainSetup (); setup.ApplicationBase = Directory.GetCurrentDirectory (); AppDomain newDomain = AppDomain.CreateDomain ("NewDomain", null, setup); c1 a1 = new c1 (); a1.e1.a = 3; a1.e1.s1 = "SS"; newDomain.SetData ("TEST", a1); c1 r1 = (c1)newDomain.GetData ("TEST"); if (r1.a != 1 || r1.b !=2) return 1; if (r1.s1 != "TEST1") return 2; if (r1.s2 != null) return 3; if (r1.e1.a != 3) return 4; if (r1.e1.s1 != "SS") return 5; Console.WriteLine("test-ok"); return 0; }
/// <summary> /// Creates an ITask instance and returns it. /// </summary> internal static ITask CreateTask(LoadedType loadedType, string taskName, string taskLocation, int taskLine, int taskColumn, LogError logError, AppDomainSetup appDomainSetup, bool isOutOfProc, out AppDomain taskAppDomain) { bool separateAppDomain = loadedType.HasLoadInSeparateAppDomainAttribute(); s_resolverLoadedType = null; taskAppDomain = null; ITask taskInstanceInOtherAppDomain = null; try { if (separateAppDomain) { if (!loadedType.Type.IsMarshalByRef) { logError ( taskLocation, taskLine, taskColumn, "TaskNotMarshalByRef", taskName ); return(null); } else { // Our task depend on this name to be precisely that, so if you change it make sure // you also change the checks in the tasks run in separate AppDomains. Better yet, just don't change it. // Make sure we copy the appdomain configuration and send it to the appdomain we create so that if the creator of the current appdomain // has done the binding redirection in code, that we will get those settings as well. AppDomainSetup appDomainInfo = new AppDomainSetup(); // Get the current app domain setup settings byte[] currentAppdomainBytes = appDomainSetup.GetConfigurationBytes(); // Apply the appdomain settings to the new appdomain before creating it appDomainInfo.SetConfigurationBytes(currentAppdomainBytes); if (BuildEnvironmentHelper.Instance.RunningTests) { // Prevent the new app domain from looking in the VS test runner location. If this // is not done, we will not be able to find Microsoft.Build.* assemblies. appDomainInfo.ApplicationBase = BuildEnvironmentHelper.Instance.CurrentMSBuildToolsDirectory; appDomainInfo.ConfigurationFile = BuildEnvironmentHelper.Instance.CurrentMSBuildConfigurationFile; } AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolver; s_resolverLoadedType = loadedType; taskAppDomain = AppDomain.CreateDomain(isOutOfProc ? "taskAppDomain (out-of-proc)" : "taskAppDomain (in-proc)", null, appDomainInfo); if (loadedType.LoadedAssembly != null) { taskAppDomain.Load(loadedType.LoadedAssembly.GetName()); } // Hook up last minute dumping of any exceptions taskAppDomain.UnhandledException += new UnhandledExceptionEventHandler(ExceptionHandling.UnhandledExceptionHandler); } } else { // perf improvement for the same appdomain case - we already have the type object // and don't want to go through reflection to recreate it from the name. return((ITask)Activator.CreateInstance(loadedType.Type)); } if (loadedType.Assembly.AssemblyFile != null) { taskInstanceInOtherAppDomain = (ITask)taskAppDomain.CreateInstanceFromAndUnwrap(loadedType.Assembly.AssemblyFile, loadedType.Type.FullName); // this will force evaluation of the task class type and try to load the task assembly Type taskType = taskInstanceInOtherAppDomain.GetType(); // If the types don't match, we have a problem. It means that our AppDomain was able to load // a task assembly using Load, and loaded a different one. I don't see any other choice than // to fail here. if (taskType != loadedType.Type) { logError ( taskLocation, taskLine, taskColumn, "ConflictingTaskAssembly", loadedType.Assembly.AssemblyFile, loadedType.Type.Assembly.Location ); taskInstanceInOtherAppDomain = null; } } else { taskInstanceInOtherAppDomain = (ITask)taskAppDomain.CreateInstanceAndUnwrap(loadedType.Type.Assembly.FullName, loadedType.Type.FullName); } return(taskInstanceInOtherAppDomain); } finally { // Don't leave appdomains open if (taskAppDomain != null && taskInstanceInOtherAppDomain == null) { AppDomain.Unload(taskAppDomain); RemoveAssemblyResolver(); } } }
public abstract AssemblyLoadContext CreateAssemblyLoadContextWithPolicy(string appDomainName, Evidence evidence, AppDomainSetup setupInfo, SandboxCasPolicySettings casSettings);
public MainApp() { Container = Configure(); using (var scope = Container.BeginLifetimeScope()) { // jsonLoader= scope.Resolve<IJsonLoader>(); //-------------------------------------------------------------------------------- // a Error Class that will have all error message tracking //--------------------------------------------------------------------------- // Erinfo = scope.Resolve<IErrorsInfo>(); //-------------------------------------------------------------------------------- // a Log Manager //--------------------------------------------------------------------------- // lg = scope.Resolve<IDMLogger>(); // lg.WriteLog("App started"); // a Utility Class for helping in Doing Different functions for Data Managment // util = scope.Resolve<IUtil>(); //-------------------------------------------------------------------------------- // this is the assembly loader for loading from Addin Folder and Projectdrivers Folder //--------------------------------------------------------------------------- // LLoader = scope.Resolve<IAssemblyLoader>(); LLoader = scope.Resolve <IAssemblyHandler>(); //------------------------------------------------------------------------------- // a onfiguration class for assembly, addin's and drivers loading into the // application //--------------------------------------------------------------------------- // Config_editor = scope.Resolve<IConfigEditor>(); // Setup the Entry Screen // the screen has to be in one the Addin DLL's loaded by the Assembly loader // Setup the Database Connection Screen // a "Work Flow" class will control all the workflow between different data source // and automation // WorkFlowEditor = scope.Resolve<IWorkFlowEditor>(); // eTL= scope.Resolve<IETL>(); //------------------------------------------------------------------------------- // The Main Class for Data Manager //--------------------------------------------------------------------------- DMEEditor = scope.Resolve <IDMEEditor>(); //------------------------------------------------------------------------------- // LLoader.DMEEditor = DMEEditor; // util.DME = DMEEditor; //------------------------------------------------------------------------------- // The Main Visualization Class tha control the visual aspect of the system //--------------------------------------------------------------------------- vis = scope.Resolve <IVisUtil>(); //------------------------------------------------------------------------------- // this Editor will help Generate user controls for visulization Controleditor = scope.Resolve <IControlEditor>(); //------------------------------------------------------------------------------- // a tree class will be main visualization control for the system vis.controlEditor = Controleditor; //--------------------------------------------------------------------------- // This has to be last step so that all Configuration is ready for Addin's // to be able to use //--------------------------------------------------------------------------- AppDomainSetup pluginsDomainSetup = new AppDomainSetup { ApplicationBase = AppDomain.CurrentDomain.BaseDirectory, PrivateBinPath = @"ConnectionDrivers;ProjectClasses" }; LLoader.LoadAllAssembly(); Config_editor.LoadedAssemblies = LLoader.Assemblies.Select(c => c.DllLib).ToList(); // you start you application from an Calling an Addin Config_editor.Config.SystemEntryFormName = @"Form1"; // Config_editor.Config.SystemEntryFormName = @"Frm_MainDisplayForm"; if (Config_editor.Config.SystemEntryFormName != null) { // Config_editor.Config.SystemEntryFormName = @"Frm_MainDisplayForm"; vis.ShowMainDisplayForm(); } else { Controleditor.MsgBox("Beep", "Could not Find any Startup Screen"); } } }
/// <summary> /// Creates an instance of a given type in the test source host. /// </summary> /// <param name="type"> The type that needs to be created in the host. </param> /// <param name="args">The arguments to pass to the constructor. /// This array of arguments must match in number, order, and type the parameters of the constructor to invoke. /// Pass in null for a constructor with no arguments. /// </param> /// <returns> An instance of the type created in the host. </returns> /// <remarks> If a type is to be created in isolation then it needs to be a MarshalByRefObject. </remarks> public object CreateInstanceForType(Type type, object[] args) { List <string> resolutionPaths = this.GetResolutionPaths(this.sourceFileName, VSInstallationUtilities.IsCurrentProcessRunningInPortableMode()); // Check if user specified any runsettings MSTestAdapterSettings adapterSettings = MSTestSettingsProvider.Settings; if (resolutionPaths != null && resolutionPaths.Count > 0) { if (EqtTrace.IsInfoEnabled) { EqtTrace.Info("TestSourceHost: Creating assembly resolver with resolution paths {0}.", string.Join(",", resolutionPaths.ToArray())); } // Adding adapter folder to resolution paths if (!resolutionPaths.Contains(Path.GetDirectoryName(typeof(TestSourceHost).Assembly.Location))) { resolutionPaths.Add(Path.GetDirectoryName(typeof(TestSourceHost).Assembly.Location)); } // Adding extensions folder to resolution paths if (!resolutionPaths.Contains(Path.GetDirectoryName(typeof(AssemblyHelper).Assembly.Location))) { resolutionPaths.Add(Path.GetDirectoryName(typeof(AssemblyHelper).Assembly.Location)); } } // Honour DisableAppDomain setting if it is present in runsettings if (this.runSettings != null && MSTestAdapterSettings.IsAppDomainCreationDisabled(this.runSettings.SettingsXml)) { if (adapterSettings != null) { try { this.assemblyResolver = new AssemblyResolver(resolutionPaths); this.assemblyResolver.AddSearchDirectoriesFromRunSetting(adapterSettings.GetDirectoryListWithRecursiveProperty(null)); } catch (Exception exception) { if (EqtTrace.IsErrorEnabled) { EqtTrace.Error(exception); } } } return(Activator.CreateInstance(type, args)); } var appDomainSetup = new AppDomainSetup(); // The below logic of preferential setting the appdomains appbase is needed because: // 1. We set this to the location of the test source if it is built for Full CLR -> Ideally this needs to be done in all situations. // 2. We set this to the location where the current adapter is being picked up from for UWP and .Net Core scenarios -> This needs to be // different especially for UWP because we use the desktop adapter(from %temp%\VisualStudioTestExplorerExtensions) itself for test discovery // in IDE scenarios. If the app base is set to the test source location, discovery will not work because we drop the // UWP platform service assembly at the test source location and since CLR starts looking for assemblies from the app base location, // there would be a mismatch of platform service assemblies during discovery. var frameworkVersionString = this.GetTargetFrameworkVersionString(this.sourceFileName); if (frameworkVersionString.Contains(PlatformServices.Constants.DotNetFrameWorkStringPrefix)) { appDomainSetup.ApplicationBase = Path.GetDirectoryName(this.sourceFileName) ?? Path.GetDirectoryName(typeof(TestSourceHost).Assembly.Location); } else { appDomainSetup.ApplicationBase = Path.GetDirectoryName(typeof(TestSourceHost).Assembly.Location); } if (EqtTrace.IsInfoEnabled) { EqtTrace.Info("TestSourceHost: Creating app-domain for source {0} with application base path {1}.", this.sourceFileName, appDomainSetup.ApplicationBase); } AppDomainUtilities.SetAppDomainFrameworkVersionBasedOnTestSource(appDomainSetup, frameworkVersionString); var configFile = this.GetConfigFileForTestSource(this.sourceFileName); AppDomainUtilities.SetConfigurationFile(appDomainSetup, configFile); this.domain = this.appDomain.CreateDomain("TestSourceHost: Enumering assembly", null, appDomainSetup); // Load objectModel before creating assembly resolver otherwise in 3.5 process, we run into a recurive assembly resolution // which is trigged by AppContainerUtilities.AttachEventToResolveWinmd method. EqtTrace.SetupRemoteEqtTraceListeners(this.domain); // Add an assembly resolver... Type assemblyResolverType = typeof(AssemblyResolver); if (EqtTrace.IsInfoEnabled) { EqtTrace.Info("TestSourceHost: assemblyenumerator location: {0} , fullname: {1} ", assemblyResolverType.Assembly.Location, assemblyResolverType.FullName); } var resolver = AppDomainUtilities.CreateInstance( this.domain, assemblyResolverType, new object[] { resolutionPaths }); if (EqtTrace.IsInfoEnabled) { EqtTrace.Info( "TestSourceHost: resolver type: {0} , resolve type assembly: {1} ", resolver.GetType().FullName, resolver.GetType().Assembly.Location); } this.assemblyResolver = (AssemblyResolver)resolver; if (adapterSettings != null) { try { var additionalSearchDirectories = adapterSettings.GetDirectoryListWithRecursiveProperty(appDomainSetup.ApplicationBase); if (additionalSearchDirectories?.Count > 0) { this.assemblyResolver.AddSearchDirectoriesFromRunSetting( adapterSettings.GetDirectoryListWithRecursiveProperty(appDomainSetup.ApplicationBase)); } } catch (Exception exception) { if (EqtTrace.IsErrorEnabled) { EqtTrace.Error(exception); } } } var enumerator = AppDomainUtilities.CreateInstance( this.domain, type, args); return(enumerator); }
public static object CreateApplicationHost(Type hostType, string virtualDir, string physicalDir) { if (physicalDir == null) { throw new NullReferenceException(); } // Make sure physicalDir has file system semantics // and not uri semantics ( '\' and not '/' ). physicalDir = Path.GetFullPath(physicalDir); if (hostType == null) { throw new ArgumentException("hostType can't be null"); } if (virtualDir == null) { throw new ArgumentNullException("virtualDir"); } Evidence evidence = new Evidence(AppDomain.CurrentDomain.Evidence); // // Setup // AppDomainSetup setup = new AppDomainSetup(); setup.ApplicationBase = physicalDir; string webConfig = FindWebConfig(physicalDir); if (webConfig == null) { webConfig = Path.Combine(physicalDir, DEFAULT_WEB_CONFIG_NAME); } setup.ConfigurationFile = webConfig; setup.DisallowCodeDownload = true; string[] bindirPath = new string [1] { Path.Combine(physicalDir, "bin") }; string bindir; foreach (string dir in HttpApplication.BinDirs) { bindir = Path.Combine(physicalDir, dir); if (Directory.Exists(bindir)) { bindirPath [0] = bindir; break; } } setup.PrivateBinPath = BuildPrivateBinPath(physicalDir, bindirPath); setup.PrivateBinPathProbe = "*"; string dynamic_dir = null; string user = Environment.UserName; int tempDirTag = 0; string dirPrefix = String.Concat(user, "-temp-aspnet-"); for (int i = 0; ; i++) { string d = Path.Combine(Path.GetTempPath(), String.Concat(dirPrefix, i.ToString("x"))); try { CreateDirectory(d); string stamp = Path.Combine(d, "stamp"); CreateDirectory(stamp); dynamic_dir = d; try { Directory.Delete(stamp); } catch (Exception) { // ignore } tempDirTag = i.GetHashCode(); break; } catch (UnauthorizedAccessException) { continue; } } // // Unique Domain ID // string domain_id = (virtualDir.GetHashCode() + 1 ^ physicalDir.GetHashCode() + 2 ^ tempDirTag).ToString("x"); // This is used by mod_mono's fail-over support string domain_id_suffix = Environment.GetEnvironmentVariable("__MONO_DOMAIN_ID_SUFFIX"); if (domain_id_suffix != null && domain_id_suffix.Length > 0) { domain_id += domain_id_suffix; } setup.ApplicationName = domain_id; setup.DynamicBase = dynamic_dir; setup.CachePath = dynamic_dir; string dynamic_base = setup.DynamicBase; if (CreateDirectory(dynamic_base) && (Environment.GetEnvironmentVariable("MONO_ASPNET_NODELETE") == null)) { ClearDynamicBaseDirectory(dynamic_base); } // // Create app domain // AppDomain appdomain; appdomain = AppDomain.CreateDomain(domain_id, evidence, setup); // // Populate with the AppDomain data keys expected, Mono only uses a // few, but third party apps might use others: // appdomain.SetData(".appDomain", "*"); int l = physicalDir.Length; if (physicalDir [l - 1] != Path.DirectorySeparatorChar) { physicalDir += Path.DirectorySeparatorChar; } appdomain.SetData(".appPath", physicalDir); appdomain.SetData(".appVPath", virtualDir); appdomain.SetData(".appId", domain_id); appdomain.SetData(".domainId", domain_id); appdomain.SetData(".hostingVirtualPath", virtualDir); appdomain.SetData(".hostingInstallDir", Path.GetDirectoryName(typeof(Object).Assembly.CodeBase)); appdomain.SetData("DataDirectory", Path.Combine(physicalDir, "App_Data")); appdomain.SetData(MonoHostedDataKey, "yes"); appdomain.DoCallBack(SetHostingEnvironment); return(appdomain.CreateInstanceAndUnwrap(hostType.Module.Assembly.FullName, hostType.FullName)); }
public void TestNET2Caller_AppDomain4_AssemblyLocator() { Assembly net2Caller = Assembly.LoadFrom(TestAssemblyRelativePath); AppDomainSetup setup = new AppDomainSetup() { //ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase, ApplicationBase = net2Caller.CodeBase, // -> AssemblyLocator will crash ApplicationName = "TestNET2Caller", SandboxInterop = true, ShadowCopyFiles = Boolean.TrueString, TargetFrameworkName = ".NETFramework,Version=v2.0" // appdomain is more or less ignoring < 4.5 :( }; setup.SetConfigurationBytes(System.Text.Encoding.UTF8.GetBytes(NET2Config)); System.Security.Policy.Evidence evidence = new System.Security.Policy.Evidence(AppDomain.CurrentDomain.Evidence); evidence.AddAssemblyEvidence(new System.Security.Policy.ApplicationDirectory(@"..\..\..\]BET[.Playground.Interop.COM.NET2Caller\bin\Debug\")); // create domain AppDomain net2CallerDomain = AppDomain.CreateDomain( "TestNET4Caller", evidence, setup ); try { AssemblyLocator.Init(net2CallerDomain); } catch (Exception ex) { Assert.Fail(ex.Message); /* * Could not load file or assembly ']BET[.Playground.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. Das System kann die angegebene Datei nicht finden. * * === Pre-bind state information === * LOG: DisplayName = ]BET[.Playground.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null * (Fully-specified) * * LOG: Appbase = ../]BET[.Playground/]BET[.Playground.Interop.COM.NET2Caller/bin/Debug/Playground.Interop.COM.NET2Caller.exe * LOG: Initial PrivatePath = ../Projects/]BET[.Playground/]BET[.Playground.Interop.COM.NET2Caller/bin/Debug/Playground.Interop.COM.NET2Caller.exe * Calling assembly : (Unknown). * === * LOG: This bind starts in default load context. * LOG: Found application configuration file (\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO 14.0\COMMON7\IDE\COMMONEXTENSIONS\MICROSOFT\TESTWINDOW\vstest.executionengine.x86.exe.Config). * LOG: Using application configuration file: \PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO 14.0\COMMON7\IDE\COMMONEXTENSIONS\MICROSOFT\TESTWINDOW\vstest.executionengine.x86.exe.Config * LOG: Using host configuration file: * LOG: Using machine configuration file from \Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config. * LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind). * LOG: Attempting download of new URL ../]BET[.Playground/]BET[.Playground.Interop.COM.NET2Caller/bin/Debug/Playground.Interop.COM.NET2Caller.exe/]BET[.Playground.Core.DLL. * LOG: Attempting download of new URL ../]BET[.Playground/]BET[.Playground.Interop.COM.NET2Caller/bin/Debug/Playground.Interop.COM.NET2Caller.exe/]BET[.Playground.Core/]BET[.Playground.Core.DLL. * LOG: Attempting download of new URL ../]BET[.Playground/]BET[.Playground.Interop.COM.NET2Caller/bin/Debug/Playground.Interop.COM.NET2Caller.exe/]BET[.Playground.Core.EXE. * LOG: Attempting download of new URL ../]BET[.Playground/]BET[.Playground.Interop.COM.NET2Caller/bin/Debug/Playground.Interop.COM.NET2Caller.exe/]BET[.Playground.Core/]BET[.Playground.Core.EXE. * * * at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) * at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) * at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) * at System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) * at System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) * at System.Reflection.Assembly.Load(String assemblyString) * at System.Runtime.Serialization.FormatterServices.LoadAssemblyFromString(String assemblyName) * at System.Reflection.MemberInfoSerializationHolder..ctor(SerializationInfo info, StreamingContext context) * at System.AppDomain.add_AssemblyLoad(AssemblyLoadEventHandler value) * at _BET_.Playground.Core.AssemblyLocator.Init(AppDomain domain) in ..\]BET[.Playground\]BET[.Playground.Core\Assembly.cs:line 14 * at _BET_.Playground.UnitTests.Interop.TestNET2Caller_AppDomain3_CreateCom2() in ..\]BET[.Playground\]BET[.Playground.UnitTests\Interop.cs:line 529 * */ } }
private void StartScript(UUID sourceItemID, UUID sourceAssetID, ISceneEntity hostObject, byte[] scriptBinary) { // Create a new AppDomain for this script AppDomainSetup domainSetup = new AppDomainSetup(); domainSetup.LoaderOptimization = LoaderOptimization.SingleDomain; AppDomain scriptDomain = AppDomain.CreateDomain(sourceItemID + ".lsl", null, domainSetup); // Create an instance (that lives in this AppDomain) and a wrapper // (that lives in the script AppDomain) for this script LSLScriptInstance instance = new LSLScriptInstance(sourceItemID, sourceAssetID, hostObject, scriptDomain); LSLScriptWrapper wrapper = (LSLScriptWrapper)scriptDomain.CreateInstanceAndUnwrap( Assembly.GetExecutingAssembly().FullName, "Simian.Scripting.Linden.LSLScriptWrapper"); wrapper.Init(scriptBinary, instance); instance.Init(wrapper); lock (m_syncRoot) { // If this script is already running, shut it down StopScript(sourceItemID, false); // Keep track of this script m_scripts[sourceItemID] = instance; // Keep track of the entity containing this script Dictionary <UUID, LSLScriptInstance> entityScripts; if (!m_scriptedEntities.TryGetValue(hostObject.ID, out entityScripts)) { entityScripts = new Dictionary <UUID, LSLScriptInstance>(); m_scriptedEntities[hostObject.ID] = entityScripts; } entityScripts[instance.ID] = instance; } if (hostObject is LLPrimitive) { // Update the PrimFlags for the containing LLPrimitive LLPrimitive obj = (LLPrimitive)hostObject; bool hasCollisionEvents; PrimFlags oldFlags = obj.Prim.Flags; LSLEventFlags eventFlags = wrapper.GetEventsForState("default"); PrimFlags newFlags = oldFlags; newFlags &= ~(PrimFlags.Touch | PrimFlags.Money); newFlags |= PrimFlags.Scripted | LSLEventFlagsToPrimFlags(eventFlags, out hasCollisionEvents); // FIXME: Do something with hasCollisionEvents // Either update the PrimFlags for this prim or just schedule // it for serialization (since it has a new script) if (newFlags != oldFlags) { obj.Prim.Flags = newFlags; m_scene.EntityAddOrUpdate(this, obj, 0, (uint)LLUpdateFlags.PrimFlags); } else { m_scene.EntityAddOrUpdate(this, obj, UpdateFlags.Serialize, 0); } } // Fire the state_entry event to get this script started PostScriptEvent(new EventParams(sourceItemID, "state_entry", new object[0], new DetectParams[0])); }
private static async Task ExecuteInternalAsync(BrokeredMessage message, ICollector <BrokeredMessage> response) { // We'll always need a response message, so create it now and populate it below. var responseMessage = new BrokeredMessage(); // We'll create the app domain in the outer scope so we can unload it when we are finished (if it was created). AppDomain sandboxDomain = null; try { var requestId = (int)message.Properties["RequestId"]; // Set correlation id of response message using the correlation ID of the request message. responseMessage.CorrelationId = message.CorrelationId; responseMessage.Properties["RequestId"] = requestId; // The request will also load the associated route, so we'll use that feature // to reduce the number of SQL calls we make. var request = await Program.RequestRepository.GetRequestByIdAsync(requestId).TraceTimeAsync("Load Request"); var route = request.Route; var routeSettings = route.RouteSettings.ToArray(); var routePackages = route.RoutePackages.ToArray(); // Trace the incoming request URI. Trace.TraceInformation("Trace 'Request Uri' - {0}", request.Uri); try { var ev = new Evidence(); ev.AddHostEvidence(new Zone(SecurityZone.Internet)); var assemblyType = typeof(ExecutionSandbox); var assemblyPath = Path.GetDirectoryName(assemblyType.Assembly.Location); var sandboxPermissionSet = TraceUtility.TraceTime("Create Sandbox Permission Set", () => SecurityManager.GetStandardSandbox(ev)); // Exit with an error code if for some reason we can't get the sandbox permission set. if (sandboxPermissionSet == null) { throw new EntryPointException("Unable to load the sandbox environment, please contact Subroute.io for help with this error."); } // We'll create a new folder to hold an empty config file we create, and by // doing this, it prevents the user from gaining access to our configuration // file and the settings within, such as connection strings, infrastructure // and other sensitive information we don't want them to have. Plus it will // allow us to change any configuration settings that are specific to their // application domain, such as default settings and other infrastructure. // We must ensure that we have at least the root configuration XML tag in // the configuration file we create or various dependencies will fail // such as XmlSerializer and DataContractSerializer. var directories = TraceUtility.TraceTime("Setup Filesystem", () => SetupFilesystem(route, routeSettings)); TraceUtility.TraceTime("Reconfigure Appropriate Permission Sets", () => { // Remove access to UI components since we are in a headless environment. sandboxPermissionSet.RemovePermission(typeof(UIPermission)); // Remove access to the File System Dialog since we are headless. sandboxPermissionSet.RemovePermission(typeof(FileDialogPermission)); // Add the ability to use reflection for invocation and serialization. sandboxPermissionSet.AddPermission(new ReflectionPermission(PermissionState.Unrestricted)); // Add the ability to make web requests. sandboxPermissionSet.AddPermission(new WebPermission(PermissionState.Unrestricted)); // Add the ability to use the XmlSerializer and the DataContractSerializer. sandboxPermissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.SerializationFormatter)); // Add permission to access the nuget package directory so that assemblies can be loaded. sandboxPermissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Read, Settings.NugetPackageDirectory)); // Add permission to read execution temp directory. sandboxPermissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read, new[] { directories.RootDirectory })); }); TraceUtility.TraceTime("Create AppDomain", () => { var appDomainSetup = new AppDomainSetup { ApplicationBase = assemblyPath, ConfigurationFile = directories.ConfigFile }; sandboxDomain = AppDomain.CreateDomain("Sandboxed", ev, appDomainSetup, sandboxPermissionSet); }); // The ExecutionSandbox is a MarshalByRef type that allows us to dynamically // load their assemblies via a byte array and execute methods inside of // their app domain from our full-trust app domain. It's the bridge that // crosses the app domain boundary. var executionSandbox = TraceUtility.TraceTime("Create ExecutionSandbox Instance", () => (ExecutionSandbox)sandboxDomain.CreateInstance( assemblyType.Assembly.FullName, assemblyType.FullName, false, BindingFlags.Public | BindingFlags.Instance, null, null, null, null) .Unwrap()); // Prepare packages by locating the proper assemblies for the current framework and ensure // they have been downloaded to the packages folder and return their paths. executionSandbox.SetReferences(await PreparePackagesAsync(routePackages).TraceTimeAsync("Prepare Packages")); // To properly load assemblies into the dynamic partial trust assembly, we have to override // the AssemblyResolve method which is only called when an assembly load attempt is made // and fails. We can't use a closure here because to do that, the entire class ExecutionMethods // would have to be serailized across the app domain boundry. So we'll add a string array property // to the ExecutionSandbox class so we can access the references from in the app domain boundry. // Just remember this event is executed inside the partial trust domain. sandboxDomain.AssemblyResolve += (sender, args) => { var name = new AssemblyName(args.Name); var path = ExecutionSandbox.References.FirstOrDefault(r => Path.GetFileNameWithoutExtension(r) == name.Name); return(path == null ? null : Assembly.LoadFrom(path)); }; // Build the ExecutionRequest object that represents the incoming request // which holds the payload, headers, method, etc. The class is serialized // so it can cross the app domain boundary. So it's serialized in our // full-trust host app domain, and deserialized and reinstantiated in // the sandbox app domain. var uri = new Uri(request.Uri, UriKind.Absolute); var executionRequest = TraceUtility.TraceTime("Create RouteRequest Instance", () => new RouteRequest(uri, request.Method) { IpAddress = request.IpAddress, Headers = HeaderHelpers.DeserializeHeaders(request.RequestHeaders), Body = request.RequestPayload }); try { // The ExecutionSandbox we'll attempt to locate the best method to execute // based on the incoming request method (GET, POST, DELETE, etc.) and // will pass the ExecutionRequest we created above. In return, we receive // an instance of ExecutionResponse that has been serialized like the request // and deserialized in our full-trust host domain. var executionResponse = TraceUtility.TraceTime("Load and Execute Request", () => executionSandbox.Execute(route.Assembly, executionRequest)); // We'll use the data that comes back from the response to fill out the // remainder of the database request record which will return the status // code, message, payload, and headers. Then we update the database. request.CompletedOn = DateTimeOffset.UtcNow; request.StatusCode = (int)executionResponse.StatusCode; request.StatusMessage = executionResponse.StatusMessage; request.ResponsePayload = executionResponse.Body; request.ResponseHeaders = RouteResponse.SerializeHeaders(executionResponse.Headers); await Program.RequestRepository.UpdateRequestAsync(request).TraceTimeAsync("Update Request Record"); // We'll pass back a small bit of data indiciating to the subscribers of // the response topic listening for our specific correlation ID that indicates // the route code was executed successfully and to handle it as such. responseMessage.Properties["Result"] = (int)ExecutionResult.Success; responseMessage.Properties["Message"] = "Completed Successfully"; // Create the response message and send it on its way. response.Add(responseMessage); } catch (TargetInvocationException invokationException) { // These exceptions can occur when we encounter a permission exception where // the user doesn't have permission to execute a particular block of code. if (invokationException.InnerException is SecurityException securityException) { throw new RoutePermissionException(GetPermissionErrorMessage(securityException), invokationException); } // Check for BadRequestException, we need to wrap it with the core exception. // These exceptions can occur when query string parsing fails, and since the // user's code doesn't have access to the core exceptions, we'll need to wrap // it instead manually. if (invokationException.InnerException is Common.BadRequestException badRequestException) { throw new Core.Exceptions.BadRequestException(badRequestException.Message, badRequestException); } // Otherwise it is most likely a custom user exception. throw new CodeException(invokationException.InnerException?.Message ?? "Route raised a custom exception.", invokationException.InnerException); } catch (EntryPointException entryPointException) { // These exceptions occur when an entry point could not be located. // Since we don't have a reference to core in the common library. // We'll instead wrap this exception in a core // exception to apply a status code. throw new RouteEntryPointException(entryPointException.Message, entryPointException); } catch (SecurityException securityException) { // These exceptions can occur when we encounter a permission exception where // the user doesn't have permission to execute a particular block of code. throw new RoutePermissionException(GetPermissionErrorMessage(securityException), securityException); } catch (Common.BadRequestException badRequestException) { // These exceptions can occur when query string parsing fails, and since the // user's code doesn't have access to the core exceptions, we'll need to wrap // it instead manually. throw new Core.Exceptions.BadRequestException(badRequestException.Message, badRequestException); } catch (AggregateException asyncException) // Captures async and task exceptions. { // These exceptions occur when an entry point could not be located. // Since we don't have a reference to core in the common library. // We'll instead wrap this exception in a core // exception to apply a status code. if (asyncException.InnerException is EntryPointException entryPointException) { throw new RouteEntryPointException(entryPointException.Message, entryPointException); } // These exceptions can occur when we encounter a permission exception where // the user doesn't have permission to execute a particular block of code. if (asyncException.InnerException is SecurityException securityException) { throw new RoutePermissionException(GetPermissionErrorMessage(securityException), securityException); } // These exceptions can occur when query string parsing fails, and since the // user's code doesn't have access to the core exceptions, we'll need to wrap // it instead manually. if (asyncException.InnerException is SecurityException badRequestException) { throw new Core.Exceptions.BadRequestException(badRequestException.Message, badRequestException); } // These are all other exceptions that occur during the execution of // a route. These exceptions are raised by the users code. throw new RouteException(asyncException.InnerException?.Message ?? asyncException.Message, asyncException.InnerException); } catch (Exception routeException) { // These are all other exceptions that occur during the execution of // a route. These exceptions are raised by the users code. throw new RouteException(routeException.Message, routeException); } } catch (Exception appDomainException) { // This exception relates to exceptions configuring the AppDomain and we'll still notify the // user, we just won't give them specific information that could reveal our infrastructure // unless an IStatusCodeException was thrown, meaning it's a public exception. var statusCode = 500; var statusMessage = "An unexpected exception has occurred. Please contact Subroute.io regarding this error."; var statusCodeException = appDomainException as IStatusCodeException; string stackTrace = null; if (statusCodeException != null) { statusCode = (int)statusCodeException.StatusCode; statusMessage = appDomainException.Message; if (appDomainException is CodeException) { stackTrace = appDomainException.ToString(); } } request.CompletedOn = DateTimeOffset.UtcNow; request.StatusCode = statusCode; request.ResponsePayload = PayloadHelpers.CreateErrorPayload(statusMessage, stackTrace); request.ResponseHeaders = HeaderHelpers.GetDefaultHeaders(); await Program.RequestRepository.UpdateRequestAsync(request).TraceTimeAsync("Update Request Record (Error)"); responseMessage.Properties["Result"] = (int)ExecutionResult.Failed; responseMessage.Properties["Message"] = appDomainException.Message; // Create the response message and send it on its way. response.Add(responseMessage); } } catch (Exception fatalException) { // These exceptions are absolutely fatal. We'll have to notify the waiting thread // via the service bus message, because we're unable to load a related request. responseMessage.Properties["Result"] = (int)ExecutionResult.Fatal; responseMessage.Properties["Message"] = fatalException.Message; // Create the response message and send it on its way. response.Add(responseMessage); } finally { // Unload the users app domain to recover all memory used by it. if (sandboxDomain != null) { TraceUtility.TraceTime("Unload AppDomain", () => AppDomain.Unload(sandboxDomain)); } } }
public NewDomainTestHelper(AppDomainSetup setupInformation) { domain = AppDomain.CreateDomain("TestDomain", AppDomain.CurrentDomain.Evidence, setupInformation); testObject = (T)domain.CreateInstanceAndUnwrap(typeof(T).Assembly.FullName, typeof(T).FullName); }
public static int Main(string[] args) { AppDomainSetup setup = new AppDomainSetup(); setup.ApplicationBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); _serverAppDomain = AppDomain.CreateDomain("Server", null, setup); _serverAppDomain.Load(typeof(ZyanConnection).Assembly.GetName()); CrossAppDomainDelegate serverWork = new CrossAppDomainDelegate(() => { var server = EventServer.Instance; if (server != null) { Console.WriteLine("Event server started."); } }); _serverAppDomain.DoCallBack(serverWork); // Test IPC Binary int ipcBinaryTestResult = IpcBinaryTest.RunTest(); Console.WriteLine("Passed: {0}", ipcBinaryTestResult == 0); // Test TCP Binary int tcpBinaryTestResult = TcpBinaryTest.RunTest(); Console.WriteLine("Passed: {0}", tcpBinaryTestResult == 0); // Test TCP Custom int tcpCustomTestResult = TcpCustomTest.RunTest(); Console.WriteLine("Passed: {0}", tcpCustomTestResult == 0); // Test TCP Duplex int tcpDuplexTestResult = TcpDuplexTest.RunTest(); Console.WriteLine("Passed: {0}", tcpDuplexTestResult == 0); // Test HTTP Custom int httpCustomTestResult = HttpCustomTest.RunTest(); Console.WriteLine("Passed: {0}", httpCustomTestResult == 0); // Test NULL Channel const string nullChannelResultSlot = "NullChannelResult"; _serverAppDomain.DoCallBack(new CrossAppDomainDelegate(() => { int result = NullChannelTest.RunTest(); AppDomain.CurrentDomain.SetData(nullChannelResultSlot, result); })); var nullChannelTestResult = Convert.ToInt32(_serverAppDomain.GetData(nullChannelResultSlot)); Console.WriteLine("Passed: {0}", nullChannelTestResult == 0); // Stop the event server EventServerLocator locator = _serverAppDomain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, "IntegrationTest_DistributedEvents.EventServerLocator") as EventServerLocator; locator.GetEventServer().Dispose(); Console.WriteLine("Event server stopped."); if (!MonoCheck.IsRunningOnMono || MonoCheck.IsUnixOS) { // Mono/Windows bug: // AppDomain.Unload freezes in Mono under Windows if tests for // System.Runtime.Remoting.Channels.Tcp.TcpChannel were executed. AppDomain.Unload(_serverAppDomain); Console.WriteLine("Server AppDomain unloaded."); } if (ipcBinaryTestResult + tcpBinaryTestResult + tcpCustomTestResult + tcpDuplexTestResult + httpCustomTestResult + nullChannelTestResult == 0) { Console.WriteLine("All tests passed."); return(0); } return(1); }
public void TestNET45Caller_AppDomain3_CreateCom1() { AppDomainSetup setup = new AppDomainSetup() { PrivateBinPath = TestPath, ApplicationBase = TestPath, ApplicationName = "TestNET45Caller", SandboxInterop = true, ShadowCopyFiles = Boolean.TrueString, TargetFrameworkName = ".NETFramework,Version=v4.5" }; System.Security.Policy.Evidence evidence = new System.Security.Policy.Evidence(AppDomain.CurrentDomain.Evidence); evidence.AddAssemblyEvidence(new System.Security.Policy.ApplicationDirectory(TestPath)); // create domain AppDomain net45CallerDomain = AppDomain.CreateDomain( "TestNET45Caller", evidence, setup ); Type proxy = typeof(Proxy); try { var handle = net45CallerDomain.CreateComInstanceFrom(proxy.Assembly.ManifestModule.FullyQualifiedName, proxy.FullName); var prg = (Proxy)handle.Unwrap(); var assembly = prg.GetAssembly(TestAssembly45RelativePath); var instance = Activator.CreateInstance(assembly.GetType(TestObject45)); var call = assembly.GetType(TestObject45).GetMethod(TestMethod); var result = call.Invoke(instance, null) as string; Assert.AreEqual <string>(ErrorMsg, result); // fail } catch (Exception ex) { if (ex.HResult == -2146233054) { Assert.Fail($"Expected Fail 1: {ex.Message}"); } if (ex.HResult == -2147024894) { Assert.Fail($"Expected Fail 2: {ex.Message}"); } if (ex.HResult == -2147024773) { Assert.Fail($"Expected Fail 3: {ex.Message}"); } Assert.Fail($"Unknown Fail: {ex.Message}"); } finally { AppDomain.Unload(net45CallerDomain); } Assert.Inconclusive(InconclusiveMsg); }
/// <summary> /// This is responsible for invoking Execute on the Task /// Any method calling ExecuteTask must remember to call CleanupTask /// </summary> /// <remarks> /// We also allow the Task to have a reference to the BuildEngine by design /// at ITask.BuildEngine /// </remarks> /// <param name="oopTaskHostNode">The OutOfProcTaskHostNode as the BuildEngine</param> /// <param name="taskName">The name of the task to be executed</param> /// <param name="taskLocation">The path of the task binary</param> /// <param name="taskFile">The path to the project file in which the task invocation is located.</param> /// <param name="taskLine">The line in the project file where the task invocation is located.</param> /// <param name="taskColumn">The column in the project file where the task invocation is located.</param> /// <param name="appDomainSetup">The AppDomainSetup that we want to use to launch our AppDomainIsolated tasks</param> /// <param name="taskParams">Parameters that will be passed to the task when created</param> /// <returns>Task completion result showing success, failure or if there was a crash</returns> internal OutOfProcTaskHostTaskResult ExecuteTask ( IBuildEngine oopTaskHostNode, string taskName, string taskLocation, string taskFile, int taskLine, int taskColumn, #if FEATURE_APPDOMAIN AppDomainSetup appDomainSetup, #endif IDictionary <string, TaskParameter> taskParams ) { buildEngine = oopTaskHostNode; this.taskName = taskName; #if FEATURE_APPDOMAIN _taskAppDomain = null; #endif wrappedTask = null; LoadedType taskType = null; try { TypeLoader typeLoader = new TypeLoader(TaskLoader.IsTaskClass); taskType = typeLoader.Load(taskName, AssemblyLoadInfo.Create(null, taskLocation)); } catch (Exception e) { if (ExceptionHandling.IsCriticalException(e)) { throw; } Exception exceptionToReturn = e; // If it's a TargetInvocationException, we only care about the contents of the inner exception, // so just save that instead. if (e is TargetInvocationException) { exceptionToReturn = e.InnerException; } return(new OutOfProcTaskHostTaskResult ( TaskCompleteType.CrashedDuringInitialization, exceptionToReturn, "TaskInstantiationFailureError", new string[] { taskName, taskLocation, String.Empty } )); } OutOfProcTaskHostTaskResult taskResult; if (taskType.HasSTAThreadAttribute()) { #if FEATURE_APARTMENT_STATE taskResult = InstantiateAndExecuteTaskInSTAThread(oopTaskHostNode, taskType, taskName, taskLocation, taskFile, taskLine, taskColumn, #if FEATURE_APPDOMAIN appDomainSetup, #endif taskParams); #else return(new OutOfProcTaskHostTaskResult ( TaskCompleteType.CrashedDuringInitialization, null, "TaskInstantiationFailureNotSupported", new string[] { taskName, taskLocation, typeof(RunInSTAAttribute).FullName } )); #endif } else { taskResult = InstantiateAndExecuteTask(oopTaskHostNode, taskType, taskName, taskLocation, taskFile, taskLine, taskColumn, #if FEATURE_APPDOMAIN appDomainSetup, #endif taskParams); } return(taskResult); }
/// <summary> /// Execute a task on the STA thread. /// </summary> /// <comment> /// STA thread launching code lifted from XMakeBuildEngine\BackEnd\Components\RequestBuilder\TaskBuilder.cs, ExecuteTaskInSTAThread method. /// Any bug fixes made to this code, please ensure that you also fix that code. /// </comment> private OutOfProcTaskHostTaskResult InstantiateAndExecuteTaskInSTAThread ( IBuildEngine oopTaskHostNode, LoadedType taskType, string taskName, string taskLocation, string taskFile, int taskLine, int taskColumn, #if FEATURE_APPDOMAIN AppDomainSetup appDomainSetup, #endif IDictionary <string, TaskParameter> taskParams ) { ManualResetEvent taskRunnerFinished = new ManualResetEvent(false); OutOfProcTaskHostTaskResult taskResult = null; Exception exceptionFromExecution = null; try { ThreadStart taskRunnerDelegate = delegate() { try { taskResult = InstantiateAndExecuteTask ( oopTaskHostNode, taskType, taskName, taskLocation, taskFile, taskLine, taskColumn, #if FEATURE_APPDOMAIN appDomainSetup, #endif taskParams ); } catch (Exception e) { if (ExceptionHandling.IsCriticalException(e)) { throw; } exceptionFromExecution = e; } finally { taskRunnerFinished.Set(); } }; Thread staThread = new Thread(taskRunnerDelegate); staThread.SetApartmentState(ApartmentState.STA); staThread.Name = "MSBuild STA task runner thread"; staThread.CurrentCulture = Thread.CurrentThread.CurrentCulture; staThread.CurrentUICulture = Thread.CurrentThread.CurrentUICulture; staThread.Start(); // TODO: Why not just Join on the thread??? taskRunnerFinished.WaitOne(); } finally { #if CLR2COMPATIBILITY taskRunnerFinished.Close(); #else taskRunnerFinished.Dispose(); #endif taskRunnerFinished = null; } if (exceptionFromExecution != null) { // Unfortunately this will reset the callstack throw exceptionFromExecution; } return(taskResult); }
/// <summary> /// Do the work of actually instantiating and running the task. /// </summary> private OutOfProcTaskHostTaskResult InstantiateAndExecuteTask ( IBuildEngine oopTaskHostNode, LoadedType taskType, string taskName, string taskLocation, string taskFile, int taskLine, int taskColumn, #if FEATURE_APPDOMAIN AppDomainSetup appDomainSetup, #endif IDictionary <string, TaskParameter> taskParams ) { #if FEATURE_APPDOMAIN _taskAppDomain = null; #endif wrappedTask = null; try { wrappedTask = TaskLoader.CreateTask(taskType, taskName, taskFile, taskLine, taskColumn, new TaskLoader.LogError(LogErrorDelegate), #if FEATURE_APPDOMAIN appDomainSetup, #endif true /* always out of proc */ #if FEATURE_APPDOMAIN , out _taskAppDomain #endif ); wrappedTask.BuildEngine = oopTaskHostNode; } catch (Exception e) { if (ExceptionHandling.IsCriticalException(e)) { throw; } Exception exceptionToReturn = e; // If it's a TargetInvocationException, we only care about the contents of the inner exception, // so just save that instead. if (e is TargetInvocationException) { exceptionToReturn = e.InnerException; } return(new OutOfProcTaskHostTaskResult ( TaskCompleteType.CrashedDuringInitialization, exceptionToReturn, "TaskInstantiationFailureError", new string[] { taskName, taskLocation, String.Empty } )); } foreach (KeyValuePair <string, TaskParameter> param in taskParams) { try { PropertyInfo paramInfo = wrappedTask.GetType().GetProperty(param.Key, BindingFlags.Instance | BindingFlags.Public); paramInfo.SetValue(wrappedTask, (param.Value == null ? null : param.Value.WrappedParameter), null); } catch (Exception e) { if (ExceptionHandling.IsCriticalException(e)) { throw; } Exception exceptionToReturn = e; // If it's a TargetInvocationException, we only care about the contents of the inner exception, // so just save that instead. if (e is TargetInvocationException) { exceptionToReturn = e.InnerException; } return(new OutOfProcTaskHostTaskResult ( TaskCompleteType.CrashedDuringInitialization, exceptionToReturn, "InvalidTaskAttributeError", new string[] { param.Key, param.Value.ToString(), taskName } )); } } bool success = false; try { if (CancelPending) { return(new OutOfProcTaskHostTaskResult(TaskCompleteType.Failure)); } // If it didn't crash and return before now, we're clear to go ahead and execute here. success = wrappedTask.Execute(); } catch (Exception e) { if (ExceptionHandling.IsCriticalException(e)) { throw; } return(new OutOfProcTaskHostTaskResult(TaskCompleteType.CrashedDuringExecution, e)); } PropertyInfo[] finalPropertyValues = wrappedTask.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); IDictionary <string, Object> finalParameterValues = new Dictionary <string, Object>(StringComparer.OrdinalIgnoreCase); foreach (PropertyInfo value in finalPropertyValues) { // only record outputs if (value.GetCustomAttributes(typeof(OutputAttribute), true).Count() > 0) { try { finalParameterValues[value.Name] = value.GetValue(wrappedTask, null); } catch (Exception e) { if (ExceptionHandling.IsCriticalException(e)) { throw; } // If it's not a critical exception, we assume there's some sort of problem in the parameter getter -- // so save the exception, and we'll re-throw once we're back on the main node side of the // communications pipe. finalParameterValues[value.Name] = e; } } } return(new OutOfProcTaskHostTaskResult(success ? TaskCompleteType.Success : TaskCompleteType.Failure, finalParameterValues)); }
public ActorSystemPlaygroundConfiguration With(AppDomainSetup setup) { Requires.NotNull(setup, "setup"); this.setup = setup; return(this); }
protected RdbmsToolsRunner(AppDomainSetup appDomainSetup, RdbmsToolsParameters rdbmsToolsParameters) : base(appDomainSetup) { _rdbmsToolsParameters = rdbmsToolsParameters; }
/// <summary> /// Constructor /// </summary> public TaskHostTask(IElementLocation taskLocation, TaskLoggingContext taskLoggingContext, IBuildComponentHost buildComponentHost, IDictionary <string, string> taskHostParameters, LoadedType taskType, AppDomainSetup appDomainSetup) { ErrorUtilities.VerifyThrowInternalNull(taskType, "taskType"); _taskLocation = taskLocation; _taskLoggingContext = taskLoggingContext; _buildComponentHost = buildComponentHost; _taskType = taskType; _appDomainSetup = appDomainSetup; _taskHostParameters = taskHostParameters; _packetFactory = new NodePacketFactory(); (this as INodePacketFactory).RegisterPacketHandler(NodePacketType.LogMessage, LogMessagePacket.FactoryForDeserialization, this); (this as INodePacketFactory).RegisterPacketHandler(NodePacketType.TaskHostTaskComplete, TaskHostTaskComplete.FactoryForDeserialization, this); (this as INodePacketFactory).RegisterPacketHandler(NodePacketType.NodeShutdown, NodeShutdown.FactoryForDeserialization, this); _packetReceivedEvent = new AutoResetEvent(false); _receivedPackets = new Queue <INodePacket>(); _taskHostLock = new Object(); _setParameters = new Dictionary <string, object>(); }
// Arguments: Codebase, flags, zone, uniqueid // If the flags indicate zone then a zone must be provided. // If the flags indicate a site then a uniqueid must be provided internal static int Main(string[] args) { if (args.Length != 1) { throw new ArgumentException(); } int index = 0; string file = args[index++]; if ((file.Length == 0) || (file[0] == '\0')) { throw new ArgumentException(); } string hashString = null; byte[] hash = null; int r = file.LastIndexOf("#"); if (r != -1 & r != (file.Length - 1)) { hashString = file.Substring(r + 1); file = file.Substring(0, r); hash = DecodeHex(hashString); } // Find the URL of the executable. For now we assume the // form to be http://blah/... with forward slashes. This // need to be update. string URL; string ConfigurationFile = null; int k = file.LastIndexOf('/'); if (k == -1) { URL = file; ConfigurationFile = file; } else { URL = file.Substring(0, k + 1); if (k + 1 < file.Length) { ConfigurationFile = file.Substring(k + 1); } } // Build up the configuration File name if (ConfigurationFile != null) { StringBuilder bld = new StringBuilder(); bld.Append(ConfigurationFile); bld.Append(".config"); ConfigurationFile = bld.ToString(); } string friendlyName = GetSiteName(file); Evidence documentSecurity = null; documentSecurity = new Evidence(); Zone zone = Zone.CreateFromUrl(file); if (zone.SecurityZone == SecurityZone.MyComputer) { throw new ArgumentException(); } documentSecurity.AddHost(zone); if (file.Length < 7 || String.Compare(file.Substring(0, 7), "file://", true, CultureInfo.InvariantCulture) != 0) { documentSecurity.AddHost(System.Security.Policy.Site.CreateFromUrl(file)); } else { throw new ArgumentException(); } documentSecurity.AddHost(new Url(file)); AppDomainSetup properties = new AppDomainSetup(); PermissionSet ps = SecurityManager.ResolvePolicy(documentSecurity); if (FailRebinds(ps)) { properties.DisallowBindingRedirects = true; } else { properties.DisallowBindingRedirects = false; } properties.ApplicationBase = URL; properties.PrivateBinPath = "bin"; if (ConfigurationFile != null) { properties.ConfigurationFile = ConfigurationFile; } AppDomain proxy = AppDomain.CreateDomain(friendlyName, documentSecurity, properties); if (proxy != null) { AssemblyName caller = Assembly.GetExecutingAssembly().GetName(); AssemblyName remote = new AssemblyName(); remote.Name = "IEExecRemote"; remote.SetPublicKey(caller.GetPublicKey()); remote.Version = caller.Version; remote.CultureInfo = CultureInfo.InvariantCulture; proxy.SetData("APP_LAUNCH_URL", file); ObjectHandle handle = proxy.CreateInstance(remote.FullName, "IEHost.Execute.IEExecuteRemote"); if (handle != null) { IEExecuteRemote execproxy = (IEExecuteRemote)handle.Unwrap(); if (execproxy != null) { int res = execproxy.ExecuteAsAssembly(file, documentSecurity, hash, AssemblyHashAlgorithm.SHA1); Stream streamedexception = execproxy.Exception; if (streamedexception != null) { BinaryFormatter formatter = new BinaryFormatter(); Exception e = (Exception)formatter.Deserialize(streamedexception); throw e; } return(res); } } } return(-1); }
/// <summary> /// Create an instance of the wrapped ITask for a batch run of the task. /// </summary> internal ITask CreateTaskInstance(ElementLocation taskLocation, TaskLoggingContext taskLoggingContext, IBuildComponentHost buildComponentHost, IDictionary <string, string> taskIdentityParameters, #if FEATURE_APPDOMAIN AppDomainSetup appDomainSetup, #endif bool isOutOfProc) { bool useTaskFactory = false; IDictionary <string, string> mergedParameters = null; _taskLoggingContext = taskLoggingContext; // Optimization for the common (vanilla AssemblyTaskFactory) case -- only calculate // the task factory parameters if we have any to calculate; otherwise even if we // still launch the task factory, it will be with parameters corresponding to the // current process. if ((_factoryIdentityParameters != null && _factoryIdentityParameters.Count > 0) || (taskIdentityParameters != null && taskIdentityParameters.Count > 0)) { VerifyThrowIdentityParametersValid(taskIdentityParameters, taskLocation, _taskName, "MSBuildRuntime", "MSBuildArchitecture"); mergedParameters = MergeTaskFactoryParameterSets(_factoryIdentityParameters, taskIdentityParameters); useTaskFactory = !NativeMethodsShared.IsMono && (_taskHostFactoryExplicitlyRequested || !TaskHostParametersMatchCurrentProcess(mergedParameters)); } else { // if we don't have any task host parameters specified on either the using task or the // task invocation, then we will run in-proc UNLESS "TaskHostFactory" is explicitly specified // as the task factory. useTaskFactory = _taskHostFactoryExplicitlyRequested; } if (useTaskFactory) { ErrorUtilities.VerifyThrowInternalNull(buildComponentHost, "buildComponentHost"); mergedParameters = mergedParameters ?? new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); string runtime = null; string architecture = null; if (!mergedParameters.TryGetValue(XMakeAttributes.runtime, out runtime)) { mergedParameters[XMakeAttributes.runtime] = XMakeAttributes.MSBuildRuntimeValues.clr4; } if (!mergedParameters.TryGetValue(XMakeAttributes.architecture, out architecture)) { mergedParameters[XMakeAttributes.architecture] = XMakeAttributes.GetCurrentMSBuildArchitecture(); } TaskHostTask task = new TaskHostTask(taskLocation, taskLoggingContext, buildComponentHost, mergedParameters, _loadedType #if FEATURE_APPDOMAIN , appDomainSetup #endif ); return(task); } else { #if FEATURE_APPDOMAIN AppDomain taskAppDomain = null; #endif ITask taskInstance = TaskLoader.CreateTask(_loadedType, _taskName, taskLocation.File, taskLocation.Line, taskLocation.Column, new TaskLoader.LogError(ErrorLoggingDelegate) #if FEATURE_APPDOMAIN , appDomainSetup #endif , isOutOfProc #if FEATURE_APPDOMAIN , out taskAppDomain #endif ); #if FEATURE_APPDOMAIN if (taskAppDomain != null) { _tasksAndAppDomains[taskInstance] = taskAppDomain; } #endif return(taskInstance); } }
public override void InitializeNewDomain(AppDomainSetup appDomainInfo) { appDomainInfo.ShadowCopyFiles = "true"; base.InitializeNewDomain(appDomainInfo); }
/// <summary> /// Initialisierung der Simulation /// </summary> /// <param name="configuration">Simulationskonfiguration</param> public void Init(SimulatorConfiguration configuration) { // unload possible appdomains. Unload(); // load involved ai's for (int team = 0; team < configuration.Teams.Count; team++) { for (int i = 0; i < configuration.Teams[team].Player.Count; i++) { // externe Guid-Info speichern Guid guid = configuration.Teams[team].Player[i].Guid; if (configuration.Teams[team].Player[i] is PlayerInfoFiledump) { // use filedump configuration.Teams[team].Player[i] = AiAnalysis.FindPlayerInformation( ((PlayerInfoFiledump)configuration.Teams[team].Player[i]).File, configuration.Teams[team].Player[i].ClassName); } else if (configuration.Teams[team].Player[i] is PlayerInfoFilename) { // use filename configuration.Teams[team].Player[i] = AiAnalysis.FindPlayerInformation( ((PlayerInfoFilename)configuration.Teams[team].Player[i]).File, configuration.Teams[team].Player[i].ClassName); } else { // not supported PlayerInfo-type throw new InvalidOperationException( Resource.SimulationCoreProxyWrongPlayerInfo); } // Rückspeicherung der externen Guid configuration.Teams[team].Player[i].Guid = guid; } } // setup appDomain AppDomainSetup setup = new AppDomainSetup(); // Base Path for references string applicationBase = AppDomain.CurrentDomain.RelativeSearchPath; if (string.IsNullOrEmpty(applicationBase)) { applicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase; } setup.ApplicationBase = applicationBase; setup.ShadowCopyDirectories = AppDomain.CurrentDomain.SetupInformation.ShadowCopyDirectories; setup.ShadowCopyFiles = "false"; setup.PrivateBinPath = ""; // setup some access-rights für appdomain PermissionSet rechte = new PermissionSet(PermissionState.None); rechte.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution)); rechte.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess)); bool IoAccess = false; bool UiAccess = false; bool DbAccess = false; bool NetAccess = false; // allow access to the needed ai-files foreach (TeamInfo team in configuration.Teams) { foreach (PlayerInfo info in team.Player) { if (info is PlayerInfoFilename) { rechte.AddPermission( new FileIOPermission( FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, ((PlayerInfoFilename)info).File)); } if (info.RequestDatabaseAccess) { DbAccess = true; } if (info.RequestFileAccess) { IoAccess = true; } if (info.RequestNetworkAccess) { NetAccess = true; } if (info.RequestUserInterfaceAccess) { UiAccess = true; } } } // Grand special rights if (IoAccess) { if (configuration.AllowFileAccess) { rechte.AddPermission(new FileIOPermission(PermissionState.Unrestricted)); } else { throw new ConfigurationErrorsException(Resource.SimulationCoreRightsConflictIo); } } if (UiAccess) { if (configuration.AllowUserinterfaceAccess) { rechte.AddPermission(new UIPermission(PermissionState.Unrestricted)); } else { throw new ConfigurationErrorsException(Resource.SimulationCoreRightsConflictUi); } } if (DbAccess) { if (configuration.AllowDatabaseAccess) { // TODO: Grand rights } else { throw new ConfigurationErrorsException(Resource.SimulationCoreRightsConflictDb); } } if (NetAccess) { if (configuration.AllowNetworkAccess) { rechte.AddPermission(new System.Net.WebPermission(PermissionState.Unrestricted)); rechte.AddPermission(new System.Net.SocketPermission(PermissionState.Unrestricted)); rechte.AddPermission(new System.Net.DnsPermission(PermissionState.Unrestricted)); } else { throw new ConfigurationErrorsException(Resource.SimulationCoreRightsConflictNet); } } // create appdomain and load simulation-host appDomain = AppDomain.CreateDomain("Simulation", AppDomain.CurrentDomain.Evidence, setup, rechte); host = (SimulatorHost) appDomain.CreateInstanceAndUnwrap( Assembly.GetExecutingAssembly().FullName, "AntMe.Simulation.SimulatorHost"); // initialize host if (!host.Init(configuration)) { // got some exceptions - unload appdomain und throw exception Exception ex = host.Exception; Unload(); throw ex; } }
static void loadFile(string fileName) { // Attempts to load the file. On failure, it will call unload. // Loading part does not take out a lock. // Lock is only done after loading is finished and dictionaries need updating. // We might get a load for a file that's no longer there. Just unload the old one. if (!File.Exists(fileName)) { unloadFile(fileName); return; } Type pmType; switch (Path.GetExtension(fileName).ToLowerInvariant()) { case ".dll": pmType = typeof(AsmPluginManager); break; case ".exe": // TODO these need to come from config case ".fsx": case ".vbx": case ".csx": case ".jsx": pmType = typeof(ScriptPluginManager); break; default: pmType = null; break; } if (pmType == null) { return; } // App domain setup var setup = new AppDomainSetup(); if (File.Exists(fileName + ".config")) { setup.ConfigurationFile = fileName + ".config"; } setup.ApplicationBase = Native.freeswitch.SWITCH_GLOBAL_dirs.mod_dir; setup.LoaderOptimization = LoaderOptimization.MultiDomainHost; // TODO: would MultiDomain work better since FreeSWITCH.Managed isn't gac'd? setup.CachePath = shadowDir; setup.ShadowCopyFiles = "true"; // computing private bin path var binPath = setup.PrivateBinPath ?? string.Empty; var binPaths = binPath.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries) .Select(x => x.Trim()) .ToList(); // adding "managed" (modules) directory if (!binPaths.Contains("managed")) { binPaths.Add("managed"); } // adding "managed/<modulename>" directory for per-module references support var moduleRefsDir = Path.GetFileName(fileName); moduleRefsDir = Path.GetFileNameWithoutExtension(moduleRefsDir); if (moduleRefsDir != null && moduleRefsDir.Trim() != "") { moduleRefsDir = Path.Combine("managed", moduleRefsDir); if (!binPaths.Contains(moduleRefsDir, StringComparer.OrdinalIgnoreCase)) { binPaths.Add(moduleRefsDir); } } // bringing all together setup.PrivateBinPath = string.Join(";", binPaths); // Create domain and load PM inside System.Threading.Interlocked.Increment(ref appDomainCount); setup.ApplicationName = Path.GetFileName(fileName) + "_" + appDomainCount; var domain = AppDomain.CreateDomain(setup.ApplicationName, null, setup); PluginManager pm; try { pm = (PluginManager)domain.CreateInstanceAndUnwrap(pmType.Assembly.FullName, pmType.FullName, null); if (!pm.Load(fileName)) { AppDomain.Unload(domain); unloadFile(fileName); return; } } catch (Exception ex) { // On an exception, we will unload the current file so an old copy doesnt stay active Log.WriteLine(LogLevel.Alert, "Exception loading {0}: {1}", fileName, ex.ToString()); AppDomain.Unload(domain); unloadFile(fileName); return; } // Update dictionaries atomically lock (loaderLock) { unloadFile(fileName); var pi = new PluginInfo { FileName = fileName, Domain = domain, Manager = pm }; pluginInfos.Add(pi); var newAppExecs = new Dictionary <string, AppPluginExecutor>(appExecs, StringComparer.OrdinalIgnoreCase); var newApiExecs = new Dictionary <string, ApiPluginExecutor>(apiExecs, StringComparer.OrdinalIgnoreCase); pm.AppExecutors.ForEach(x => x.Aliases.ForEach(y => newAppExecs[y] = x)); pm.ApiExecutors.ForEach(x => x.Aliases.ForEach(y => newApiExecs[y] = x)); appExecs = newAppExecs; apiExecs = newApiExecs; Action <PluginExecutor, string> printLoaded = (pe, type) => { var aliases = pe.Aliases.Aggregate((acc, x) => acc += ", " + x); Log.WriteLine(LogLevel.Notice, "Loaded {3} {0}, aliases '{1}', into domain {2}.", pe.Name, aliases, pi.Domain.FriendlyName, type); }; pm.AppExecutors.ForEach(x => printLoaded(x, "App")); pm.ApiExecutors.ForEach(x => printLoaded(x, "Api")); Log.WriteLine(LogLevel.Info, "Finished loading {0} into domain {1}.", pi.FileName, pi.Domain.FriendlyName); } }
internal static int Main(string[] args) { try { // Make sure that we have a strong name signature, otherwise we won't be able // to correctly trust this assembly in the sandboxed domain. if (Assembly.GetExecutingAssembly().Evidence.GetHostEvidence <StrongName>() == null) { WriteOutput(Resources.PartialTrustRunnerUnsigned); return(-1); } // Parse the command line - and make sure it is valid CommandLineData commands = ParseCommandLine(args); if (commands == null) { return(-1); } AppDomainSetup sandboxSetup = new AppDomainSetup(); // We need the AppDomain to have its AppBase be in the same location as the target // program. This allows the application to find all of its dependencies correctly sandboxSetup.ApplicationBase = Path.GetDirectoryName(Path.GetFullPath(commands.ProgramName)); // The application name should match the entry point sandboxSetup.ApplicationName = Path.GetFileNameWithoutExtension(commands.ProgramName); // We also want the AppDomain to use the .exe.config file that the target has // specified for itself (if it exists) string configFile = Path.GetFullPath(commands.ProgramName) + ".config"; if (File.Exists(configFile)) { sandboxSetup.ConfigurationFile = configFile; } // Get strong names for the full trust assemblies var fullTrustStrongNames = from fullTrustAssembly in commands.FullTrustAssemblies where fullTrustAssembly.Evidence.GetHostEvidence <StrongName>() != null select fullTrustAssembly.Evidence.GetHostEvidence <StrongName>(); // Create the sandboxed domain AppDomain sandbox = AppDomain.CreateDomain(Path.GetFileNameWithoutExtension(commands.ProgramName), null, sandboxSetup, commands.PermissionSet, fullTrustStrongNames.ToArray()); // Create an instance of our runner trampoline in the sandbox ObjectHandle runnerHandle = Activator.CreateInstanceFrom(sandbox, typeof(AssemblyRunner).Assembly.Location, typeof(AssemblyRunner).FullName); AssemblyRunner runner = runnerHandle.Unwrap() as AssemblyRunner; // Use the runner to execute the target assembly, and return the result of the assembly's // Main method. return(runner.ExecuteAssembly(commands.ProgramName, commands.Arguments, commands.NoRunnerOutput)); } catch (Exception ex) { WriteOutput(String.Format(CultureInfo.CurrentCulture, Resources.GeneralError, ex.Message)); return(-1); } }
/// <inheritdoc /> public void LoadPlugin(PluginInfo pluginInfo) { lock (_plugins) { // Unload the plugin first if it is already loaded if (_plugins.Contains(pluginInfo)) { UnloadPlugin(pluginInfo); } // TODO Just temporarily until settings are in place pluginInfo.Enabled = true; var mainFile = Path.Combine(pluginInfo.Directory.FullName, pluginInfo.Main); if (!File.Exists(mainFile)) { throw new ArtemisPluginException(pluginInfo, "Couldn't find the plugins main entry at " + mainFile); } // Load the plugin, all types implementing Plugin and register them with DI var setupInfo = new AppDomainSetup { ApplicationName = pluginInfo.Guid.ToString(), ApplicationBase = AppDomain.CurrentDomain.BaseDirectory, PrivateBinPath = pluginInfo.Directory.FullName }; pluginInfo.Context = AppDomainContext.Create(setupInfo); try { pluginInfo.Context.LoadAssemblyWithReferences(LoadMethod.LoadFrom, mainFile); } catch (Exception e) { throw new ArtemisPluginException(pluginInfo, "Failed to load the plugins assembly", e); } // Get the Plugin implementation from the main assembly and if there is only one, instantiate it var mainAssembly = pluginInfo.Context.Domain.GetAssemblies().First(a => a.Location == mainFile); var pluginTypes = mainAssembly.GetTypes().Where(t => typeof(Plugin).IsAssignableFrom(t)).ToList(); if (pluginTypes.Count > 1) { throw new ArtemisPluginException(pluginInfo, $"Plugin contains {pluginTypes.Count} implementations of Plugin, only 1 allowed"); } if (pluginTypes.Count == 0) { throw new ArtemisPluginException(pluginInfo, "Plugin contains no implementation of Plugin"); } var pluginType = pluginTypes.Single(); try { var parameters = new IParameter[] { new ConstructorArgument("pluginInfo", pluginInfo), new Parameter("PluginInfo", pluginInfo, false) }; pluginInfo.Instance = (Plugin)_childKernel.Get(pluginType, constraint: null, parameters: parameters); } catch (Exception e) { throw new ArtemisPluginException(pluginInfo, "Failed to instantiate the plugin", e); } _plugins.Add(pluginInfo); OnPluginLoaded(new PluginEventArgs(pluginInfo)); } }
public override void InitializeNewDomain(AppDomainSetup appDomainInfo) { InitializationFlags = AppDomainManagerInitializationOptions.RegisterWithHost; base.InitializeNewDomain(appDomainInfo); }
public static RdbmsToolsRunner Create(RdbmsToolsParameters rdbmsToolsParameters) { AppDomainSetup appDomainSetup = CreateAppDomainSetup(rdbmsToolsParameters); return(new RdbmsToolsRunner(appDomainSetup, rdbmsToolsParameters)); }
private static void _UpdateStart(OuiLoggedProgress progress, Entry version) { // Last line printed on error. const string errorHint = "\nPlease create a new issue on GitHub @ https://github.com/EverestAPI/Everest\nor join the #game_modding channel on Discord (invite in the repo).\nMake sure to upload your log.txt"; // Check if we're on an OS which supports manipulating Celeste.exe while it's used. bool canModWhileAlive = Environment.OSVersion.Platform == PlatformID.Unix; string zipPath = Path.Combine(PathGame, "everest-update.zip"); string extractedPath = canModWhileAlive ? PathGame : Path.Combine(PathGame, "everest-update"); progress.LogLine($"Updating to {version.Name} (branch: {version.Branch}) @ {version.URL}"); progress.LogLine($"Downloading"); DateTime timeStart = DateTime.Now; try { if (File.Exists(zipPath)) { File.Delete(zipPath); } // Manual buffered copy from web input to file output. // Allows us to measure speed and progress. using (WebClient wc = new WebClient()) using (Stream input = wc.OpenRead(version.URL)) using (FileStream output = File.OpenWrite(zipPath)) { long length; if (input.CanSeek) { length = input.Length; } else { length = _ContentLength(version.URL); } progress.Progress = 0; progress.ProgressMax = (int)length; byte[] buffer = new byte[4096]; DateTime timeLastSpeed = timeStart; int read; int readForSpeed = 0; int pos = 0; int speed = 0; TimeSpan td; while (pos < length) { read = input.Read(buffer, 0, (int)Math.Min(buffer.Length, length - pos)); output.Write(buffer, 0, read); pos += read; readForSpeed += read; td = DateTime.Now - timeLastSpeed; if (td.TotalMilliseconds > 100) { speed = (int)((readForSpeed / 1024D) / td.TotalSeconds); readForSpeed = 0; timeLastSpeed = DateTime.Now; } progress.Lines[progress.Lines.Count - 1] = $"Downloading: {((int) Math.Floor(100D * (pos / (double) length)))}% @ {speed} KiB/s"; progress.Progress = pos; } } } catch (Exception e) { progress.LogLine("Download failed!"); e.LogDetailed(); progress.LogLine(errorHint); progress.Progress = 0; progress.ProgressMax = 1; return; } progress.LogLine("Download finished."); progress.LogLine("Extracting update .zip"); try { if (extractedPath != PathGame && Directory.Exists(extractedPath)) { Directory.Delete(extractedPath, true); } // Don't use zip.ExtractAll because we want to keep track of the progress. using (ZipFile zip = new ZipFile(zipPath)) { progress.LogLine($"{zip.Entries.Count} entries"); progress.Progress = 0; progress.ProgressMax = zip.Entries.Count; foreach (ZipEntry entry in zip.Entries) { if (entry.FileName.Replace('\\', '/').EndsWith("/")) { progress.Progress++; continue; } string fullPath = Path.Combine(extractedPath, entry.FileName); string fullDir = Path.GetDirectoryName(fullPath); if (!Directory.Exists(fullDir)) { Directory.CreateDirectory(fullDir); } if (File.Exists(fullPath)) { File.Delete(fullPath); } progress.LogLine($"{entry.FileName} -> {fullPath}"); entry.Extract(extractedPath); // Confusingly enough, this takes the base directory. progress.Progress++; } } } catch (Exception e) { progress.LogLine("Extraction failed!"); e.LogDetailed(); progress.LogLine(errorHint); progress.Progress = 0; progress.ProgressMax = 1; return; } progress.LogLine("Extraction finished."); // Load MiniInstaller and run it in a new app domain on systems supporting this. if (canModWhileAlive) { progress.LogLine("Starting MiniInstaller"); progress.Progress = 0; progress.ProgressMax = 0; Directory.SetCurrentDirectory(PathGame); try { AppDomainSetup nestInfo = new AppDomainSetup(); nestInfo.ApplicationBase = Path.GetDirectoryName(extractedPath); AppDomain nest = AppDomain.CreateDomain( AppDomain.CurrentDomain.FriendlyName + " - MiniInstaller", AppDomain.CurrentDomain.Evidence, nestInfo, AppDomain.CurrentDomain.PermissionSet ); // nest.DoCallBack(Boot); ((MiniInstallerProxy)nest.CreateInstanceFromAndUnwrap( typeof(MiniInstallerProxy).Assembly.Location, typeof(MiniInstallerProxy).FullName )).Boot(new MiniInstallerBridge { Progress = progress, ExtractedPath = extractedPath }); AppDomain.Unload(nest); } catch (Exception e) { progress.LogLine("MiniInstaller failed!"); e.LogDetailed(); progress.LogLine(errorHint); progress.Progress = 0; progress.ProgressMax = 1; return; } } progress.Progress = 1; progress.ProgressMax = 1; progress.LogLine("Restarting"); for (int i = 5; i > 0; --i) { progress.Lines[progress.Lines.Count - 1] = $"Restarting in {i}"; Thread.Sleep(1000); } progress.Lines[progress.Lines.Count - 1] = $"Restarting"; // Start MiniInstaller in a separate process on systems that don't support modding the game while it'S alive. if (!canModWhileAlive) { try { // We're on Windows or another OS which doesn't support manipulating Celeste.exe while it's used. // Run MiniInstaller "out of body." Process installer = new Process(); if (Type.GetType("Mono.Runtime") != null) { installer.StartInfo.FileName = "mono"; installer.StartInfo.Arguments = "\"" + Path.Combine(extractedPath, "MiniInstaller.exe") + "\""; } else { installer.StartInfo.FileName = Path.Combine(extractedPath, "MiniInstaller.exe"); } installer.StartInfo.WorkingDirectory = extractedPath; installer.Start(); } catch (Exception e) { progress.LogLine("Starting installer failed!"); e.LogDetailed(); progress.LogLine(errorHint); progress.Progress = 0; progress.ProgressMax = 1; } } else { // On Linux / macOS, restart the game after it shuts down. Events.Celeste.OnShutdown += () => { Process game = new Process(); // If the game was installed via Steam, it should restart in a Steam context on its own. if (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX) { // The Linux and macOS versions come with a wrapping bash script. game.StartInfo.FileName = "bash"; game.StartInfo.Arguments = "\"" + Path.Combine(PathGame, "Celeste") + "\""; } else { game.StartInfo.FileName = Path.Combine(PathGame, "Celeste.exe"); } game.StartInfo.WorkingDirectory = PathGame; game.Start(); }; } }
public void TestNET45Caller_AppDomain3_CreateCom2() { Assembly net45Caller = Assembly.LoadFrom(TestAssembly45RelativePath); AppDomainSetup setup = new AppDomainSetup() { PrivateBinPath = net45Caller.CodeBase, ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase, //ApplicationBase = net45Caller.CodeBase, // -> AssemblyLocator will crash ApplicationName = "TestNET45Caller", SandboxInterop = true, ShadowCopyFiles = Boolean.TrueString, TargetFrameworkName = ".NETFramework,Version=v4.5", }; setup.SetConfigurationBytes(System.Text.Encoding.UTF8.GetBytes(NET45Config)); System.Security.Policy.Evidence evidence = new System.Security.Policy.Evidence(AppDomain.CurrentDomain.Evidence); evidence.AddAssemblyEvidence(new System.Security.Policy.ApplicationDirectory(@"..\..\..\]BET[.Playground.Interop.COM.NET45Caller\bin\Debug\")); // create domain AppDomain net45CallerDomain = AppDomain.CreateDomain( "TestNET45Caller", evidence, setup ); _BET_.Playground.Core.AssemblyLocator.Init(net45CallerDomain); try { var handle = net45CallerDomain.CreateComInstanceFrom(net45Caller.ManifestModule.FullyQualifiedName, net45Caller.GetType().FullName); var prg = handle.Unwrap(); var callCom = prg.GetType().GetMethod("CallCom"); var result = callCom.Invoke(prg, null) as string; Assert.AreEqual <string>(ErrorMsg, result); // fail Assert.Inconclusive(InconclusiveMsg); } catch (Exception ex) { // Could not load type 'System.Reflection.RuntimeAssembly' from // assembly 'Playground.Interop.COM.NET2Caller, Version=1.0.0.0, // Culture =neutral, PublicKeyToken=null' if (ex.HResult == -2146233054) { Assert.Fail($"Expected Fail 1: {ex.Message}"); } // Could not load file or assembly 'Playground.Interop.COM.NET2Caller, // Version =1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of // its dependencies. Das System kann die angegebene Datei nicht finden. if (ex.HResult == -2147024894) { Assert.Fail($"Expected Fail 2: {ex.Message}"); } // Could not load file or assembly 'Playground.Interop.COM.NET2Caller, // Version =1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of // its dependencies. Die Syntax für den Dateinamen, Verzeichnisnamen // oder die Datenträgerbezeichnung ist falsch. if (ex.HResult == -2147024773) { Assert.Fail($"Expected Fail 3: {ex.Message}"); } Assert.Fail($"Unknown Fail: {ex.Message}"); } finally { AppDomain.Unload(net45CallerDomain); } }
public NewDomainTestHelper(AppDomainSetup setupInformation, PermissionSet permissionSet, params StrongName[] fullTrustAssemblies) { domain = AppDomain.CreateDomain("TestDomain", null, setupInformation, permissionSet, fullTrustAssemblies); testObject = (T)domain.CreateInstanceAndUnwrap(typeof(T).Assembly.FullName, typeof(T).FullName); }
/// <summary> /// Load a project content using Reflection in a separate AppDomain. /// This method first tries to load the assembly from the disk cache, if it exists there. /// If it does not exist in disk cache, it creates a new AppDomain, instanciates a ReflectionLoader in it /// and loads the assembly <paramref name="filename"/>. /// If the file does not exist, <paramref name="include"/> is loaded from GAC. /// </summary> public ReflectionProjectContent ReflectionLoadProjectContent(string filename, string include) { DomPersistence persistence; bool tempPersistence; if (this.persistence == null) { tempPersistence = true; persistence = new DomPersistence(Path.GetTempPath(), this); } else { // non-temp persistence tempPersistence = false; persistence = this.persistence; ReflectionProjectContent pc = persistence.LoadProjectContentByAssemblyName(filename); if (pc != null) { return(pc); } pc = persistence.LoadProjectContentByAssemblyName(include); if (pc != null) { return(pc); } } AppDomainSetup setup = new AppDomainSetup(); setup.DisallowCodeDownload = true; setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; AppDomain domain = AppDomain.CreateDomain("AssemblyLoadingDomain", AppDomain.CurrentDomain.Evidence, setup); string database; try { object o = domain.CreateInstanceAndUnwrap(typeof(ReflectionLoader).Assembly.FullName, typeof(ReflectionLoader).FullName); ReflectionLoader loader = (ReflectionLoader)o; database = loader.LoadAndCreateDatabase(filename, include, persistence.CacheDirectory); } catch (FileLoadException e) { database = null; HostCallback.ShowAssemblyLoadErrorInternal(filename, include, e.Message); } catch (Exception e) { database = null; HostCallback.ShowError("Error loading code-completion information for " + include + " from " + filename, e); } finally { AppDomain.Unload(domain); } if (database == null) { LoggingService.Debug("AppDomain finished but returned null..."); return(null); } else { LoggingService.Debug("AppDomain finished, loading cache..."); try { return(persistence.LoadProjectContent(database)); } finally { if (tempPersistence) { try { File.Delete(database); } catch {} } } } }