Exemplo n.º 1
0
        public InterfaceAppDomainProxy(Type appDomainSetupType, bool appDomainSetupTypeLoadFromMainModule = false)
        {
            AppDomain.MonitoringIsEnabled = true;
            AppDomainSetupType            = appDomainSetupType;
            PermissionSet grantSet  = new PermissionSet(PermissionState.Unrestricted);
            AppDomain     appDomain = AppDomain.CreateDomain("Interface", null, new AppDomainSetup
            {
                ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase
            }, grantSet);
            string assemblyFile = System.Diagnostics.Process.GetCurrentProcess()?.MainModule?.FileName;

            if (null != appDomainSetupType)
            {
                if (appDomainSetupTypeLoadFromMainModule && !IsRunningInHostingProcess)
                {
                    appDomain.CreateInstanceFrom(assemblyFile, appDomainSetupType.FullName);
                }
                else
                {
                    appDomain.CreateInstance(appDomainSetupType.Assembly.FullName, appDomainSetupType.FullName);
                }
            }
            Type typeFromHandle = typeof(AppDomainProxyByte);

            InterfaceAppDomainSetup.Setup();
            Proxy = (AppDomainProxyByte)appDomain.CreateInstanceAndUnwrap(typeFromHandle.Assembly.FullName, typeFromHandle.FullName);
            InterfaceAppDomain = appDomain;
        }
Exemplo n.º 2
0
        public static void Init()
        {
            // Try restarting in another AppDomain if possible.
            try
            {
                // Give the new AppDomain full permissions.
                PermissionSet permissionSet = new PermissionSet(PermissionState.Unrestricted);
                permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.AllFlags));

                // The ApplicationBase of the new domain should be the directory containing the current DLL.
                AppDomainSetup appDomainSetup = new AppDomainSetup()
                {
                    ApplicationBase = Path.GetDirectoryName(typeof(InitProxy).Assembly.Location)
                };
                _childDomain = AppDomain.CreateDomain("SonicGlvl", null, appDomainSetup, permissionSet);
                _childDomain.UnhandledException += ChildDomain_UnhandledException;

                // Now make the new AppDomain load our code using our proxy.
                Type proxyType = typeof(InitProxy);
                _proxyObject = _childDomain.CreateInstanceFrom(proxyType.Assembly.Location, proxyType.FullName).Unwrap(); // Our AssemblyResolve will pick the missing DLL out.
                _proxyObject.Run();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Initialize();
            }
        }
Exemplo n.º 3
0
        /// <span class="code-SummaryComment"><summary></span>
        /// Loads an assembly into a new AppDomain and obtains all the
        /// namespaces in the loaded Assembly, which are returned as a
        /// List. The new AppDomain is then Unloaded
        /// <span class="code-SummaryComment"></summary></span>
        /// <span class="code-SummaryComment"><param name="assemblyLocation">The Assembly file </span>
        /// location<span class="code-SummaryComment"></param></span>
        /// <span class="code-SummaryComment"><returns>A list of found namespaces</returns></span>
        public List <String> GetNamespaces(FileInfo assemblyLocation)
        {
            List <String> namespaces = new List <String>();

            //if (string.IsNullOrEmpty(assemblyLocation.Directory.FullName))
            //{
            //    throw new InvalidOperationException("Directory can't be null or empty.");
            //}

            //if (!Directory.Exists(assemblyLocation.Directory.FullName))
            //{
            //    throw new InvalidOperationException(
            //       string.Format(CultureInfo.CurrentCulture,
            //       "Directory not found {0}",
            //       assemblyLocation.Directory.FullName));
            //}

            AppDomain childDomain = BuildChildDomain(AppDomain.CurrentDomain);

            try
            {
                Type loaderType = typeof(AssemblyLoader);
                if (loaderType.Assembly != null)
                {
                    var loader = (AssemblyLoader)childDomain.CreateInstanceFrom(loaderType.Assembly.Location, loaderType.FullName).Unwrap();
                    loader.LoadAssembly(assemblyLocation.FullName);
                    namespaces = loader.GetNamespaces(assemblyLocation.Directory.FullName);
                }
                return(namespaces);
            }
            finally
            {
                AppDomain.Unload(childDomain);
            }
        }
Exemplo n.º 4
0
        public void ConvertRequest_DoesLazyGetBufferlessInputStream()
        {
            // Need to run this test on different AppDomain because the buffer policy selector in
            // HttpControllerHandler is static and cached so it's not possible to change in the context of this test.
            AppDomain    newAppDomain = AppDomain.CreateDomain("NewTestAppDomain");
            string       codeBase     = Assembly.GetExecutingAssembly().CodeBase;
            UriBuilder   uri          = new UriBuilder(codeBase);
            string       location     = Uri.UnescapeDataString(uri.Path);
            ObjectHandle proxy        = newAppDomain.CreateInstanceFrom(location, typeof(RemoteHttpControllerHandlerTest).FullName);
            RemoteHttpControllerHandlerTest remoteTest = proxy.Unwrap() as RemoteHttpControllerHandlerTest;

            ConvertRequest_DoesLazyGetBufferlessInputStream_TestResults results;

            try
            {
                results = remoteTest.ConvertRequest_DoesLazyGetBufferlessInputStream();
            }
            finally
            {
                if (newAppDomain != null)
                {
                    AppDomain.Unload(newAppDomain);
                }
            }

            Assert.False(results.inputStreamCalledBeforeContentIsRead);
            Assert.True(results.inputStreamCalledAfterContentIsRead);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Instance method that creates a RazorHost in a new AppDomain.
        /// This method requires that you keep the Factory around in
        /// order to keep the AppDomain alive and be able to unload it.
        /// </summary>
        /// <returns></returns>
        public RazorEngine <TBaseTemplateType> GetRazorHostInAppDomain()
        {
            _localAppDomain = CreateAppDomain(null);
            if (_localAppDomain == null)
            {
                return(null);
            }

            RazorEngine <TBaseTemplateType> host;

            try
            {
                var ass = Assembly.GetExecutingAssembly();

                var assemblyPath = ass.Location;

                host = (RazorEngine <TBaseTemplateType>)_localAppDomain.CreateInstanceFrom(assemblyPath, typeof(RazorEngine <TBaseTemplateType>).FullName).Unwrap();
            }
            catch (Exception ex)
            {
                ErrorMessage = ex.Message;
                return(null);
            }

            return(host);
        }
Exemplo n.º 6
0
        private static AppDomain CreateTestDomain(string baseDirectory, bool assemblyResolver)
        {
            AppDomainSetup setup = new AppDomainSetup();

            setup.ApplicationBase = baseDirectory;
            setup.ApplicationName = "testdomain";

            AppDomain ad = AppDomain.CreateDomain("testdomain",
                                                  AppDomain.CurrentDomain.Evidence, setup);

            if (assemblyResolver)
            {
                Assembly ea = Assembly.GetExecutingAssembly();
                ad.CreateInstanceFrom(ea.CodeBase,
                                      typeof(AssemblyResolveHandler).FullName,
                                      false,
                                      BindingFlags.Public | BindingFlags.Instance,
                                      null,
                                      new object [] { ea.Location, ea.FullName },
                                      CultureInfo.InvariantCulture,
                                      null,
                                      null);
            }

            return(ad);
        }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            //AppDomain current = AppDomain.CurrentDomain;
            //Console.WriteLine("Current Domain : " + current.FriendlyName);
            //foreach (Assembly asm in current.GetAssemblies())
            //{
            //    Console.WriteLine("Assembly : " + asm.FullName);
            //    foreach (Module m in asm.GetModules())
            //    {
            //        Console.WriteLine("Module : " + m.FullyQualifiedName);
            //        foreach (Type t in m.GetTypes())
            //        {
            //            Console.WriteLine("Type : " + t.FullName);
            //            foreach (MemberInfo mi in t.GetMembers())
            //            {
            //                Console.WriteLine("Member : " + mi.Name);
            //            }
            //        }
            //    }
            //}

            AppDomain newAppDomain = AppDomain.CreateDomain("MyAppDomain");
            string    dllPath      = @"E:\Programming\C#\Study_CSharp\Test_Library\bin\Debug\Test_Library.dll";

            ObjectHandle objHandle1 = newAppDomain.CreateInstanceFrom(dllPath, "Test_Library.Class1");

            //AppDomain.Unload(newAppDomain);

            AppDomain.CurrentDomain.CreateInstanceFrom(dllPath, "Test_Library.Class2");

            //AppDomain.Unload(AppDomain.CurrentDomain);

            Console.WriteLine("objHandle1 : " + objHandle1.ToString());
        }
        /// <summary>
        /// Gets the requested type from the just created weaved assembly
        /// </summary>
        /// <param name="name">Name of the type to return.</param>
        /// <returns></returns>
        public object CreateInstance(string name)
        {
            var type     = _assembly.GetTypes().Single(x => x.Name == name);
            var instance = _domain.CreateInstanceFrom(_assemblyPath, type.FullName);

            return(instance);
        }
        /// <summary>
        /// TypeParser Factory method that loads the TypeParser
        /// object into a new AppDomain so it can be unloaded.
        /// Creates AppDomain and creates type.
        /// </summary>
        /// <returns></returns>
        public TypeParserLegacy CreateTypeParser()
        {
            if (!CreateAppDomain(null))
            {
                return(null);
            }

            // *** Use a custom Assembly Resolver that looks in the CURRENT directory
            //			this.LocalAppDomain.AssemblyResolve += new ResolveEventHandler( TypeParserFactory.ResolveAssembly );

            /// Create the instance inside of the new AppDomain
            /// Note: remote domain uses local EXE's AppBasePath!!!
            TypeParserLegacy parserLegacy = null;

            try
            {
                Assembly assembly     = Assembly.GetExecutingAssembly();
                string   assemblyPath = Assembly.GetExecutingAssembly().Location;
                object   objparser    = LocalAppDomain.CreateInstanceFrom(assemblyPath,
                                                                          typeof(TypeParserLegacy).FullName).Unwrap();

                parserLegacy = (TypeParserLegacy)objparser;
            }
            catch (Exception ex)
            {
                ErrorMessage = ex.GetBaseException().Message;
                return(null);
            }

            return(parserLegacy);
        }
        public static void Main(IntPtr portAddress)
        {
            // Retrieve Assemblies from the "Libraries" folder.
            AppDomain.CurrentDomain.AssemblyResolve += LocalAssemblyFinder.ResolveAppDomainAssembly;

            // Try restarting in another AppDomain if possible.
            try
            {
                // Give the new AppDomain full permissions.
                PermissionSet permissionSet = new PermissionSet(PermissionState.Unrestricted);
                permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.AllFlags));

                // The ApplicationBase of the new domain should be the directory containing the current DLL.
                AppDomainSetup appDomainSetup = new AppDomainSetup()
                {
                    ApplicationBase = Path.GetDirectoryName(typeof(InitProxy).Assembly.Location)
                };
                _childDomain = AppDomain.CreateDomain("Reloaded", null, appDomainSetup, permissionSet);

                // Now make the new AppDomain load our code using our proxy.
                Type    proxyType = typeof(InitProxy);
                dynamic initProxy = _childDomain.CreateInstanceFrom(proxyType.Assembly.Location, proxyType.FullName).Unwrap(); // Our AssemblyResolve will pick the missing DLL out.
                initProxy.Run(portAddress);
            }
            catch (Exception ex)
            {
                Initialize(portAddress);
            }
        }
        public bool Load()
        {
            //create the appdomain, base directory should be set to the packages base directory which should have the assembly containing the proxy in it
            AppDomainSetup setupInfo = new AppDomainSetup();

            setupInfo.ApplicationBase   = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            setupInfo.ApplicationName   = _appDomainName;
            setupInfo.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
            _appDomain = AppDomain.CreateDomain(_appDomainName, AppDomain.CurrentDomain.Evidence, setupInfo);


            try
            {
                //log4net.Repository.Hierarchy.Hierarchy hierachy = (log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository();
                log.Debug("Creating domain proxy for AppDomain: " + _appDomainName);
                //create the domain proxy
                Type proxyType = typeof(AssemblyLoadProxy);
                _loadProxy = (AssemblyLoadProxy)_appDomain.CreateInstanceFrom(proxyType.Assembly.Location, proxyType.FullName).Unwrap();

                _loadProxySponsor = new LifetimeSponsor(_loadProxy);

                log.Debug("Initializing cross-domain logging for AppDomain: " + _appDomainName);
                _loadProxy.InitializeLogging(new Logging.CrossDomainParentAppender());
            }
            catch (Exception ex)
            {
                //log.Error("An error occurred initializing the domain proxy for AppDomain: " + _appDomainName, ex);
                //return false;

                throw;
            }

            return(true);
        }
Exemplo n.º 12
0
        private static void GenerateWin32ManifestFileUsingHelper(string strAssemblyManifestFileName, string strAssemblyName, bool bGenerateTypeLib, string strReferenceFiles, string strAsmPath)
        {
            string         directoryName = Path.GetDirectoryName(strAssemblyName);
            AppDomainSetup info          = new AppDomainSetup {
                ApplicationBase = directoryName
            };
            AppDomain domain = AppDomain.CreateDomain("GenMan32", null, info);

            if (domain == null)
            {
                throw new ApplicationException(Resource.FormatString("Err_CannotCreateAppDomain"));
            }
            try
            {
                ObjectHandle handle = domain.CreateInstanceFrom(Assembly.GetExecutingAssembly().CodeBase, typeof(Win32ManifestGenerator).FullName);
                if (handle == null)
                {
                    throw new ApplicationException(Resource.FormatString("Err_CannotCreateRemoteWin32ManGen"));
                }
                ((Win32ManifestGenerator)handle.Unwrap()).GenerateWin32ManifestFile(strAssemblyManifestFileName, strAssemblyName, bGenerateTypeLib, strReferenceFiles, strAsmPath);
            }
            finally
            {
                AppDomain.Unload(domain);
            }
        }
Exemplo n.º 13
0
        public IEnumerable <IModelTermProvider> Interrogate()
        {
            if (!File.Exists(PackagePath))
            {
                throw new FileNotFoundException("The file: " + Path.GetFileName(PackagePath) + " was not found in " + Path.GetDirectoryName(PackagePath) + ".");
            }

            string         domainName = Path.GetFileNameWithoutExtension(PackagePath);
            AppDomainSetup setupInfo  = new AppDomainSetup();

            setupInfo.ApplicationName = domainName;
            setupInfo.ApplicationBase = AppDomainBase;
            _appDomain = AppDomain.CreateDomain(domainName, AppDomain.CurrentDomain.Evidence, setupInfo);

            Type proxyType = typeof(PackageInterrogationProxy);

            _interrogationProxy = (PackageInterrogationProxy)_appDomain.CreateInstanceFrom(proxyType.Assembly.Location, proxyType.FullName).Unwrap();

            return(_interrogationProxy.Interrogate(PackagePath).Select(
                       termProvider => {
                System.Runtime.Remoting.Lifetime.ILease leaseObj = System.Runtime.Remoting.RemotingServices.GetLifetimeService((ProxyModelTermProvider)termProvider) as System.Runtime.Remoting.Lifetime.ILease;
                if (leaseObj != null)
                {
                    Sponsors.Add(new LifetimeSponsor(leaseObj));
                }

                return termProvider;
            }
                       ));
        }
Exemplo n.º 14
0
        private static string GenerateTypeLibUsingHelper(string strAssemblyName)
        {
            string         directoryName = Path.GetDirectoryName(strAssemblyName);
            string         strTlbName    = null;
            AppDomainSetup info          = new AppDomainSetup {
                ApplicationBase = directoryName
            };
            AppDomain domain = AppDomain.CreateDomain("GenMan32", null, info);

            if (domain == null)
            {
                throw new ApplicationException(Resource.FormatString("Err_CannotCreateAppDomain"));
            }
            try
            {
                ObjectHandle handle = domain.CreateInstanceFrom(Assembly.GetExecutingAssembly().CodeBase, typeof(TypeLibGenerator).FullName);
                if (handle == null)
                {
                    throw new ApplicationException(Resource.FormatString("Err_CannotCreateRemoteTypeLibGenerator"));
                }
                ((TypeLibGenerator)handle.Unwrap()).GenerateTypeLib(strAssemblyName, ref strTlbName);
            }
            finally
            {
                AppDomain.Unload(domain);
            }
            if ((strTlbName != null) && !s_Options.m_bSilentMode)
            {
                Console.WriteLine(Resource.FormatString("Msg_TlbGenerated", strAssemblyName));
            }
            return(strTlbName);
        }
Exemplo n.º 15
0
        private IStoryHandler GetHandler()
        {
            //return
            //    Activator.CreateInstanceFrom(
            //        _assemblyLocation,
            //        "StorEvilTestAssembly.StorEvilDriver", true, 0, null, new object[] {_eventBus},
            //        CultureInfo.CurrentCulture, new object[0], AppDomain.CurrentDomain.Evidence) as IStoryHandler;

            // Construct and initialize settings for a second AppDomain.
            var domainSetup = new AppDomainSetup();

            if (InTest)
            {
                domainSetup.ApplicationBase          = Environment.CurrentDirectory;
                domainSetup.DisallowBindingRedirects = false;
            }
            else
            {
                domainSetup.ApplicationBase          = Path.GetDirectoryName(_assemblyLocations.First());
                domainSetup.DisallowBindingRedirects = false;
            }
            domainSetup.ShadowCopyFiles       = "true";
            domainSetup.ShadowCopyDirectories = GetDirectories(_assemblyLocations);
            domainSetup.ConfigurationFile     = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;

            // Create the second AppDomain.
            _appDomain = AppDomain.CreateDomain("TestDomain", null, domainSetup);

            return(_appDomain.CreateInstanceFrom(
                       _assemblyLocation,
                       "StorEvilTestAssembly.StorEvilDriver", true, 0, null, new object[] { _eventBus },
                       CultureInfo.CurrentCulture, new object[0]).Unwrap() as IStoryHandler);
        }
Exemplo n.º 16
0
        private bool ValidateCachedAssemblyVersion(string path)
        {
            AppDomain domain = AppDomain.CreateDomain("VersionChecker",
                                                      new Evidence(AppDomain.CurrentDomain.Evidence),
                                                      AppDomain.CurrentDomain.SetupInformation);

            try
            {
                Type checkerType = typeof(VersionChecker);
                var  checker     = (VersionChecker)domain.
                                   CreateInstanceFrom(
                    checkerType.Assembly.Location,
                    checkerType.FullName).Unwrap();

                checker.LoadAssembly(path);
                string version = checker.GetVersion();
                if (version != Program.GetProgramVersionInfo())
                {
                    return(false);
                }

                return(EnsureMethodsExist(checker.GetMethods()));
            }
            finally
            {
                AppDomain.Unload(domain);
            }
        }
Exemplo n.º 17
0
        private void ParseDirectory(string directory)
        {
            ////DirectoryInfo di = new DirectoryInfo(directory);

            string expandedDirectory = Path.GetFullPath(Environment.ExpandEnvironmentVariables(directory));
            string fileName          = Path.GetFileName(expandedDirectory);

            string[] candidateAssemblyPaths = Directory.GetFiles(expandedDirectory, string.Format(CultureInfo.InvariantCulture, @"{0}.dll", fileName), SearchOption.TopDirectoryOnly);

            if (candidateAssemblyPaths.Length > 0)
            {
                AppDomain childAppDomain = this.CreateChildAppDomain(AppDomain.CurrentDomain, expandedDirectory);
                Type      loaderType     = typeof(InnerModuleInfoLoader);

                try
                {
                    InnerModuleInfoLoader loader = (InnerModuleInfoLoader)childAppDomain.CreateInstanceFrom(loaderType.Assembly.Location, loaderType.FullName).Unwrap();
                    this.Items.AddRange(loader.LoadModules(candidateAssemblyPaths));
                }
                catch (FileNotFoundException)
                {
                    // Continue loading assemblies even if an assembly can not be loaded in the new AppDomain
                }
                finally
                {
                    AppDomain.Unload(childAppDomain);
                }
            }

            foreach (string d in Directory.GetDirectories(expandedDirectory))
            {
                ParseDirectory(d);
            }
        }
Exemplo n.º 18
0
    static void Main()
    {
        // Construct a path to the current assembly.
        string assemblyPath = Environment.CurrentDirectory + "\\" +
                              typeof(MarshalableExample).Assembly.GetName().Name + ".exe";

        AppDomain ad = AppDomain.CreateDomain("MyDomain");

        System.Runtime.Remoting.ObjectHandle oh =
            ad.CreateInstanceFrom(assemblyPath, "MarshalableExample");

        object obj = oh.Unwrap();

        // Three ways to use the newly created object, depending on how
        // much is known about the type: Late bound, early bound through
        // a mutually known interface, or early binding of a known type.
        //
        obj.GetType().InvokeMember("Test",
                                   System.Reflection.BindingFlags.InvokeMethod,
                                   Type.DefaultBinder, obj, new object[] { "Hello" });

        ITest it = (ITest)obj;

        it.Test("Hi");

        MarshalableExample ex = (MarshalableExample)obj;

        ex.Test("Goodbye");
    }
Exemplo n.º 19
0
        public static void Main()
        {
            // Try restarting in another AppDomain if possible.
            try
            {
                // Give the new AppDomain full permissions.
                PermissionSet permissionSet = new PermissionSet(PermissionState.Unrestricted);
                permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.AllFlags));

                // The ApplicationBase of the new domain should be the directory containing the current DLL.
                AppDomainSetup appDomainSetup = new AppDomainSetup()
                {
                    ApplicationBase = Path.GetDirectoryName(typeof(InitProxy).Assembly.Location)
                };
                _childDomain = AppDomain.CreateDomain("SA2VsChat", null, appDomainSetup, permissionSet);

                // Now make the new AppDomain load our code using our proxy.
                Type    proxyType = typeof(InitProxy);
                dynamic initProxy = _childDomain.CreateInstanceFrom(proxyType.Assembly.Location, proxyType.FullName).Unwrap();                 // Our AssemblyResolve will pick the missing DLL out.
                initProxy.Run();
            }
            catch
            {
                Init();
            }
        }
Exemplo n.º 20
0
        public RazorEngine <T> GetRazorHostInAppDomain()
        {
            LocalAppDomain = CreateAppDomain(null);
            if (LocalAppDomain == null)
            {
                return(null);
            }

            /// Create the instance inside of the new AppDomain
            /// Note: remote domain uses local EXE's AppBasePath!!!
            RazorEngine <T> host = null;

            try
            {
                Assembly ass = Assembly.GetExecutingAssembly();

                string AssemblyPath = ass.Location;

                host = (RazorEngine <T>)LocalAppDomain.CreateInstanceFrom(AssemblyPath,
                                                                          typeof(RazorEngine <T>).FullName).Unwrap();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(host);
        }
Exemplo n.º 21
0
        private void PrinterAssemblyInPlace(string assemblyFileFullPath, string workingDirectory)
        {
            // Create an AppDomain to load the assembly printer.
            AppDomainSetup options = new AppDomainSetup();

            options.ApplicationBase = workingDirectory;
            AppDomain domain = AppDomain.CreateDomain("AssemPrinter", null, options);

            if (domain == null)
            {
                MessageBox.Show("Cannot Create AppDomain.");
                throw new Exception("Cannot Create AppDomain.");
            }

            // Create the remote component that will printer the assembly.
            ObjectHandle h = domain.CreateInstanceFrom(typeof(TlbImpRegressionTestTool.RemoteAssemPrinter).Assembly.CodeBase,
                                                       "TlbImpRegressionTestTool.RemoteAssemPrinter");

            if (h == null)
            {
                MessageBox.Show("Failed in Calling Assembly Printer.");
                throw new Exception("Failed in Calling Assembly Printer.");
            }

            RemoteAssemPrinter code = (RemoteAssemPrinter)h.Unwrap();

            if (code != null)
            {
                code.Run(assemblyFileFullPath);
            }

            // Unload the app domain. Now the assembly is unloaded, too.
            AppDomain.Unload(domain);
        }
        /// <summary>
        /// Loads an assembly into a new AppDomain and obtains all the
        /// namespaces in the loaded Assembly, which are returned as a
        /// List. The new AppDomain is then Unloaded
        /// </summary>
        /// <param name="assemblyLocation">The Assembly file
        /// location</param>
        /// <returns>A list of found namespaces</returns>
        public List <String> LoadAssemblies(List <FileInfo> assemblyLocations)
        {
            List <String> namespaces = new List <String>();

            AppDomain childDomain = BuildChildDomain(
                AppDomain.CurrentDomain);

            try
            {
                Type loaderType = typeof(AssemblyLoader);
                if (loaderType.Assembly != null)
                {
                    AssemblyLoader loader =
                        (AssemblyLoader)childDomain.
                        CreateInstanceFrom(
                            loaderType.Assembly.Location,
                            loaderType.FullName).Unwrap();

                    namespaces = loader.LoadAssemblies(
                        assemblyLocations);
                }
                return(namespaces);
            }

            finally
            {
                AppDomain.Unload(childDomain);
            }
        }
Exemplo n.º 23
0
        public static void GetFullNameOfClassThatInheritsFromApplication(string pathOfAssemblyThatContainsEntryPoint, out string applicationClassFullName, out string assemblyName, out string assemblyFullName)
        {
            //-----------------
            // Thanks to: http://www.c-sharpcorner.com/UploadFile/girish.nehte/how-to-unload-an-assembly-loaded-dynamically-using-reflection/
            //-----------------

            // Load the assembly in a new AppDomain mainly so that we are able to unload it, which is necessary when we want to delete all temporary files including this assembly.
            AppDomainSetup setupInformation = AppDomain.CurrentDomain.SetupInformation;
            AppDomain      newAppDomain     = AppDomain.CreateDomain("newAppDomain", AppDomain.CurrentDomain.Evidence, setupInformation);

            //Create an instance of the inspector class in the new domain:
            //System.Runtime.Remoting.ObjectHandle obj = newAppDomain.CreateInstance(typeof(AssemblyInspectorOnOtherDomain).Assembly.FullName, typeof(AssemblyInspectorOnOtherDomain).FullName);
            string pathOfThisVeryAssembly = PathsHelper.GetPathOfThisVeryAssembly();

            System.Runtime.Remoting.ObjectHandle obj = newAppDomain.CreateInstanceFrom(pathOfThisVeryAssembly, typeof(AssemblyInspectorOnOtherDomain).FullName);

            IAssemblyInspectorOnOtherDomain inspector = (IAssemblyInspectorOnOtherDomain)obj.Unwrap(); // As the object we are creating is from another appdomain hence we will get that object in wrapped format and hence in next step we have unwrappped it

            // Call LoadAssembly method so that the assembly will be loaded into the new appdomain amd the object will also remain in new appdomain only:
            inspector.LoadAssembly(pathOfAssemblyThatContainsEntryPoint);

            // Call the method that finds the type that inherits from Application:
            applicationClassFullName = inspector.FindApplicationClassFullName();

            // Get the assembly name and full name too:
            assemblyName     = inspector.GetAssemblyName();
            assemblyFullName = inspector.GetAssemblyFullName();

            // Unload the assembly (so that we can later delete it if necessary):
            AppDomain.Unload(newAppDomain);
            GC.Collect();                  // Collects all unused memory
            GC.WaitForPendingFinalizers(); // Waits until GC has finished its work
            GC.Collect();
        }
Exemplo n.º 24
0
        private void EnsureModulesDiscovered()
        {
            if (_modules == null)
            {
                AppDomain childDomain = BuildChildDomain(AppDomain.CurrentDomain);

                try
                {
                    List <string> loadedAssemblies = new List <string>();

                    var assemblies = (
                        from Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()
                        where !(assembly is System.Reflection.Emit.AssemblyBuilder) &&
                        !String.IsNullOrEmpty(assembly.Location)
                        select assembly.Location
                        );

                    loadedAssemblies.AddRange(assemblies);

                    Type loaderType = typeof(InnerModuleInfoLoader);

                    if (loaderType.Assembly != null)
                    {
                        var loader =
                            (InnerModuleInfoLoader)childDomain.CreateInstanceFrom(loaderType.Assembly.Location, loaderType.FullName).Unwrap();
                        loader.LoadAssemblies(loadedAssemblies);
                        _modules = loader.GetModuleInfos(path);
                    }
                }
                finally
                {
                    AppDomain.Unload(childDomain);
                }
            }
        }
Exemplo n.º 25
0
        [Category("MobileNotWorking")]         // SIGSEGV, probably on AppDomain.Unload
        public void WeakHandleWorksOnNonRootDomain()
        {
            //Console.WriteLine("current app domain: " + AppDomain.CurrentDomain.Id);
            AppDomain domain = AppDomain.CreateDomain("testdomain");

            Assembly ea = Assembly.GetExecutingAssembly();

            domain.CreateInstanceFrom(ea.CodeBase,
                                      typeof(AssemblyResolveHandler).FullName,
                                      false,
                                      BindingFlags.Public | BindingFlags.Instance,
                                      null,
                                      new object [] { ea.Location, ea.FullName },
                                      CultureInfo.InvariantCulture,
                                      null,
                                      null);


            var testerType = typeof(CrossDomainGCHandleRunner);
            var r          = (CrossDomainGCHandleRunner)domain.CreateInstanceAndUnwrap(
                testerType.Assembly.FullName, testerType.FullName, false,
                BindingFlags.Public | BindingFlags.Instance, null, new object [0],
                CultureInfo.InvariantCulture, new object [0], null);


            Assert.IsTrue(r.RunTest(), "#1");
            AppDomain.Unload(domain);
        }
Exemplo n.º 26
0
        private static void CreateAndUnwrap(AppDomain domain)
        {
            var dll    = AppDomain.CurrentDomain.BaseDirectory + "plugin.dll";
            var handle = domain.CreateInstanceFrom(dll, "Plugin.ConsolePlugin");
            var ins    = (AppDomainComponent)handle.Unwrap();

            ins.Start();
        }
Exemplo n.º 27
0
 public CrossDomainTextWriter(AppDomain domain, TextWriter writer)
 {
     this.remoteTracer = domain.CreateInstanceFrom(Assembly.GetExecutingAssembly().Location, typeof(CrossDomainTextWriter).FullName).Unwrap() as CrossDomainTextWriter;
     if (remoteTracer != null)
     {
         remoteTracer.StartListening(this, writer);
     }
 }
Exemplo n.º 28
0
        public CrossDomainProxy(AppDomain domain)
        {
            this.domain = domain;

            var proxyObjectHandle = domain.CreateInstanceFrom(Assembly.GetExecutingAssembly().Location, typeof(InDomainHost).FullName);

            inDomainHost = (InDomainHost)proxyObjectHandle.Unwrap();
        }
Exemplo n.º 29
0
        static int LoadAPEIPC(IntPtr apePid)
        {
            try
            {
                int    APEPID       = apePid.ToInt32();
                string APEProcessId = apePid.ToString();
                string AUTProcessId = Process.GetCurrentProcess().Id.ToString();

                RegistryKey key                 = Registry.CurrentUser.CreateSubKey("Software").CreateSubKey("APE");
                string      APEPath             = (string)key.GetValue(APEProcessId + "_Path_" + AUTProcessId, null);
                string      AppDomainToLoadInto = (string)key.GetValue(APEProcessId + "_AppDomain_" + AUTProcessId, null);
                key.DeleteValue(APEProcessId + "_Path_" + AUTProcessId);
                key.DeleteValue(APEProcessId + "_AppDomain_" + AUTProcessId);
                key.Close();

                Assembly  assembly        = Assembly.LoadFrom(APEPath + @"\APE.Domain.dll");
                Type      myAPEDomainType = assembly.GetType("APE.Domain.DomainSearch");
                AppDomain appDom          = null;

                if (AppDomainToLoadInto == "DefaultDomain")
                {
                    if (AppDomain.CurrentDomain.IsDefaultAppDomain())
                    {
                        appDom = AppDomain.CurrentDomain;
                    }
                }
                else
                {
                    appDom = (AppDomain)myAPEDomainType.InvokeMember("GetAppDomain", BindingFlags.Default | BindingFlags.InvokeMethod, null, null, new object[] { AppDomainToLoadInto });
                }

                if (appDom == null)
                {
                    throw new Exception("Failed to find the appdomain " + AppDomainToLoadInto);
                }

                bool     WPF;
                Assembly assemblyWPF = appDom.GetAssemblies().FirstOrDefault(x => x.GetName().Name == "WindowsBase");
                if (assemblyWPF == null)
                {
                    WPF = false;
                }
                else
                {
                    WPF = true;
                }

                appDom.CreateInstanceFrom(APEPath + @"\APE.Communication.dll", "APE.Communication.APEIPC", false, BindingFlags.Default, null, new object[] { APEPID, AppDomainToLoadInto, WPF }, null, null);

                return(0);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message + "\r\n" + e.StackTrace);
                return(-1);
            }
        }
        private RemoteDirectoryLookupCatalog CreateRemoteDirectoryModuleCatalogInAppDomain(AppDomain testDomain)
        {
            RemoteDirectoryLookupCatalog remoteEnum;
            Type remoteEnumType = typeof(RemoteDirectoryLookupCatalog);

            remoteEnum = (RemoteDirectoryLookupCatalog)testDomain.CreateInstanceFrom(
                remoteEnumType.Assembly.Location, remoteEnumType.FullName).Unwrap();
            return(remoteEnum);
        }