Exemple #1
0
        static void Main()
        {
            // Read the main configuration file
            var xmlDoc = ReadConfiguration();

            // if MQ is installed, we need to inject in the configuration file
            // the necessary bindingredirect to use the amqmdnet installed in the GAC (even if older than the one ship with the tool)
            bool mqInstalled = CheckMqInstalled(out string mqVersion);

            if (mqInstalled)
            {
                AddBindingRedirect(xmlDoc, mqVersion);
            }

            // Prepare a new application domain setup with the modified configuration file
            var config = xmlDoc.ToString();
            var setup  = new AppDomainSetup();

            setup.SetConfigurationBytes(Encoding.Default.GetBytes(config));
            var newdomain = AppDomain.CreateDomain("MQExplorerPlusWithRightAPI", new Evidence(), setup);

            void startupaction()
            {
                Thread thread = new Thread(() =>
                {
                    App.Main();
                });

                thread.SetApartmentState(
                    ApartmentState.STA);
                thread.Start();
            }

            newdomain.DoCallBack(startupaction);
        }
        /// <exception cref="ArgumentNullException"><paramref name="assemblyDirectory"/> is <see langword="null" />.</exception>
        public AppDomainIsolation(string assemblyDirectory, string assemblyConfiguration)
        {
            if (string.IsNullOrEmpty(assemblyDirectory))
            {
                throw new ArgumentNullException(nameof(assemblyDirectory));
            }

            var configuration = AssemblyConfigurationFileTransformer.GetConfigurationBytes(assemblyDirectory, assemblyConfiguration);

            var setup = new AppDomainSetup();

            setup.ShadowCopyFiles = "true";
            setup.SetConfigurationBytes(configuration);

            Domain = AppDomain.CreateDomain("AppDomainIsolation:" + Guid.NewGuid(), null, setup);

            var type = typeof(T);

            LoadToolchainAssemblies(type);
            try
            {
                Object = (T)Domain.CreateInstanceAndUnwrap(type.Assembly.FullName, type.FullName);
            }
            catch
            {
                Object = (T)Domain.CreateInstanceFromAndUnwrap(type.Assembly.Location, type.FullName);
            }
        }
Exemple #3
0
        private static void Main(string[] args)
        {
            var typedArgs = TypedArgs.FromArgs(args);

            var config = new RuntimeConfig();

            config.AddCodeBaseFor(typeof(Program).Assembly.GetName());
            config.AddCodeBaseFor(typeof(IPluginController).Assembly.GetName());
            config.AddCodeBaseFor(typeof(ILogService).Assembly.GetName());

            var setup = new AppDomainSetup()
            {
                ApplicationBase     = AppDomain.CurrentDomain.BaseDirectory,
                PrivateBinPath      = Environment.CurrentDirectory,
                PrivateBinPathProbe = "ExcludeAppBase",
                ConfigurationFile   = typedArgs.AssemblyFile + ".config"
            };

            setup.SetConfigurationBytes(config.GetBytes());

            var pluginDomain = AppDomain.CreateDomain("Plugin", null, setup);

            pluginDomain.AssemblyResolve += AssemblyResolve;

            var bootstrapper = (Bootstrapper)pluginDomain.CreateInstanceAndUnwrap(typeof(Bootstrapper).Assembly.FullName, typeof(Bootstrapper).FullName);

            bootstrapper.RunPluginDomain(args);
        }
Exemple #4
0
        /// <exception cref="ArgumentNullException"><paramref name="assemblyDirectory"/> is <see langword="null" />.</exception>
        public AppDomainIsolation(string assemblyDirectory, string assemblyConfiguration, IEnumerable <BindingRedirect> bindingRedirects, IEnumerable <string> preloadedAssemblies)
        {
            if (string.IsNullOrEmpty(assemblyDirectory))
            {
                throw new ArgumentNullException(nameof(assemblyDirectory));
            }

            var configuration = AssemblyConfigurationFileTransformer.GetConfigurationBytes(
                assemblyDirectory, assemblyConfiguration, bindingRedirects);

            var setup = new AppDomainSetup();

            setup.ShadowCopyFiles = "true";
            setup.SetConfigurationBytes(configuration);

            Domain = AppDomain.CreateDomain("AppDomainIsolation:" + Guid.NewGuid(), null, setup);

            foreach (var pa in preloadedAssemblies)
            {
                Domain.Load(new AssemblyName {
                    CodeBase = pa
                });
            }

            var type = typeof(T);

            try
            {
                Object = (T)Domain.CreateInstanceAndUnwrap(type.Assembly.FullName, type.FullName);
            }
            catch
            {
                Object = (T)Domain.CreateInstanceFromAndUnwrap(type.Assembly.Location, type.FullName);
            }
        }
Exemple #5
0
        public void TestNET45Caller_AppDomain4_AssemblyLocator()
        {
            Assembly net45Caller = Assembly.LoadFrom(TestAssembly45RelativePath);

            AppDomainSetup setup = new AppDomainSetup()
            {
                //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
                );

            try
            {
                _BET_.Playground.Core.AssemblyLocator.Init(net45CallerDomain);
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
Exemple #6
0
        /// <summary>
        /// Loads the specified plugin assembly file into the returned plugin application domain.
        /// </summary>
        /// <param name="pluginAssemblyFile">the.NET maven plugin</param>
        /// <returns>application domain for .NET maven plugin</returns>
        ///
        internal AppDomain GetApplicationDomainFor(FileInfo pluginAssemblyFile)
        {
            Console.WriteLine("Loading Generator: " + pluginAssemblyFile.DirectoryName);
            AppDomainSetup setup = new AppDomainSetup();

            setup.ApplicationBase = pluginAssemblyFile.DirectoryName;

            // This is a fix for NPANDAY-398. The AppDomain should never load NPanday.Plugin in the version
            // that was referenced by the .NET-Plugin itself, but rather the version of NPanday.Plugin that
            // the Generator is compiled against.
            setup.SetConfigurationBytes(Encoding.UTF8.GetBytes(@"
<configuration>
    <runtime>
    <assemblyBinding xmlns=""urn:schemas-microsoft-com:asm.v1"">
        <dependentAssembly>
            <assemblyIdentity name=""NPanday.Plugin""
                            publicKeyToken=""4b435f4d76e2f0e6""
                            culture=""neutral"" />
            <bindingRedirect oldVersion=""0.0.0.0-65535.65535.65535.65535""
                            newVersion=""" + typeof(FieldAttribute).Assembly.GetName().Version + @"""/>
        </dependentAssembly>
    </assemblyBinding>
    </runtime>
</configuration>
"));

            AppDomain applicationDomain = AppDomain.CreateDomain("Loader", null, setup);

            string assemblyName = pluginAssemblyFile.Name.Replace(pluginAssemblyFile.Extension, "");

            applicationDomain.Load(assemblyName);

            return(applicationDomain);
        }
Exemple #7
0
        public void TestNET2Caller_AppDomain2_CustomDomain4()
        {
            Assembly net2Caller = Assembly.LoadFrom(TestAssemblyRelativePath);

            AppDomainSetup setup = new AppDomainSetup()
            {
                ApplicationBase     = AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
                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(
                "TestNET2Caller",
                evidence,
                setup
                );

            AssemblyLocator.Init(net2CallerDomain);

            try
            {
                var prg = net2CallerDomain.CreateInstanceAndUnwrap(net2Caller.FullName, net2Caller.GetType().FullName);

                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)
            {
                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(net2CallerDomain);
            }
        }
Exemple #8
0
        // Helper to create a cofigured domain using a config file excerpt
        public static AppDomain CreateDomain(string configFile)
        {
            AppDomain      current = App;
            AppDomainSetup ads     = new AppDomainSetup {
                ApplicationBase = current.BaseDirectory,
            };

            string configExcerpt  = File.ReadAllText(Path.Combine("Content", "Configuration", configFile));
            string configTemplate = File.ReadAllText(Path.Combine("Content", "Configuration", "configuration-template.xml"));

            byte[] bytes = Encoding.ASCII.GetBytes(configTemplate.Replace("{UNIVERSAL_CONFIGURATION}", configExcerpt));
            ads.SetConfigurationBytes(bytes);
            File.WriteAllBytes(ads.ConfigurationFile = Path.GetTempFileName(), bytes);

            return(AppDomain.CreateDomain(configFile, current.Evidence, ads));
        }
        public void TestNET45App_AppDomain2_CustomDomain2()
        {
            AppDomainSetup setup = new AppDomainSetup()
            {
                PrivateBinPath      = TestPath,
                ApplicationBase     = TestPath,
                ApplicationName     = "TestNET45App",
                TargetFrameworkName = ".NETFramework,Version=v4.5",
            };

            setup.SetConfigurationBytes(System.Text.Encoding.UTF8.GetBytes(NET45Config));

            Type proxy = typeof(Proxy);

            System.Security.Policy.Evidence evidence = AppDomain.CurrentDomain.Evidence;

            // create domain
            AppDomain net45AppDomain = AppDomain.CreateDomain(
                "TestNET45App",
                evidence,
                setup
                );

            try
            {
                var prg = (Proxy)net45AppDomain.CreateInstanceAndUnwrap(proxy.Assembly.FullName, proxy.FullName);

                // this will only work when it is referenced in the project?
                var assembly = prg.GetAssembly(TestAssembly45RelativePath);
                var instance = Activator.CreateInstance(assembly.GetType(TestObject45));

                var call   = assembly.GetType(TestObject45).GetMethod("Call");
                var result = call.Invoke(instance, null) as string;

                Assert.AreEqual <string>("This assembly is NET Dll Version v4.0.30319", result);
            }
            catch (Exception ex)
            {
                Assert.Fail($"Unknown Fail: {ex.Message}");
            }
            finally
            {
                AppDomain.Unload(net45AppDomain);
            }
        }
Exemple #10
0
        internal static void SetConfigurationFile(AppDomainSetup appDomainSetup, string testSourceConfigFile)
        {
            if (!string.IsNullOrEmpty(testSourceConfigFile))
            {
                if (EqtTrace.IsInfoEnabled)
                {
                    EqtTrace.Info("UnitTestAdapter: Using configuration file {0} to setup appdomain for test source {1}.", testSourceConfigFile, Path.GetFileNameWithoutExtension(testSourceConfigFile));
                }

                appDomainSetup.ConfigurationFile = Path.GetFullPath(testSourceConfigFile);

                try
                {
                    // Add redirection of the built 11.0 Object Model assembly to the current version if that is not 11.0
                    var currentVersionOfObjectModel = typeof(TestCase).Assembly.GetName().Version.ToString();
                    if (!string.Equals(currentVersionOfObjectModel, ObjectModelVersionBuiltAgainst))
                    {
                        var assemblyName       = typeof(TestCase).Assembly.GetName();
                        var configurationBytes =
                            XmlUtilities.AddAssemblyRedirection(
                                testSourceConfigFile,
                                assemblyName,
                                ObjectModelVersionBuiltAgainst,
                                assemblyName.Version.ToString());
                        appDomainSetup.SetConfigurationBytes(configurationBytes);
                    }
                }
                catch (Exception ex)
                {
                    if (EqtTrace.IsErrorEnabled)
                    {
                        EqtTrace.Error("Exception hit while adding binding redirects to test source config file. Exception : {0}", ex);
                    }
                }
            }
            else
            {
                // Use the current domains configuration setting.
                appDomainSetup.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
            }
        }
Exemple #11
0
        private void ThreadProc()
        {
            try
            {
                var setup = new AppDomainSetup
                {
                    ApplicationBase     = AppDomain.CurrentDomain.BaseDirectory,
                    ApplicationName     = "RPC client",
                    PrivateBinPath      = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath,
                    PrivateBinPathProbe = AppDomain.CurrentDomain.SetupInformation.PrivateBinPathProbe
                };

                if (_startInfo.AppDomainConfiguration != null)
                {
                    setup.SetConfigurationBytes(_startInfo.AppDomainConfiguration);
                }

                var appDomain = AppDomain.CreateDomain(setup.ApplicationName, AppDomain.CurrentDomain.Evidence, setup);

                try
                {
                    appDomain.ExecuteAssembly(_startInfo.FileName, _startInfo.Arguments.ToArray());
                }
                finally
                {
                    AppDomain.Unload(appDomain);
                }
            }
            catch (Exception exception)
            {
                _exception = exception;
            }
            finally
            {
                HasExited = true;

                OnExited();
            }
        }
Exemple #12
0
        private static AppDomain CreateAppDomain(string applicationPath)
        {
            var appDomainSetup = new AppDomainSetup {
                ApplicationBase = Path.GetDirectoryName(typeof(Program).Assembly.Location)
            };

            appDomainSetup.SetConfigurationBytes(Encoding.UTF8.GetBytes($@"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<runtime>
    <assemblyBinding xmlns=""urn:schemas-microsoft-com:asm.v1"">
        <dependentAssembly>
            <assemblyIdentity name=""Microsoft.VisualStudio.ExtensionManager"" publicKeyToken=""b03f5f7f11d50a3a"" culture=""neutral"" />
            <bindingRedirect oldVersion=""10.0.0.0-{VsProductVersion.Major}.0.0.0"" newVersion=""{VsProductVersion.Major}.0.0.0"" />
        </dependentAssembly>
    </assemblyBinding>
    </runtime>
</configuration>"));
            var appDomain        = AppDomain.CreateDomain($"{nameof(Installer)} {VsProductVersion}", null, appDomainSetup);
            var assemblyResolver = appDomain.CreateInstanceFromAndUnwrap <AssemblyResolver>();

            assemblyResolver.Install(Path.GetDirectoryName(applicationPath));
            return(appDomain);
        }
Exemple #13
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
#if FEATURE_APPDOMAIN
                                         , AppDomainSetup appDomainSetup
#endif
                                         , bool isOutOfProc
#if FEATURE_APPDOMAIN
                                         , out AppDomain taskAppDomain
#endif
                                         )
        {
#if FEATURE_APPDOMAIN
            bool separateAppDomain = loadedType.HasLoadInSeparateAppDomainAttribute();
            s_resolverLoadedType = null;
            taskAppDomain        = null;
            ITask taskInstanceInOtherAppDomain = null;
#endif

            try
            {
#if FEATURE_APPDOMAIN
                if (separateAppDomain)
                {
                    if (!loadedType.Type.GetTypeInfo().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 net.r_eg.IeXod.* 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());
                        }

#if FEATURE_APPDOMAIN_UNHANDLED_EXCEPTION
                        // Hook up last minute dumping of any exceptions
                        taskAppDomain.UnhandledException += new UnhandledExceptionEventHandler(ExceptionHandling.UnhandledExceptionHandler);
#endif
                    }
                }
                else
#endif
                {
                    // 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 FEATURE_APPDOMAIN
                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.GetTypeInfo().Assembly.Location
                        );

                        taskInstanceInOtherAppDomain = null;
                    }
                }
                else
                {
                    taskInstanceInOtherAppDomain = (ITask)taskAppDomain.CreateInstanceAndUnwrap(loadedType.Type.GetTypeInfo().Assembly.FullName, loadedType.Type.FullName);
                }

                return(taskInstanceInOtherAppDomain);
#endif
            }
            finally
            {
#if FEATURE_APPDOMAIN
                // Don't leave appdomains open
                if (taskAppDomain != null && taskInstanceInOtherAppDomain == null)
                {
                    AppDomain.Unload(taskAppDomain);
                    RemoveAssemblyResolver();
                }
#endif
            }
        }
Exemple #14
0
        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
                 *
                 */
            }
        }
Exemple #15
0
        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);
            }
        }
Exemple #16
0
        public void TestNET45Caller_AppDomain2_CustomDomain1()
        {
            AppDomainSetup setup = new AppDomainSetup()
            {
                PrivateBinPath      = TestPath,
                ApplicationBase     = TestPath,
                ApplicationName     = "TestNET45Caller",
                SandboxInterop      = true,
                ShadowCopyFiles     = Boolean.TrueString,
                TargetFrameworkName = ".NETFramework,Version=v4.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(TestPath));

            Type proxy = typeof(Proxy);

            // create domain
            AppDomain net45CallerDomain = AppDomain.CreateDomain(
                "TestNET45Caller",
                evidence,
                setup
                );

            try
            {
                var prg = (Proxy)net45CallerDomain.CreateInstanceAndUnwrap(proxy.Assembly.FullName, proxy.FullName);

                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>
        /// Create an instance of the wrapped ITask for a batch run of the task.
        /// </summary>
        public ITask CreateTaskInstance(ElementLocation taskLocation, TaskLoggingContext taskLoggingContext, AppDomainSetup appDomainSetup, bool isOutOfProc)
        {
            separateAppDomain = false;
            separateAppDomain = loadedType.HasLoadInSeparateAppDomainAttribute();

            taskAppDomain = null;

            if (separateAppDomain)
            {
                if (!loadedType.Type.IsMarshalByRef)
                {
                    taskLoggingContext.LogError
                    (
                        new BuildEventFileInfo(taskLocation),
                        "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);
                    taskAppDomain = AppDomain.CreateDomain(isOutOfProc ? "taskAppDomain (out-of-proc)" : "taskAppDomain (in-proc)", null, appDomainInfo);

                    // Hook up last minute dumping of any exceptions 
                    taskAppDomain.UnhandledException += new UnhandledExceptionEventHandler(ExceptionHandling.UnhandledExceptionHandler);
                }
            }

            // instantiate the task in given domain
            if (taskAppDomain == null || taskAppDomain == AppDomain.CurrentDomain)
            {
                // 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.
                taskInstance = (ITask)Activator.CreateInstance(loadedType.Type);

                return taskInstance;
            }

            if (loadedType.Assembly.AssemblyFile != null)
            {
                taskInstance = (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 = taskInstance.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)
                {
                    taskLoggingContext.LogError
                    (
                    new BuildEventFileInfo(taskLocation),
                    "ConflictingTaskAssembly",
                    loadedType.Assembly.AssemblyFile,
                    loadedType.Type.Assembly.Location
                    );

                    taskInstance = null;
                }
            }
            else
            {
                taskInstance = (ITask)taskAppDomain.CreateInstanceAndUnwrap(loadedType.Type.Assembly.FullName, loadedType.Type.FullName);
            }

            return taskInstance;
        }