Example #1
0
        // Cross-domain instance creation

        public static ObjectHandle CreateInstanceFrom(AppDomain domain, string assemblyFile, string typeName)
        {
            if (domain == null)
            {
                throw new ArgumentNullException("domain");
            }
            return(domain.CreateInstanceFrom(assemblyFile, typeName));
        }
 public DomainContainer(string clientDllPath, string version, int databasePort)
 {
     var clientDllFolder = System.IO.Path.GetDirectoryName(clientDllPath);
     var testSuiteRunningFolder = AppDomain.CurrentDomain.BaseDirectory;
     var setup = new AppDomainSetup();
     setup.ApplicationBase = clientDllFolder;
     domain = AppDomain.CreateDomain(version, null, setup);
     Type loaderType = typeof(Wrapper);
     wrapperProxy = (Wrapper)domain.CreateInstanceFrom(loaderType.Assembly.Location, loaderType.FullName).Unwrap();
     wrapperProxy.LoadAssemblyAndSetUp(clientDllPath, testSuiteRunningFolder, databasePort);
 }
Example #3
0
        public static ObjectHandle CreateInstanceFrom(AppDomain domain, string assemblyFile, string typeName,
                                                      bool ignoreCase, BindingFlags bindingAttr, Binder binder,
                                                      object [] args, CultureInfo culture,
                                                      object [] activationAttributes)
        {
            if (domain == null)
            {
                throw new ArgumentNullException("domain");
            }

            return(domain.CreateInstanceFrom(assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes));
        }
        /// <summary>
        /// 指定域的友好名称和程序集路径加载程序集。
        /// </summary>
        /// <param name="assemblyPath">程序集路径。</param>
        /// <param name="domainName">域的友好名称。</param>
        /// <returns>加载成功返回 true,否则返回 false。</returns>
        public bool LoadAssembly(string assemblyPath, string domainName)
        {
            // if the assembly file does not exist then fail
            if (!File.Exists(assemblyPath))
            {
                return(false);
            }

            // if the assembly was already loaded then fail
            if (_loadedAssemblies.ContainsKey(assemblyPath))
            {
                return(false);
            }

            // check if the appdomain exists, and if not create a new one
            AppDomain appDomain = null;

            if (_mapDomains.ContainsKey(domainName))
            {
                appDomain = _mapDomains[domainName];
            }
            else
            {
                appDomain = CreateChildDomain(AppDomain.CurrentDomain, domainName);
                _mapDomains[domainName] = appDomain;
            }

            // load the assembly in the specified app domain
            try
            {
                Type proxyType = typeof(AssemblyReflectionProxy);
                if (proxyType.Assembly != null)
                {
                    var proxy =
                        (AssemblyReflectionProxy)appDomain.
                        CreateInstanceFrom(
                            proxyType.Assembly.Location,
                            proxyType.FullName).Unwrap();

                    proxy.LoadAssembly(assemblyPath);

                    _loadedAssemblies[assemblyPath] = appDomain;
                    _proxies[assemblyPath]          = proxy;

                    return(true);
                }
            }
            catch
            { }

            return(false);
        }
Example #5
0
        /// <summary>
        /// Registers the assembply import.
        /// </summary>
        /// <param name="hostAppDomain">The host application domain.</param>
        public static void RegisterAssembplyImport(AppDomain hostAppDomain)
        {
            var assemblyImportType = typeof(AssemblyImport);

            hostAppDomain.CreateInstanceFrom(assemblyImportType.Assembly.CodeBase,
                    assemblyImportType.FullName,
                    true,
                    BindingFlags.CreateInstance,
                    null,
                    new object[] { AppDomain.CurrentDomain.BaseDirectory },
                    null,
                    new object[0]);
        }
Example #6
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 LoadResult LoadAssembly(FileInfo assemblyLocation)
		{
			LoadResult rlt = new LoadResult();
			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));

			}

			childDomain = BuildChildDomain(
				AppDomain.CurrentDomain);

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

					rlt.Assembly = loader.LoadAssembly(
						assemblyLocation.FullName);
					namespaces =
						loader.GetNamespaces(
							assemblyLocation.Directory.FullName);
				}
			}
			catch (Exception ex)
			{
				if (Debugger.IsAttached)
				{
					Debugger.Break();
				}
			}
			rlt.Namespaces = namespaces != null ? namespaces.ToArray() : null;
			return rlt;
		}
Example #7
0
        /// <summary>
        /// Creates an instance of the specified mojo name within the specified application domain.
        /// </summary>
        /// <param name="mojoName">the name of the mojo to create</param>
        /// <param name="pluginAssemblyFile">the.NET maven plugin</param>
        /// <param name="paramFile">the file containing the parameters to inject into an instance 
        /// of the specified mojo</param>
        /// <param name="applicationDomain">
        /// the application domain used to create the specified mojo name instance</param>
        /// <returns>an instance of the specified mojo name within the specified application domain</returns>
        internal int BuildPluginProject(AppDomain applicationDomain, FileInfo pluginArtifact,
                                        FileInfo outputDirectory, string groupId, string artifactId,
                                        string version)
        {
            ObjectHandle objectHandle =
                applicationDomain.CreateInstanceFrom(@pluginArtifact.FullName,
                                                     "NPanday.Plugin.Generator.JavaClassUnmarshaller");
            JavaClassUnmarshaller jcuRemote = (JavaClassUnmarshaller)objectHandle.Unwrap();
            List<JavaClass> javaClasses = jcuRemote.GetMojosFor(artifactId, groupId);
            JavaClassUnmarshaller jcuLocal = new JavaClassUnmarshaller();

            char[] delim = { '.' };
            DirectoryInfo sourceDirectory = new DirectoryInfo(@outputDirectory.FullName + "/src/main/java/"
                                                              + artifactId.Replace('.', '/'));
            sourceDirectory.Create();
            if (javaClasses.Count == 0)
            {
                Console.WriteLine("NPanday-000-000: There are no Mojos within the assembly: Artifact Id = "
                                  + artifactId);
                return 1;
            }

            foreach (JavaClass javaClass in javaClasses)
            {
                string[] tokens = javaClass.ClassName.Split(delim);
                string classFileName = tokens[tokens.Length - 1];
                FileInfo fileInfo = new FileInfo(sourceDirectory.FullName + "/"
                                                 + classFileName + ".java");
                jcuLocal.unmarshall(javaClass, fileInfo);
            }

            TextReader reader = new StreamReader(typeof(Generator).Assembly
                .GetManifestResourceStream("NPanday.Plugin.MojoGenerator.pom-java.xml"));

            XmlSerializer serializer = new XmlSerializer(typeof(NPanday.Model.Pom.Model));
            NPanday.Model.Pom.Model model = (NPanday.Model.Pom.Model)serializer.Deserialize(reader);
            model.artifactId = artifactId + ".JavaBinding";
            model.groupId = groupId;
            model.version = version;
            model.name = artifactId + ".JavaBinding";

            FileInfo outputPomXml = new FileInfo(@outputDirectory.FullName + "/pom-java.xml");
            TextWriter textWriter = new StreamWriter(@outputPomXml.FullName);
            serializer.Serialize(textWriter, model);

            return 0;
        }
Example #8
0
        static void Main(string[] args)
        {
            //这里获取当前程序域
            System.AppDomain currentDomain = System.AppDomain.CurrentDomain;
            Console.WriteLine(currentDomain.FriendlyName);

            //这里创建一个程序域 并在这个程序域中 运行AppDomain.exe
            System.AppDomain secondDomain = System.AppDomain.CreateDomain("New AppDomain");
            secondDomain.ExecuteAssembly("AppDomain.exe");

            //这里创建一个其它程序域的对象
            var cls = secondDomain.CreateInstanceFrom("Cs8.exe", "AppDomain.Demo", false, System.Reflection.BindingFlags.Default, null, new object[2] {
                1, 2
            }, null, null);
            //这里使用动态类型 是因为没有引用Cs8.exe程序集 所以取不到AppDomain.Demo类型(实际使用中是可以引用Cs8.exe程序集的)
            dynamic clsi = cls.Unwrap();

            Console.WriteLine(clsi.GetType().ToString());
            Console.WriteLine("{0} {1}", clsi.Var1, clsi.Var2);

            //这里清除掉程序域
            System.AppDomain.Unload(secondDomain);
        }
        InnerAssemblyLoader GetLoader()
        {
            if( !reflectionOnly ) return new InnerAssemblyLoader();

            childDomain = BuildChildDomain(AppDomain.CurrentDomain);

            var loaderType = typeof(InnerAssemblyLoader);

            var loader =
                (InnerAssemblyLoader)
                childDomain.CreateInstanceFrom(loaderType.Assembly.Location, loaderType.FullName)
                .Unwrap();

            return loader;
        }
        private RemoteEnumerator CreateRemoteEnumeratorInAppdomain(AppDomain testDomain)
        {
            RemoteEnumerator remoteEnum;
            Type remoteEnumType = typeof(RemoteEnumerator);

            remoteEnum = (RemoteEnumerator)testDomain.CreateInstanceFrom(
                                               remoteEnumType.Assembly.Location, remoteEnumType.FullName).Unwrap();
            return remoteEnum;
        }
Example #11
0
        /// <summary>
        /// Factory method used to create a DomainInitializer in an AppDomain.
        /// </summary>
        /// <param name="targetDomain">The domain in which to create the agent</param>
        /// <param name="traceLevel">The level of internal tracing to use</param>
        /// <returns>A proxy for the DomainAgent in the other domain</returns>
        public static DomainInitializer CreateInstance(AppDomain targetDomain)
        {
            #if NET_2_0
            System.Runtime.Remoting.ObjectHandle oh = Activator.CreateInstanceFrom(
                targetDomain,
            #else
            System.Runtime.Remoting.ObjectHandle oh = targetDomain.CreateInstanceFrom(
            #endif
                typeof(DomainInitializer).Assembly.CodeBase,
                typeof(DomainInitializer).FullName,
                false, BindingFlags.Default, null, null, null, null, null);

            object obj = oh.Unwrap();
            Type type = obj.GetType();
            return (DomainInitializer)obj;
        }
Example #12
0
        /// <summary>
        /// Runs a single testcase.
        /// </summary>
        /// <param name="assemblyFile">The test assembly.</param>
        /// <param name="configFile">The application configuration file for the test domain.</param>
        /// <param name="referenceAssemblies">List of files to scan for missing assembly references.</param>
        /// <returns>
        /// The result of the test.
        /// </returns>
        public TestRunner CreateRunner(FileInfo assemblyFile, FileInfo configFile, StringCollection referenceAssemblies)
        {
            // create test domain
            _domain = CreateDomain(assemblyFile.Directory, assemblyFile,
                configFile);

            // assemble directories which can be probed for missing unresolved
            // assembly references
            string[] probePaths = null;

            if (AppDomain.CurrentDomain.SetupInformation.PrivateBinPath != null) {
                string [] privateBinPaths = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath.Split(Path.PathSeparator);
                probePaths = new string [privateBinPaths.Length + 1];
                for (int i = 0; i < privateBinPaths.Length; i++) {
                    probePaths[i] = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                        privateBinPaths[i]);
                }
            } else {
                probePaths = new string[1];
            }

            string[] references = new string[referenceAssemblies.Count];
            referenceAssemblies.CopyTo (references, 0);

            // add base directory of current AppDomain as probe path
            probePaths [probePaths.Length - 1] = AppDomain.CurrentDomain.BaseDirectory;

            // create an instance of our custom Assembly Resolver in the target domain.
            #if NET_4_0
            _domain.CreateInstanceFrom(Assembly.GetExecutingAssembly().CodeBase,
                    typeof(AssemblyResolveHandler).FullName,
                    false,
                    BindingFlags.Public | BindingFlags.Instance,
                    null,
                    new object[] {probePaths, references},
                    CultureInfo.InvariantCulture,
                    null);
            #else
            _domain.CreateInstanceFrom(Assembly.GetExecutingAssembly().CodeBase,
                    typeof(AssemblyResolveHandler).FullName,
                    false,
                    BindingFlags.Public | BindingFlags.Instance,
                    null,
                    new object[] {probePaths, references},
                    CultureInfo.InvariantCulture,
                    null,
                    AppDomain.CurrentDomain.Evidence);
            #endif
            // create testrunner
            return CreateTestRunner(_domain);
        }
        private IStoryHandler GetHandler()
        {
            // 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], AppDomain.CurrentDomain.Evidence).Unwrap() as IStoryHandler;
        }
        /// <summary>
        /// Starts this server instance.
        /// </summary>
        /// <returns>
        /// return true if start successfull, else false
        /// </returns>
        public bool Start()
        {
            try
            {
                var currentDomain = AppDomain.CurrentDomain;
                var marshalServerType = typeof(MarshalAppServer);

                var workingDir = Path.Combine(Path.Combine(currentDomain.BaseDirectory, m_WorkingDir), Name);

                if (!Directory.Exists(workingDir))
                    Directory.CreateDirectory(workingDir);

                var startupConfigFile = m_Bootstrap.StartupConfigFile;

                if (!string.IsNullOrEmpty(startupConfigFile))
                {
                    if (!Path.IsPathRooted(startupConfigFile))
                        startupConfigFile = Path.Combine(currentDomain.BaseDirectory, startupConfigFile);
                }

                m_HostDomain = AppDomain.CreateDomain(m_ServerConfig.Name, currentDomain.Evidence, new AppDomainSetup
                    {
                        ApplicationName = m_ServerConfig.Name,
                        ApplicationBase = workingDir,
                        ConfigurationFile = startupConfigFile
                    });

                var assemblyImportType = typeof(AssemblyImport);

                m_HostDomain.CreateInstanceFrom(assemblyImportType.Assembly.CodeBase,
                        assemblyImportType.FullName,
                        true,
                        BindingFlags.CreateInstance,
                        null,
                        new object[] { currentDomain.BaseDirectory },
                        null,
                        new object[0]);

                m_AppServer = (IWorkItem)m_HostDomain.CreateInstanceAndUnwrap(marshalServerType.Assembly.FullName,
                        marshalServerType.FullName,
                        true,
                        BindingFlags.CreateInstance,
                        null,
                        new object[] { m_ServiceTypeName },
                        null,
                        new object[0]);

                if (!m_AppServer.Setup(m_Bootstrap, m_ServerConfig, m_Factories))
                    throw new Exception("Failed tp setup MarshalAppServer");
            }
            catch (Exception)
            {
                if (m_HostDomain != null)
                {
                    AppDomain.Unload(m_HostDomain);
                    m_HostDomain = null;
                }

                if (m_AppServer != null)
                {
                    m_AppServer = null;
                }

                return false;
            }

            return m_AppServer.Start();
        }
Example #15
0
        /// <summary>
        /// Creates an instance of the specified mojo name within the specified application domain.
        /// </summary>
        /// <param name="mojoName">the name of the mojo to create</param>
        /// <param name="pluginAssemblyFile">the.NET maven plugin</param>
        /// <param name="paramFile">the file containing the parameters to inject into an instance 
        /// of the specified mojo</param>
        /// <param name="applicationDomain">
        /// the application domain used to create the specified mojo name instance</param>
        /// <returns>an instance of the specified mojo name within the specified application domain</returns>
        internal AbstractMojo CreateAbstractMojoFor(String mojoName, FileInfo pluginAssemblyFile, 
		                                          FileInfo paramFile, AppDomain applicationDomain)
        {
            ObjectHandle objectHandle =
                applicationDomain.CreateInstanceFrom(pluginAssemblyFile.FullName, mojoName);
            AbstractMojo abstractMojo = (AbstractMojo) objectHandle.Unwrap();
            abstractMojo.InjectFields(paramFile.FullName);
            return abstractMojo;
        }
 /// <summary>
 /// Create an instance of the required type using the AppDomain
 /// </summary>
 /// <param name="compileAppDomain"></param>
 /// <param name="assemblyLocation"></param>
 /// <param name="classType"></param>
 /// <param name="assemblyCodeBase"></param>
 /// <returns></returns>
 private static object CreateInstance(AppDomain compileAppDomain, string assemblyLocation,
     Type classType, string assemblyCodeBase)
 {
     object instance = null;
     try
     {
         instance = compileAppDomain.CreateInstanceFrom(assemblyLocation, classType.FullName).Unwrap();
     }
     catch (Exception)
     {
     }
     if (instance == null)
     {
         try
         {
             instance = compileAppDomain.CreateInstanceFrom(assemblyCodeBase, classType.FullName).Unwrap();
         }
         catch (Exception)
         {
         }
     }
     return instance;
 }
        private RemoteDirectoryLookupCatalog CreateRemoteDirectoryModuleCatalogInAppDomain(AppDomain testDomain)
        {
            RemoteDirectoryLookupCatalog remoteEnum;
            Type remoteEnumType = typeof(RemoteDirectoryLookupCatalog);

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