Exemplo n.º 1
0
	public static Foo GetRemote (AppDomain domain)
	{
		Foo test = (Foo) domain.CreateInstanceAndUnwrap (
			typeof (Foo).Assembly.FullName,
			typeof (Foo).FullName, new object [0]);
		return test;
	}
Exemplo n.º 2
0
Arquivo: test.cs Projeto: mono/gert
	static CrossDomainTester CreateCrossDomainTester (AppDomain domain)
	{
		Type testerType = typeof (CrossDomainTester);

		return (CrossDomainTester) domain.CreateInstanceAndUnwrap (
			testerType.Assembly.FullName, testerType.FullName, false,
			BindingFlags.Public | BindingFlags.Instance, null, new object [0],
			CultureInfo.InvariantCulture, new object [0], domain.Evidence);
	}
Exemplo n.º 3
0
        /// <summary>
        /// Generates the license file.
        /// </summary>
        protected override void ExecuteTask()
        {
            FileInfo licensesFile = null;

            // ensure base directory is set, even if fileset was not initialized
            // from XML
            if (Assemblies.BaseDirectory == null)
            {
                Assemblies.BaseDirectory = new DirectoryInfo(Project.BaseDirectory);
            }

            // get the output .licenses file
            if (OutputFile == null)
            {
                try {
                    licensesFile = new FileInfo(Project.GetFullPath(Target + ".licenses"));
                } catch (Exception ex) {
                    throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                                                           ResourceUtils.GetString("NA2015"), Target), Location, ex);
                }
            }
            else
            {
                licensesFile = OutputFile;
            }

            // make sure the directory for the .licenses file exists
            if (!licensesFile.Directory.Exists)
            {
                licensesFile.Directory.Create();
            }

            // determine whether .licenses file need to be recompiled
            if (!NeedsCompiling(licensesFile))
            {
                return;
            }

            Log(Level.Verbose, ResourceUtils.GetString("String_CompilingLicenseUsingTarget"),
                InputFile.FullName, licensesFile.FullName, Target);

            if (HasCommandLineCompiler)
            {
                // the command line compiler does not allow us to specify the
                // full path to the output file, so we have it create the licenses
                // file in a temp directory, and copy it to its actual output
                // location

                // use a newly created temporary directory as working directory
                BaseDirectory = FileUtils.GetTempDirectory();

                try {
                    // set target assembly for generated licenses file
                    Arguments.Add(new Argument(string.Format(CultureInfo.InvariantCulture,
                                                             "/target:\"{0}\"", Target)));
                    // set input filename
                    Arguments.Add(new Argument(string.Format(CultureInfo.InvariantCulture,
                                                             "/complist:\"{0}\"", InputFile.FullName)));
                    // set output directory
                    Arguments.Add(new Argument(string.Format(CultureInfo.InvariantCulture,
                                                             "/outdir:\"{0}\"", BaseDirectory.FullName)));
                    // suppress display of startup banner
                    Arguments.Add(new Argument("/nologo"));
                    // adjust verbosity of tool if necessary
                    if (Verbose)
                    {
                        Arguments.Add(new Argument("/v"));
                    }
                    // use command line tool to compile licenses file
                    base.ExecuteTask();

                    // delete any existing output file
                    if (File.Exists(licensesFile.FullName))
                    {
                        File.Delete(licensesFile.FullName);
                    }

                    // copy licenses file to output file (with overwrite)
                    File.Copy(Path.Combine(BaseDirectory.FullName, Target + ".licenses"),
                              licensesFile.FullName, true);
                } finally {
                    // delete temporary directory and all files in it
                    DeleteTask deleteTask = new DeleteTask();
                    deleteTask.Project = Project;
                    deleteTask.Parent  = this;
                    deleteTask.InitializeTaskConfiguration();
                    deleteTask.Directory = BaseDirectory;
                    deleteTask.Threshold = Level.None; // no output in build log
                    deleteTask.Execute();
                }
            }
            else
            {
                // create new domain
                AppDomain newDomain = AppDomain.CreateDomain("LicenseGatheringDomain",
                                                             AppDomain.CurrentDomain.Evidence);

                LicenseGatherer licenseGatherer = (LicenseGatherer)
                                                  newDomain.CreateInstanceAndUnwrap(typeof(LicenseGatherer).Assembly.FullName,
                                                                                    typeof(LicenseGatherer).FullName, false, BindingFlags.Public | BindingFlags.Instance,
                                                                                    null, new object[0], CultureInfo.InvariantCulture, new object[0],
                                                                                    AppDomain.CurrentDomain.Evidence);
                licenseGatherer.CreateLicenseFile(this, licensesFile.FullName);

                // unload newly created domain
                AppDomain.Unload(newDomain);
            }
        }
Exemplo n.º 4
0
        public void Create(IScriptHost host)
        {
            try
            {
                m_scriptHost = host;

                ((IScriptHostWithResourceData)host).GetResourceName(out var nameString);
                string resourceName = Marshal.PtrToStringAnsi(nameString);

                bool useTaskScheduler = true;
                bool useSyncContext   = false;

#if IS_FXSERVER
                string basePath = "";

                {
                    // we can't invoke natives if not doing this
                    InternalManager.ScriptHost = host;

                    basePath         = Native.API.GetResourcePath(resourceName);
                    useTaskScheduler = Native.API.GetNumResourceMetadata(resourceName, "clr_disable_task_scheduler") == 0;
                    useSyncContext   = Native.API.GetNumResourceMetadata(resourceName, "clr_experimental_2021_12_31_use_sync_context") > 0;

                    if (host is IScriptHostWithManifest manifestHost)
                    {
                        if (manifestHost.IsManifestVersionV2Between("bodacious", ""))
                        {
                            useTaskScheduler = false;
                        }
                    }
                }
#endif

                m_appDomain = AppDomain.CreateDomain($"ScriptDomain_{m_instanceId}", AppDomain.CurrentDomain.Evidence, new AppDomainSetup()
                {
#if IS_FXSERVER
                    ApplicationBase = basePath
#endif
                });

                m_appDomain.SetupInformation.ConfigurationFile = "dummy.config";

                m_intManager = (InternalManager)m_appDomain.CreateInstanceAndUnwrap(typeof(InternalManager).Assembly.FullName, typeof(InternalManager).FullName);

                if (useTaskScheduler)
                {
                    m_intManager.CreateTaskScheduler();
                }

                m_intManager.SetConfiguration(useSyncContext: useSyncContext);

                m_intManager.SetResourceName(resourceName);

                // TODO: figure out a cleaner solution to Mono JIT corruption so server doesn't have to be slower
#if IS_FXSERVER && !OS_WIN
                m_intManager.SetScriptHost(new WrapScriptHost(host), m_instanceId);
#else
                m_intManager.SetScriptHost(Marshal.GetIUnknownForObject(host), m_instanceId);

                m_comRuntime = Marshal.GetComInterfaceForObject(this, typeof(IScriptRuntime));
#endif
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());

                if (e.InnerException != null)
                {
                    Debug.WriteLine(e.InnerException.ToString());
                }

                throw;
            }
        }
Exemplo n.º 5
0
        private static int _appDomainCount = 0;     // only used to give each AppDomain a unique name

        public AppDomainInfo(LoggerBase log, PropellerSettings settings, PropellerModuleSettings moduleSettings, ISettingsSaver saver)
        {
            ModuleSettings     = moduleSettings;
            Saver              = saver;
            _log               = log;
            _activeConnections = 0;

            // Determine the temporary folder that DLLs will be copied to
            var tempFolder = settings.TempFolder ?? Path.GetTempPath();

            Directory.CreateDirectory(tempFolder);

            // Find a new folder to put the DLL/EXE files into
            int j = 1;

            do
            {
                TempPathUsed = Path.Combine(tempFolder, "propeller-tmp-" + (j++));
            }while (Directory.Exists(TempPathUsed));
            Directory.CreateDirectory(TempPathUsed);

            // Copy all the DLLs/EXEs to the temporary folder
            foreach (var sourceFile in
                     new[] { typeof(PropellerEngine), typeof(IPropellerModule), typeof(HttpServer), typeof(Ut) }.Select(type => type.Assembly.Location).Concat(
                         new[] { "*.exe", "*.dll", "*.pdb" }.SelectMany(ext => Directory.EnumerateFiles(Path.GetDirectoryName(moduleSettings.ModuleDll), ext))))
            {
                var destFile = Path.Combine(TempPathUsed, Path.GetFileName(sourceFile));
                if (File.Exists(destFile))
                {
                    _log.Warn(2, "Skipping file {0} because destination file {1} already exists.".Fmt(sourceFile, destFile));
                }
                else
                {
                    _log.Info(2, "Copying file {0} to {1}".Fmt(sourceFile, destFile));
                    File.Copy(sourceFile, destFile);
                }
            }

            // Create an AppDomain
            var setup = new AppDomainSetup {
                ApplicationBase = TempPathUsed, PrivateBinPath = TempPathUsed
            };

            AppDomain   = AppDomain.CreateDomain("Propeller AppDomain #{0}, module {1}".Fmt(_appDomainCount++, moduleSettings.ModuleName), null, setup);
            RunnerProxy = (AppDomainRunner)AppDomain.CreateInstanceAndUnwrap("Propeller", "RT.Propeller.AppDomainRunner");
            RunnerProxy.Init(
                Path.Combine(TempPathUsed, Path.GetFileName(moduleSettings.ModuleDll)),
                moduleSettings.ModuleType,
                moduleSettings.ModuleName,
                moduleSettings.Settings,
                _log,
                saver);

            IEnumerable <string> filters = moduleSettings.MonitorFilters ?? Enumerable.Empty <string>();

            if (RunnerProxy.FileFiltersToBeMonitoredForChanges != null)
            {
                filters = filters.Concat(RunnerProxy.FileFiltersToBeMonitoredForChanges);
            }
            foreach (var filter in filters.Concat(moduleSettings.ModuleDll))
            {
                addFileSystemWatcher(Path.GetDirectoryName(filter), Path.GetFileName(filter));
            }

            UrlMappings = moduleSettings.Hooks.Select(hook => new UrlMapping(hook, Handle, true)).ToArray();

            _log.Info("Module {0} URLs: {1}".Fmt(moduleSettings.ModuleName, moduleSettings.Hooks.JoinString("; ")));
        }
        /// <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;
        }
Exemplo n.º 7
0
    public int RunTest()
    {
        try
        {
            object    t      = null;
            string    s      = (string)t;
            AppDomain domain = AppDomain.CreateDomain("testdomain");
            Remo      server = (Remo)domain.CreateInstanceAndUnwrap(typeof(Test).Assembly.FullName, "Remo");
            if (System.Threading.Thread.GetDomainID() == server.GetDomainId())
            {
                throw new TestException("Object not created in new domain", 1);
            }

            Dada d = new Dada();
            d.p = 22;

            server.Run();
            server.Run2(88, "hola");
            server.Run3(99, d, "adeu");

            string r = server.Run4(200, d, "que");
            CheckValue(r, "vist", 140);

            try {
                server.Run5(200, d, "que");
                throw new TestException("Exception expected", 150);
            }
            catch (Exception ex) {
                CheckValue(ex.Message, "peta", 151);
            }

            Dada d2;
            d = server.Run6(99, out d2, "adeu");
            CheckValue(d.p, 987, 161);
            CheckValue(d2.p, 987, 162);

            d.p = 22;
            d2  = server.Run7(d);
            CheckValue(d.p, 22, 170);
            CheckValue(d2.p, 33, 170);

            byte[] ba = new byte[5];
            for (byte n = 0; n < ba.Length; n++)
            {
                ba [n] = n;
            }

            server.Run8(ba);

            for (int n = 0; n < ba.Length; n++)
            {
                CheckValue(ba[n], (byte)(ba.Length - n), 180);
            }

            StringBuilder sb = new StringBuilder("un");
            server.Run9_1(sb);
            Test.CheckValue(sb, new StringBuilder("un"), 190);

            StringBuilder sb2 = new StringBuilder("prefix");
            StringBuilder sb3 = server.Run9_2(sb2);
            Test.CheckValue(sb2, new StringBuilder("prefix"), 192);
            Test.CheckValue(sb3, new StringBuilder("prefix-middle"), 192);
            StringBuilder sb4 = server.Run9_3(sb3);
            Test.CheckValue(sb3, new StringBuilder("prefix-middle"), 193);
            Test.CheckValue(sb4, new StringBuilder("prefix-middle-end"), 193);
        }
        catch (TestException ex)
        {
            Console.WriteLine("TEST ERROR ({0}): {1}", ex.Code, ex);
            return(ex.Code);
        }
        catch (Exception ex)
        {
            Console.WriteLine("TEST ERROR: " + ex);
            return(-1);
        }
        return(0);
    }
Exemplo n.º 8
0
        private static void Marshalling()
        {
            AppDomain adCallingThreadDomain = Thread.GetDomain();

            string callingDomainName = adCallingThreadDomain.FriendlyName;

            Console.WriteLine("Default AppDomain's friendly name={0}", callingDomainName);

            string exeAssembly = Assembly.GetEntryAssembly().FullName;

            Console.WriteLine("Main assembly={0}", exeAssembly);

            AppDomain ad2 = null;

            // *** DEMO 1:使用Marshal-by-Reference进行跨APPDomain通信 ***
            Console.WriteLine("{0}Demo #1", Environment.NewLine);

            // 新建一个AppDomain(从当前AppDomain继承安全性和配置)
            ad2 = AppDomain.CreateDomain("AD #2", null, null);
            MarshalByRefType mbrt = null;

            // 将我们的程序集加载到新AppDomain中,构造一个对象,把它
            // 封送回我们的AppDomain(实际得到对一个代理的引用)
            mbrt = (MarshalByRefType)
                   ad2.CreateInstanceAndUnwrap(exeAssembly, "MarshalByRefType");

            // CLR 在类型上撒谎了
            Console.WriteLine("Type={0}", mbrt.GetType());

            // 证明得到的是对一个代理对象的引用
            Console.WriteLine("Is proxy={0}", RemotingServices.IsTransparentProxy(mbrt));

            // 看起来像是在MarshalByRefType上调用一个方法,实则不然
            // 我们是在代理类型上调用一个方法,代理使线程切换到拥有对象的
            // 那个AppDomain,并在真实的对象上调用这个方法
            mbrt.SomeMethod();

            // 卸载新的AppDomain
            AppDomain.Unload(ad2);

            // mbrt引用一个有效的代理对象;代理对象引用一个无效的AppDomain
            try
            {
                // 在代理类型上调用一个方法,AppDomain无效,造成抛出异常
                mbrt.SomeMethod();
                Console.WriteLine("Successful call.");
            }
            catch (AppDomainUnloadedException)
            {
                Console.WriteLine("Failed call.");
            }

            // *** DEMO 2:使用Marshal-by-Value进行跨AppDomain通信 ***
            Console.WriteLine("{0}Demo #2", Environment.NewLine);

            // 新建一个AppDomain(从当前AppDomain继承安全性和配置)
            ad2 = AppDomain.CreateDomain("AD #2", null, null);

            // 将我们的程序集加载到新AppDomain中,构造一个对象,把它
            // 封送回我们的AppDomain(实际得到对一个代理的引用)
            mbrt = (MarshalByRefType)
                   ad2.CreateInstanceAndUnwrap(exeAssembly, "MarshalByRefType");

            // 对象的方法返回所返回对象的副本;
            // 对象按值(而非按引用)封送
            MarshalByValType mbvt = mbrt.MethodWithReturn();

            // 证明得到的不是对一个代理对象的引用
            Console.WriteLine("Is proxy={0}", RemotingServices.IsTransparentProxy(mbvt));

            // 看起来是在MarshalByValType上调用一个方法,实际也是如此
            Console.WriteLine("Returned object created " + mbvt.ToString());

            // 卸载新的AppDomain
            AppDomain.Unload(ad2);
            // mbvt引用有效的对象:卸载AppDomain没有影响

            try
            {
                // 我们是在对象上调用一个方法:不会抛出异常
                Console.WriteLine("Returned object created " + mbvt.ToString());
                Console.WriteLine("Successful call.");
            }
            catch (AppDomainUnloadedException)
            {
                Console.WriteLine("Failed call.");
            }

            // DEMO 3: 使用不可封送的类型进行跨AppDomain通信 ***
            Console.WriteLine("{0}Demo #3", Environment.NewLine);

            // 新建一个AppDomain(从当前AppDomain继承安全性和配置)
            ad2 = AppDomain.CreateDomain("AD #2", null, null);
            // 将我们的程序集加载到新AppDomain中,构造一个对象,把它
            // 封送回我们的AppDomain(实际得到对一个代理的引用)
            mbrt = (MarshalByRefType)
                   ad2.CreateInstanceAndUnwrap(exeAssembly, "MarshalByRefType");

            // 对象的方法返回一个不可封送的对象:抛出异常
            NonMarshalableType nmt = mbrt.MethodArgAndReturn(callingDomainName);
            // 这里永远执行不到...
        }
 private static ProxyNancyReferenceProber CreateRemoteReferenceProber(AppDomain appDomain)
 {
     return((ProxyNancyReferenceProber)appDomain.CreateInstanceAndUnwrap(
                typeof(ProxyNancyReferenceProber).Assembly.FullName,
                typeof(ProxyNancyReferenceProber).FullName));
 }
Exemplo n.º 10
0
        /// <summary>
        /// Creates a <see cref="MServer"/> instance.
        /// </summary>
        /// <param name="domain">The domain name</param>
        /// <param name="createNewAppDomain">true if MServerFactory should create a dedicated
        /// AppDomain for the <see cref="MServer"/> instance.</param>
        /// <returns>A <see cref="MServer"/> instance.</returns>
        public static MServer CreateServer(String domain, bool createNewAppDomain)
        {
            if (domain == null)
            {
                throw new ArgumentNullException("domain");
            }

            if (domains.Contains(domain))
            {
                throw new DomainAlreadyExistsException(domain);
            }

            String typeName   = ConfigurationSettings.AppSettings[CustomServerConfigurationKey];
            Type   serverType = null;

            if (typeName != null && typeName != String.Empty)
            {
                // TODO: Allow custom servers..
            }
            else
            {
                serverType = typeof(MDefaultServer);
            }

            if (createNewAppDomain)
            {
                // Lets create a seperated AppDomain for this server

                AppDomain currentDomain = AppDomain.CurrentDomain;

                String baseDir = new FileInfo(currentDomain.BaseDirectory).FullName;

                String configFile = String.Format(
                    "{0}/{1}.config",
                    baseDir, domain);

                AppDomainSetup setup = new AppDomainSetup();

                setup.ApplicationName   = domain;
                setup.ApplicationBase   = currentDomain.SetupInformation.ApplicationBase;
                setup.PrivateBinPath    = currentDomain.SetupInformation.PrivateBinPath;
                setup.ConfigurationFile = configFile;
                // setup.ShadowCopyFiles = "false";
                // setup.ShadowCopyDirectories = appBase;

                Evidence baseEvidence = currentDomain.Evidence;
                Evidence evidence     = new Evidence(baseEvidence);

                AppDomain newDomain = AppDomain.CreateDomain(
                    domain, evidence, setup);

                object remoteInstance = newDomain.CreateInstanceAndUnwrap(
                    serverType.Assembly.FullName, serverType.FullName);

                // Register the domain

                domains.Add(domain, new DomainInfo(domain, remoteInstance as MServer, newDomain));

                // As this already method "unwraps" the target object, its safe
                // to return it - in an "wrapped" object we should invoke the
                // class's constructor

                return((MServer)remoteInstance);
            }
            else
            {
                object localInstance = Activator.CreateInstance(serverType);

                // Register the domain

                domains.Add(domain, new DomainInfo(domain, localInstance as MServer));

                return((MServer)localInstance);
            }
        }
Exemplo n.º 11
0
        public static void Main(string[] args)
        {
            var containers = ContainerAdapterFactory.CreateAdapters().ToArray();
            var benchmarks = BenchmarkFactory.CreateBenchmarks().ToArray();

            var benchmarkResults         = new List <BenchmarkResult>();
            var existingBenchmarkResults = new List <BenchmarkResult>();

            if (args != null && args.Any(a => a.Equals("-update", StringComparison.OrdinalIgnoreCase)))
            {
                existingBenchmarkResults.AddRange(XmlOutputReader.GetExistingBenchmarkResults(benchmarks, containers));
            }

            foreach (var container in containers)
            {
                AppDomain childDomain = null;

                try
                {
                    AppDomainSetup domainSetup = new AppDomainSetup()
                    {
                        ApplicationBase    = AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
                        ConfigurationFile  = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile,
                        ApplicationName    = AppDomain.CurrentDomain.SetupInformation.ApplicationName,
                        LoaderOptimization = LoaderOptimization.MultiDomainHost
                    };

                    childDomain = AppDomain.CreateDomain("AppDomain for " + container.Name, null, domainSetup);

                    ContainerAdapterRuntime runtime = (ContainerAdapterRuntime)childDomain.CreateInstanceAndUnwrap(
                        typeof(ContainerAdapterRuntime).Assembly.FullName,
                        typeof(ContainerAdapterRuntime).FullName);

                    var containerBenchmarkResults = runtime.Run(container.GetType(), existingBenchmarkResults);
                    benchmarkResults.AddRange(containerBenchmarkResults);
                }
                catch (Exception ex)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(
                        " Container '{0}' failed: {1}",
                        container.Name,
                        ex.Message);
                    Console.ResetColor();
                }
                finally
                {
                    if (childDomain != null)
                    {
                        AppDomain.Unload(childDomain);
                    }

                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    GC.Collect();
                }

                Console.WriteLine();
            }

            XmlOutputReader.AddHistoricBenchmarkResults(benchmarkResults);

            IOutput output = new MultiOutput(
                new XmlOutput(),
                new HtmlOutput(),
                new MarkdownOutput(),
                new CsvOutput(),
                new CsvRateOutput(),
                new ChartOutput(),
                new ZipOutput(),
                new JsonOutput(),
                new GithubPagesOutput());

            output.Create(benchmarks, benchmarkResults);

            Console.WriteLine("Done");
        }
Exemplo n.º 12
0
        private static AppDomainProxy CreateProxy(AppDomain domain)
        {
            Type typeProxy = typeof(AppDomainProxy);

            return((AppDomainProxy)domain.CreateInstanceAndUnwrap(typeProxy.Assembly.FullName, typeProxy.FullName));
        }
Exemplo n.º 13
0
        /// <summary>
        /// Discovers all SolidDna plug-ins
        /// </summary>
        /// <param name="addinPath">The path to the add-in that is calling this setup (typically acquired using GetType().Assembly.Location)</param>
        /// <param name="loadAll">True to find all plug-ins in the same folder as the SolidDna dll</param>
        /// <param name="log">True to log the output of the loading. Use false when registering for COM</param>
        /// <returns></returns>
        public static List <SolidPlugIn> SolidDnaPlugIns(string addinPath, bool log, bool loadAll = true)
        {
            // Create new empty list
            var assemblies = new List <SolidPlugIn>();

            // Find all dll's in the same directory
            if (loadAll)
            {
                // Log it
                if (log)
                {
                    Logger.LogDebugSource($"Loading all PlugIns...");
                }

                if (UseDetachedAppDomain)
                {
                    // Invalid combination... cannot load all from cross domain
                    // (we don't create the PlugInDetails class for each item
                    Debugger.Break();
                }

                // Clear old list
                PlugInDetails = new Dictionary <string, List <PlugInDetails> >();

                // Add new based on if found
                foreach (var path in Directory.GetFiles(addinPath, "*.dll", SearchOption.TopDirectoryOnly))
                {
                    GetPlugIns(path, (plugin) =>
                    {
                        // Log it
                        if (log)
                        {
                            Logger.LogDebugSource($"Found plugin {plugin.AddInTitle} in {path}");
                        }

                        assemblies.Add(plugin);
                    });
                }
            }
            // Or load explicit ones
            else
            {
                // Log it
                if (log)
                {
                    Logger.LogDebugSource($"Explicitly loading {PlugInDetails?.Count} PlugIns...");
                }

                // For each assembly
                foreach (var p in PlugInDetails)
                {
                    // And each plug-in inside it
                    foreach (var path in p.Value)
                    {
                        try
                        {
                            // If we are called in the main domain, cross-load
                            if (UseDetachedAppDomain)
                            {
                                // Log it
                                if (log)
                                {
                                    Logger.LogDebugSource($"Cross-domain loading PlugIn {path.AssemblyFullName}...");
                                }

                                // Create instance of the plug-in via cross-domain and cast back
                                var plugin = (dynamic)PlugInAppDomain.CreateInstanceAndUnwrap(
                                    path.AssemblyFullName,
                                    path.TypeFullName);

                                // If we got it, add it to the list
                                if (plugin != null)
                                {
                                    assemblies.Add(plugin);
                                }
                                else if (log)
                                {
                                    // Log error
                                    Logger.LogErrorSource($"Failed to create instance of PlugIn {path.AssemblyFullName}");
                                }
                            }
                            else
                            {
                                GetPlugIns(path.FullPath, (plugin) =>
                                {
                                    // Log it
                                    if (log)
                                    {
                                        Logger.LogDebugSource($"Found plugin {plugin.AddInTitle} in {path}");
                                    }

                                    assemblies.Add(plugin);
                                });
                            }
                        }
                        catch (Exception ex)
                        {
                            // Log error
                            //   Logger?.LogCriticalSource($"Unexpected error: {ex}");
                        }
                    }
                }
            }

            // Log it
            if (log)
            {
                Logger.LogDebugSource($"Loaded {assemblies?.Count} plug-ins from {addinPath}");
            }

            return(assemblies);
        }
Exemplo n.º 14
0
    public static int Main(string [] args)
    {
        AppDomain domain = AppDomain.CreateDomain("newdomain");
        Test      test   = (Test)domain.CreateInstanceAndUnwrap(typeof(Test).Assembly.FullName, typeof(Test).FullName);
        bool      didAbort;
        Test      testHere = new Test();

        if (!RemotingServices.IsTransparentProxy(test))
        {
            Console.WriteLine("test is no proxy");
            return(5);
        }

        try {
            test.abortOtherIndirect(testHere);
        } catch (ThreadAbortException e) {
            object state = e.ExceptionState;
            Thread.ResetAbort();
            if ((JustSomeClass)state != testHere.other)
            {
                Console.WriteLine("other class not preserved in state");
                return(16);
            }
        }

        try {
            didAbort = false;
            test.abortString();
        } catch (ThreadAbortException e) {
            object state;
            state = e.ExceptionState;
            Thread.ResetAbort();
            didAbort = true;
            if (state == null)
            {
                Console.WriteLine("state is null");
                return(13);
            }
            else
            {
                if (RemotingServices.IsTransparentProxy(state))
                {
                    Console.WriteLine("state is proxy");
                    return(1);
                }
                if (!((string)state).Equals("bla"))
                {
                    Console.WriteLine("state is wrong: " + (string)state);
                    return(2);
                }
            }
            if (RemotingServices.IsTransparentProxy(e))
            {
                Console.WriteLine("exception is proxy");
                return(3);
            }
            if (test.getState() != null)
            {
                Console.WriteLine("have state");
                return(12);
            }
        }
        if (!didAbort)
        {
            Console.WriteLine("no abort");
            return(4);
        }

        try {
            didAbort = false;
            test.abortProxy();
        } catch (ThreadAbortException e) {
            object state;
            state = e.ExceptionState;
            Thread.ResetAbort();
            didAbort = true;
            if (state == null)
            {
                Console.WriteLine("state is null");
                return(14);
            }
            else
            {
                if (!RemotingServices.IsTransparentProxy(state))
                {
                    Console.WriteLine("state is not proxy");
                    return(6);
                }
                if (((Test)state).getInt() != 123)
                {
                    Console.WriteLine("state doesn't work");
                    return(15);
                }
            }
            if (RemotingServices.IsTransparentProxy(e))
            {
                Console.WriteLine("exception is proxy");
                return(7);
            }
        }
        if (!didAbort)
        {
            Console.WriteLine("no abort");
            return(8);
        }

        try {
            didAbort = false;
            test.abortOther();
        } catch (ThreadAbortException e) {
            object state    = null;
            bool   stateExc = false;

            didAbort = true;

            try {
                state = e.ExceptionState;
                Console.WriteLine("have state");
            } catch (Exception) {
                stateExc = true;

                /* FIXME: if we put this after the try/catch, mono
                 * quietly quits */
                Thread.ResetAbort();
            }
            if (!stateExc)
            {
                Console.WriteLine("no state exception");
                return(9);
            }

            if (RemotingServices.IsTransparentProxy(e))
            {
                Console.WriteLine("exception is proxy");
                return(10);
            }
        }
        if (!didAbort)
        {
            Console.WriteLine("no abort");
            return(11);
        }

        // #539394
        // Calling Thread.Abort () from a remoting call throws a ThreadAbortException which
        // cannot be caught because the exception handling code is confused by the domain
        // transitions
        bool res = false;

        Thread thread = new Thread(delegate() {
            AppDomain d = AppDomain.CreateDomain("foo");

            var t = (Test1)d.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName,
                                                     "Test1");
            res = t.Run();
        });

        thread.Start();
        thread.Join();

        if (!res)
        {
            return(12);
        }

        Console.WriteLine("done");

        return(0);
    }
Exemplo n.º 15
0
        public static T CreateInstance <T>(AppDomain domain)
        {
            T obj = (T)domain.CreateInstanceAndUnwrap(typeof(T).Assembly.FullName, typeof(T).FullName);

            return(obj);
        }
Exemplo n.º 16
0
Arquivo: t46.cs Projeto: nlhepler/mono
	static Program GetRemote (AppDomain domain)
	{
		Program test = (Program) domain.CreateInstanceAndUnwrap (
			typeof (Program).Assembly.FullName,
			typeof (Program).FullName, new object [0]);
		return test;
	}
        static SingleRunner CreateRunnerInAppDomain()
        {
            var rc = (SingleRunner)_ad.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(SingleRunner).FullName);

            return(rc);
        }
Exemplo n.º 18
0
 public object CreateObject(string assemblyName, string typeName)
 {
     return(appDomain.CreateInstanceAndUnwrap(assemblyName, typeName));
 }
Exemplo n.º 19
0
 /// <summary>
 /// Loads the FSharpLint worker from FSharpLint.Application in a
 /// separate app domain and returns a proxy to the worker.
 /// </summary>
 /// <returns>Proxy to the worker from FSharpLint.Application.</returns>
 private IFSharpLintWorker GetWorker(AppDomain appDomain)
 {
     return((FSharpLint.Worker.IFSharpLintWorker)appDomain.CreateInstanceAndUnwrap("FSharpLint.Application", "FSharpLint.Application.FSharpLintWorker+FSharpLintWorker"));
 }
Exemplo n.º 20
0
    static int Main(string [] args)
    {
        string assembly     = null;
        string directory    = null;
        string lockfile     = null;
        string name         = null;
        string logname      = null;
        var    assebmlyArgs = new List <string>();

        foreach (string s in args)
        {
            if (s.Length > 3 && s [0] == '-' && s [2] == ':')
            {
                string arg = s.Substring(3);

                switch (Char.ToLower(s [1]))
                {
                case 'd': directory = arg; break;

                case 'l': lockfile = arg; break;

                case 'n': name = arg; break;

                case 'm': logname = arg; break;

                default: Usage(); break;
                }
            }
            else
            {
                if (assembly != null)
                {
                    assebmlyArgs.Add(s);
                }
                else
                {
                    assembly = s;
                }
            }
        }

        if (logname == null)
        {
            logname = assembly;
        }

        if (assembly == null)
        {
            error(logname, "Assembly name is missing");
            Usage();
        }

        if (directory != null)
        {
            if (Syscall.chdir(directory) != 0)
            {
                error(logname, "Could not change to directory {0}", directory);
                return(1);
            }
        }

        // Use lockfile to allow only one instance
        if (lockfile == null)
        {
            lockfile = String.Format("/tmp/{0}.lock", Path.GetFileName(assembly));
        }

        int lfp = Syscall.open(lockfile, OpenFlags.O_RDWR | OpenFlags.O_CREAT | OpenFlags.O_EXCL,
                               FilePermissions.S_IRUSR | FilePermissions.S_IWUSR | FilePermissions.S_IRGRP);

        if (lfp < 0)
        {
            // Provide some useful info
            if (File.Exists(lockfile))
            {
                error(logname, String.Format("Lock file already exists: {0}", lockfile));
            }
            else
            {
                error(logname, String.Format("Cannot open/create lock file exclusively: {0}", lockfile));
            }
            return(1);
        }

        if (Syscall.lockf(lfp, LockfCommand.F_TLOCK, 0) < 0)
        {
            info(logname, "Daemon is already running.");
            return(0);
        }

        try {
            // Write pid to lock file
            string pid = Syscall.getpid().ToString() + Environment.NewLine;
            IntPtr buf = Marshal.StringToCoTaskMemAnsi(pid);
            Syscall.write(lfp, buf, (ulong)pid.Length);
            Marshal.FreeCoTaskMem(buf);

            // Create new AppDomain to run service
            AppDomainSetup setup = new AppDomainSetup();
            setup.ApplicationBase   = Environment.CurrentDirectory;
            setup.ConfigurationFile = Path.Combine(Environment.CurrentDirectory, assembly + ".config");
            setup.ApplicationName   = logname;

            AppDomain         newDomain = AppDomain.CreateDomain(logname, AppDomain.CurrentDomain.Evidence, setup);
            MonoServiceRunner rnr       = newDomain.CreateInstanceAndUnwrap(
                typeof(MonoServiceRunner).Assembly.FullName,
                typeof(MonoServiceRunner).FullName,
                true,
                BindingFlags.Default,
                null,
                new object [] { assembly, name, logname, assebmlyArgs.ToArray() },
                null, null, null) as MonoServiceRunner;

            if (rnr == null)
            {
                error(logname, "Internal Mono Error: Could not create MonoServiceRunner.");
                return(1);
            }

            return(rnr.StartService());
        } finally {
            // Remove lock file when done
            if (File.Exists(lockfile))
            {
                File.Delete(lockfile);
            }
        }
    }
Exemplo n.º 21
0
        /// <summary>
        /// Load the script from an assembly into an AppDomain.
        /// </summary>
        /// <param name='dom'></param>
        /// <param name='assembly'></param>
        /// <param name='stateSource'></param>
        /// <returns>false if load failed, true if suceeded</returns>
        public bool Load(AppDomain dom, string assembly, StateSource stateSource)
        {
            m_Assembly    = assembly;
            m_stateSource = stateSource;

            ApiManager am = new ApiManager();

            foreach (string api in am.GetApis())
            {
                m_Apis[api] = am.CreateApi(api);
                m_Apis[api].Initialize(Engine, Part, ScriptTask, m_coopSleepHandle);
            }

            try
            {
                object[] constructorParams;

                Assembly scriptAssembly = dom.Load(Path.GetFileNameWithoutExtension(assembly));
                Type     scriptType     = scriptAssembly.GetType("SecondLife.XEngineScript");

                if (scriptType != null)
                {
                    constructorParams = new object[] { m_coopSleepHandle };
                }
                else if (!m_coopTermination)
                {
                    scriptType        = scriptAssembly.GetType("SecondLife.Script");
                    constructorParams = null;
                }
                else
                {
                    m_log.ErrorFormat(
                        "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}.  You must remove all existing {6}* script DLL files before using enabling co-op termination"
                        + ", either by setting DeleteScriptsOnStartup = true in [XEngine] for one run"
                        + " or by deleting these files manually.",
                        ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, assembly);

                    return(false);
                }

                //                m_log.DebugFormat(
                //                    "[SCRIPT INSTANCE]: Looking to load {0} from assembly {1} in {2}",
                //                    scriptType.FullName, Path.GetFileNameWithoutExtension(assembly), Engine.World.Name);

                if (dom != System.AppDomain.CurrentDomain)
                {
                    m_Script
                        = (IScript)dom.CreateInstanceAndUnwrap(
                              Path.GetFileNameWithoutExtension(assembly),
                              scriptType.FullName,
                              false,
                              BindingFlags.Default,
                              null,
                              constructorParams,
                              null,
                              null,
                              null);
                }
                else
                {
                    m_Script
                        = (IScript)scriptAssembly.CreateInstance(
                              scriptType.FullName,
                              false,
                              BindingFlags.Default,
                              null,
                              constructorParams,
                              null,
                              null);
                }

                //ILease lease = (ILease)RemotingServices.GetLifetimeService(m_Script as ScriptBaseClass);
                //RemotingServices.GetLifetimeService(m_Script as ScriptBaseClass);
                //                lease.Register(this);
            }
            catch (Exception e)
            {
                m_log.ErrorFormat(
                    "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}.  Error loading assembly {6}.  Exception {7}{8}",
                    ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, assembly, e.Message, e.StackTrace);

                return(false);
            }

            try
            {
                foreach (KeyValuePair <string, IScriptApi> kv in m_Apis)
                {
                    m_Script.InitApi(kv.Key, kv.Value);
                }

                //                // m_log.Debug("[Script] Script instance created");

                Part.SetScriptEvents(ItemID,
                                     (int)m_Script.GetStateEventFlags(State));
            }
            catch (Exception e)
            {
                m_log.ErrorFormat(
                    "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}.  Error initializing script instance.  Exception {6}{7}",
                    ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, e.Message, e.StackTrace);

                return(false);
            }

            m_SaveState = true;

            string savedState = Path.Combine(Path.GetDirectoryName(assembly),
                                             ItemID.ToString() + ".state");

            if (File.Exists(savedState))
            {
                string xml = String.Empty;

                try
                {
                    FileInfo fi   = new FileInfo(savedState);
                    int      size = (int)fi.Length;
                    if (size < 512000)
                    {
                        using (FileStream fs = File.Open(savedState,
                                                         FileMode.Open, FileAccess.Read, FileShare.None))
                        {
                            Byte[] data = new Byte[size];
                            fs.Read(data, 0, size);

                            xml = Encoding.UTF8.GetString(data);

                            ScriptSerializer.Deserialize(xml, this);

                            AsyncCommandManager.CreateFromData(Engine,
                                                               LocalID, ItemID, ObjectID,
                                                               PluginData);

                            //                            m_log.DebugFormat("[Script] Successfully retrieved state for script {0}.{1}", PrimName, m_ScriptName);

                            Part.SetScriptEvents(ItemID,
                                                 (int)m_Script.GetStateEventFlags(State));

                            if (!Running)
                            {
                                m_startOnInit = false;
                            }

                            Running = false;

                            // we get new rez events on sim restart, too
                            // but if there is state, then we fire the change
                            // event

                            // We loaded state, don't force a re-save
                            m_SaveState             = false;
                            m_startedFromSavedState = true;
                        }
                    }
                    else
                    {
                        m_log.WarnFormat(
                            "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}.  Unable to load script state file {6}.  Memory limit exceeded.",
                            ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, savedState);
                    }
                }
                catch (Exception e)
                {
                    m_log.ErrorFormat(
                        "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}.  Unable to load script state file {6}.  XML is {7}.  Exception {8}{9}",
                        ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, savedState, xml, e.Message, e.StackTrace);
                }
            }
            //            else
            //            {
            //                ScenePresence presence = Engine.World.GetScenePresence(part.OwnerID);

            //                if (presence != null && (!postOnRez))
            //                    presence.ControllingClient.SendAgentAlertMessage("Compile successful", false);

            //            }

            return(true);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Initializes the current reader with respect to its environment.
        /// </summary>
        public void Initialize()
        {
            AppDomain tempDomainToLoadAssembly = null;
            string    tempDomainName           = "AppInsightsDomain-" + Guid.NewGuid().ToString();
            Stopwatch sw = Stopwatch.StartNew();

            // The following approach is used to load Microsoft.WindowsAzure.ServiceRuntime assembly and read the required information.
            // Create a new AppDomain and try to load the ServiceRuntime dll into it.
            // Then using reflection, read and save all the properties we care about and unload the new AppDomain.
            // This approach ensures that if the app is running in Azure Cloud Service, we read the necessary information deterministically
            // and without interfering with any customer code which could be loading same/different version of Microsoft.WindowsAzure.ServiceRuntime.dll.
            try
            {
                AppDomainSetup domaininfo = new AppDomainSetup();
                domaininfo.ApplicationBase = Path.GetDirectoryName(AzureRoleEnvironmentContextReader.AssemblyLoaderType.Assembly.Location);

                // Create a new AppDomain
                tempDomainToLoadAssembly = AppDomain.CreateDomain(tempDomainName, null, domaininfo);
                WindowsServerEventSource.Log.AzureRoleEnvironmentContextReaderAppDomainTroubleshoot(tempDomainName, " Successfully  created with ApplicationBase: " + domaininfo.ApplicationBase);

                // Load the RemoteWorker assembly to the new domain
                tempDomainToLoadAssembly.Load(typeof(AzureServiceRuntimeAssemblyLoader).Assembly.FullName);
                WindowsServerEventSource.Log.AzureRoleEnvironmentContextReaderAppDomainTroubleshoot(tempDomainName, " Successfully loaded assembly: " + typeof(AzureServiceRuntimeAssemblyLoader).Assembly.FullName);

                // Any method invoked on this object will be executed in the newly created AppDomain.
                AzureServiceRuntimeAssemblyLoader remoteWorker = (AzureServiceRuntimeAssemblyLoader)tempDomainToLoadAssembly.CreateInstanceAndUnwrap(AzureRoleEnvironmentContextReader.AssemblyLoaderType.Assembly.FullName, AzureRoleEnvironmentContextReader.AssemblyLoaderType.FullName);

                bool success = remoteWorker.ReadAndPopulateContextInformation(out this.roleName, out this.roleInstanceName);
                if (success)
                {
                    WindowsServerEventSource.Log.AzureRoleEnvironmentContextReaderInitializedSuccess(this.roleName, this.roleInstanceName);
                }
                else
                {
                    WindowsServerEventSource.Log.AzureRoleEnvironmentContextReaderInitializationFailed();
                }
            }
            catch (Exception ex)
            {
                WindowsServerEventSource.Log.UnknownErrorOccured("AzureRoleEnvironmentContextReader Initialize", ex.ToString());
            }
            finally
            {
                try
                {
                    if (tempDomainToLoadAssembly != null)
                    {
                        AppDomain.Unload(tempDomainToLoadAssembly);
                        WindowsServerEventSource.Log.AzureRoleEnvironmentContextReaderAppDomainTroubleshoot(tempDomainName, " Successfully  Unloaded.");
                        WindowsServerEventSource.Log.AzureRoleEnvironmentContextReaderInitializationDuration(sw.ElapsedMilliseconds);
                    }
                }
                catch (Exception ex)
                {
                    WindowsServerEventSource.Log.AzureRoleEnvironmentContextReaderAppDomainTroubleshoot(tempDomainName, "AppDomain  unload failed with exception: " + ex.ToString());
                }
            }
        }
 private static T CreateInstance <T>(AppDomain domain)
 {
     return((T)domain.CreateInstanceAndUnwrap(typeof(T).Assembly.FullName,
                                              typeof(T).FullName));
 }
Exemplo n.º 24
0
        protected virtual void  OnGUI()
        {
            this.exposersFolder = EditorGUILayout.TextField("Exposers Folder", this.exposersFolder);
            EditorGUILayout.HelpBox("After generating, this current instance of Unity Editor will be unstable and might crash anytime.", MessageType.Warning);

            if (GUILayout.Button("Generate") == true)
            {
                List <ExposedClass> classes = new List <ExposerGenerator.ExposedClass>();

                // Manual init
                classes.Add(new ExposedClass()
                {
                    type     = typeof(Renderer),
                    excluded = new List <string>()
                    {
                        "material", "materials", "sharedMaterial"
                    }
                });
                classes.Add(new ExposedClass()
                {
                    type     = typeof(MeshFilter),
                    excluded = new List <string>()
                    {
                        "mesh"
                    }
                });
                classes.Add(new ExposedClass()
                {
                    type     = typeof(Collider),
                    excluded = new List <string>()
                    {
                        "material"
                    }
                });
                classes.Add(new ExposedClass()
                {
                    type     = typeof(Transform),
                    included = new List <string>()
                    {
                        "localPosition", "localEulerAngles", "localScale"
                    }
                });

                Dictionary <string, string> installs = new Dictionary <string, string>();

                NGUnityDetectorWindow.GetInstalls(installs);

                foreach (var pair in installs)
                {
                    string         dllPath    = Path.Combine(pair.Value, @"Editor\Data\Managed\UnityEngine.dll");
                    AppDomainSetup domaininfo = new AppDomainSetup();
                    domaininfo.ApplicationBase = @"Library\ScriptAssemblies";
                    Evidence  adevidence = AppDomain.CurrentDomain.Evidence;
                    AppDomain domain     = AppDomain.CreateDomain("MyDomain", adevidence, domaininfo);

                    Type type2 = typeof(ProxyDomain);
                    var  value = (ProxyDomain)domain.CreateInstanceAndUnwrap(type2.Assembly.FullName, type2.FullName);

                    value.GetAssembly(dllPath);

                    Assembly unityEngine = Assembly.LoadFile(dllPath);
                    Debug.Log("Assembly found at " + dllPath);

                    for (int i = 0; i < classes.Count; i++)
                    {
                        Type           type = unityEngine.GetType(classes[i].type.FullName, true);
                        PropertyInfo[] pis  = type.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);

                        for (int j = 0; j < pis.Length; j++)
                        {
                            if (classes[i].included.Count > 0 && classes[i].included.Contains(pis[j].Name) == false)
                            {
                                continue;
                            }

                            if (classes[i].excluded.Contains(pis[j].Name) == true ||
                                pis[j].IsDefined(typeof(ObsoleteAttribute), false) == true ||
                                pis[j].IsDefined(typeof(HideInInspector), false) == true ||
                                pis[j].GetIndexParameters().Length != 0 ||                 // Skip indexer.
                                pis[j].CanRead == false ||                                 // Skip prop without both get/set.
                                pis[j].CanWrite == false ||
                                this.CanExposeTypeInInspector(pis[j].PropertyType) == false)
                            {
                                continue;
                            }

                            List <string> versions;

                            if (classes[i].properties.TryGetValue(pis[j].Name, out versions) == false)
                            {
                                versions = new List <string>();
                                classes[i].properties.Add(pis[j].Name, versions);
                            }

                            versions.Add(pair.Key);
                        }

                        FieldInfo[] fis = type.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);

                        for (int j = 0; j < fis.Length; j++)
                        {
                            if (classes[i].included.Count > 0 && classes[i].included.Contains(fis[j].Name) == false)
                            {
                                continue;
                            }

                            if (classes[i].excluded.Contains(fis[j].Name) == true ||
                                fis[j].IsDefined(typeof(ObsoleteAttribute), false) == true ||
                                fis[j].IsDefined(typeof(HideInInspector), false) == true ||
                                this.CanExposeTypeInInspector(fis[j].FieldType) == false)
                            {
                                continue;
                            }

                            List <string> versions;

                            if (classes[i].fields.TryGetValue(fis[j].Name, out versions) == false)
                            {
                                versions = new List <string>();
                                classes[i].fields.Add(fis[j].Name, versions);
                            }

                            versions.Add(pair.Key);
                        }
                    }

                    AppDomain.Unload(domain);
                }

                string latestUnityVersion = "0";

                foreach (var pair in installs)
                {
                    if ((pair.Key[0] == '2' && (latestUnityVersion[0] == '4' || latestUnityVersion[0] == '5')) ||
                        (pair.Key[0] == latestUnityVersion[0] && latestUnityVersion.CompareTo(pair.Key) < 0) ||
                        latestUnityVersion[0] == '0')
                    {
                        latestUnityVersion = pair.Key;
                    }
                }

                latestUnityVersion = latestUnityVersion.Substring(0, latestUnityVersion.LastIndexOf('.'));

                StringBuilder linkBuffer = Utility.GetBuffer();

                linkBuffer.AppendLine("<linker>");
                linkBuffer.AppendLine("	<assembly fullname=\"UnityEngine\">");
                linkBuffer.AppendLine("		<type fullname=\""+ typeof(GameObject).FullName + "\" preserve=\"all\"/>");

                Directory.CreateDirectory(this.exposersFolder);

                string path;

                for (int i = 0; i < classes.Count; i++)
                {
                    StringBuilder buffer = Utility.GetBuffer();

                    linkBuffer.AppendLine("		<type fullname=\""+ classes[i].type.FullName + "\" preserve=\"all\"/>");

                    buffer.Append(@"// File auto-generated by ExposerGenerator.
using System.Reflection;
using UnityEngine;

namespace NGTools.NGRemoteScene
{
	internal sealed class "     + classes[i].type.Name + @"Exposer : ComponentExposer
	{
		public	"         + classes[i].type.Name + @"Exposer() : base(typeof(" + classes[i].type.Name + @"))
		{
		}"        );

                    this.AddMembers(buffer, "Property", classes[i].properties, latestUnityVersion);
                    this.AddMembers(buffer, "Field", classes[i].fields, latestUnityVersion);

                    buffer.Append(@"
	}
}");

                    Debug.Log("Type " + classes[i].type.FullName);
                    foreach (var item in classes[i].properties)
                    {
                        Debug.Log("Property " + item.Key + " in " + string.Join(", ", item.Value.ToArray()));
                    }
                    foreach (var item in classes[i].fields)
                    {
                        Debug.Log("Field " + item.Key + " in " + string.Join(", ", item.Value.ToArray()));
                    }

                    path = Path.Combine(this.exposersFolder, classes[i].type.Name + "Exposer.cs");

                    File.WriteAllText(path, Utility.ReturnBuffer(buffer));
                    Debug.Log("Exposer generated at \"" + path + "\".");
                }

                linkBuffer.AppendLine("	</assembly>");
                linkBuffer.AppendLine("</linker>");

                path = Path.Combine(this.exposersFolder, "link.xml");
                Debug.Log("Links generated at \"" + path + "\".");
                File.WriteAllText(Path.Combine(this.exposersFolder, "link.xml"), Utility.ReturnBuffer(linkBuffer));
            }
        }
Exemplo n.º 25
0
        static void TestCAS(string connectString1, string connectString2)
        {
            // Create permission set for sandbox AppDomain.
            // This example only allows execution.
            PermissionSet permissions = new PermissionSet(PermissionState.None);

            permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));

            // Create sandbox AppDomain with permission set that only allows execution,
            // and has no SqlClientPermissions.
            AppDomainSetup appDomainSetup = new AppDomainSetup();

            appDomainSetup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            AppDomain firstDomain = AppDomain.CreateDomain("NoSqlPermissions", null, appDomainSetup, permissions);

            // Create helper object in sandbox AppDomain so that code can be executed in that AppDomain.
            Type helperType = typeof(PartialTrustHelper);
            PartialTrustHelper firstHelper = (PartialTrustHelper)firstDomain.CreateInstanceAndUnwrap(helperType.Assembly.FullName, helperType.FullName);

            try {
                // Attempt to open a connection in the sandbox AppDomain.
                // This is expected to fail.
                firstHelper.TestConnectionOpen(connectString1);
                Console.WriteLine("Connection opened, unexpected.");
            }
            catch (System.Security.SecurityException ex) {
                Console.WriteLine("Failed, as expected: {0}",
                                  ex.FirstPermissionThatFailed);

                // Uncomment the following line to see Exception details.
                // Console.WriteLine("BaseException: " + ex.GetBaseException());
            }

            // Add permission for a specific connection string.
            SqlClientPermission sqlPermission = new SqlClientPermission(PermissionState.None);

            sqlPermission.Add(connectString1, "", KeyRestrictionBehavior.AllowOnly);

            permissions.AddPermission(sqlPermission);

            AppDomain          secondDomain = AppDomain.CreateDomain("OneSqlPermission", null, appDomainSetup, permissions);
            PartialTrustHelper secondHelper = (PartialTrustHelper)secondDomain.CreateInstanceAndUnwrap(helperType.Assembly.FullName, helperType.FullName);

            // Try connection open again, it should succeed now.
            try {
                secondHelper.TestConnectionOpen(connectString1);
                Console.WriteLine("Connection opened, as expected.");
            }
            catch (System.Security.SecurityException ex) {
                Console.WriteLine("Unexpected failure: {0}", ex.Message);
            }

            // Try a different connection string. This should fail.
            try {
                secondHelper.TestConnectionOpen(connectString2);
                Console.WriteLine("Connection opened, unexpected.");
            }
            catch (System.Security.SecurityException ex) {
                Console.WriteLine("Failed, as expected: {0}", ex.Message);
            }
        }
Exemplo n.º 26
0
        public static T CreateObject <T>(this AppDomain domain) where T : MarshalByRefObject
        {
            Type type = typeof(T);

            return((T)domain.CreateInstanceAndUnwrap(type.Assembly.FullName, type.FullName));
        }
 public NewDomainTestHelper(AppDomainSetup setupInformation)
 {
     domain     = AppDomain.CreateDomain("TestDomain", AppDomain.CurrentDomain.Evidence, setupInformation);
     testObject = (T)domain.CreateInstanceAndUnwrap(typeof(T).Assembly.FullName, typeof(T).FullName);
 }
Exemplo n.º 28
0
        /// <summary>
        /// This is used to create the assembly loader instance.
        /// </summary>
        /// <param name="project">The project from which to get the
        /// necessary dependency information.</param>
        /// <returns>Returns the assembly loader instance</returns>
        public static AssemblyLoader CreateAssemblyLoader(
            SandcastleProject project)
        {
            string[] files;
            string   dirName, fileSpec, sourcePath;
            int      idx;

            if (loader == null)
            {
                AppDomain appDomain = AppDomain.CreateDomain(
                    "SHFBNamespaceInfo");

                loader = (AssemblyLoader)appDomain.CreateInstanceAndUnwrap(
                    typeof(AssemblyLoader).Assembly.FullName,
                    typeof(AssemblyLoader).FullName, false,
                    BindingFlags.NonPublic | BindingFlags.Instance, null,
                    new object[0], CultureInfo.InvariantCulture,
                    new object[0], AppDomain.CurrentDomain.Evidence);

                loader.AppDomain = appDomain;

                foreach (DocumentAssembly da in project.Assemblies)
                {
                    if (!da.CommentsOnly)
                    {
                        loader.AddDependency(da.AssemblyPath);
                    }
                }

                foreach (DependencyItem di in project.Dependencies)
                {
                    sourcePath = di.DependencyPath;

                    if (!sourcePath.StartsWith("GAC:"))
                    {
                        if (sourcePath.IndexOfAny(new char[] { '*', '?' }) == -1)
                        {
                            loader.AddDependency(sourcePath);
                        }
                        else
                        {
                            idx      = sourcePath.LastIndexOf('\\');
                            dirName  = sourcePath.Substring(0, idx);
                            fileSpec = sourcePath.Substring(idx + 1);

                            files = Directory.GetFiles(dirName, fileSpec);

                            foreach (string name in files)
                            {
                                if (name.EndsWith(".dll") || name.EndsWith(".exe"))
                                {
                                    loader.AddDependency(name);
                                }
                            }
                        }
                    }
                }
            }

            return(loader);
        }
 public NewDomainTestHelper(AppDomainSetup setupInformation, PermissionSet permissionSet, params StrongName[] fullTrustAssemblies)
 {
     domain     = AppDomain.CreateDomain("TestDomain", null, setupInformation, permissionSet, fullTrustAssemblies);
     testObject = (T)domain.CreateInstanceAndUnwrap(typeof(T).Assembly.FullName, typeof(T).FullName);
 }
Exemplo n.º 30
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 Microsoft.Build.* assemblies.
                            appDomainInfo.ApplicationBase   = BuildEnvironmentHelper.Instance.CurrentMSBuildToolsDirectory;
                            appDomainInfo.ConfigurationFile = BuildEnvironmentHelper.Instance.CurrentMSBuildConfigurationFile;
                        }

                        AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolver;
                        s_resolverLoadedType = loadedType;

                        taskAppDomain = AppDomain.CreateDomain(isOutOfProc ? "taskAppDomain (out-of-proc)" : "taskAppDomain (in-proc)", null, appDomainInfo);

                        if (loadedType.LoadedAssembly != null)
                        {
                            taskAppDomain.Load(loadedType.LoadedAssembly.GetName());
                        }

#if FEATURE_APPDOMAIN_UNHANDLED_EXCEPTION
                        // Hook up last minute dumping of any exceptions
                        taskAppDomain.UnhandledException += 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
            }
        }
Exemplo n.º 31
0
        public static bool RunService(out string msg)
        {
            bool retValue = false;

            msg = "";

            try
            {
                string.Format("启动位于 {0} 位置的 {1} 服务,并启动实例: {2}",
                              ServiceContext.Current.ContentPath,
                              ServiceContext.Current.Name,
                              ServiceContext.Current.TargetType)
                .Info();

                AppDomainSetup oSetup = new AppDomainSetup();
                oSetup.ApplicationName = ServiceContext.Current.Name;
                oSetup.ApplicationBase = ServiceContext.Current.ContentPath;

                //oSetup.PrivateBinPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "private");
                oSetup.CachePath = Path.Combine(Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory.TrimEnd(new char[] { '\\' })).FullName,
                                                "Cache");
                oSetup.ShadowCopyFiles       = "true"; //启用影像复制程序集
                oSetup.ShadowCopyDirectories = oSetup.ApplicationBase;
                oSetup.ConfigurationFile     = Path.Combine(oSetup.ApplicationBase, ServiceContext.Current.AssemblyName + ".dll.config");
                oSetup.PrivateBinPath        = oSetup.ApplicationBase;

                string.Format("基础路径:{0}", oSetup.ApplicationBase).Info();
                string.Format("BIN路径:{0}", oSetup.PrivateBinPath).Info();
                string.Format("镜像路径:{0}", oSetup.ShadowCopyDirectories).Info();
                string.Format("缓存路径:{0}", oSetup.CachePath).Info();
                string.Format("配置文件:{0}", oSetup.ConfigurationFile).Info();

                AppDomain newDomain = AppDomain.CreateDomain(ServiceContext.Current.Name,
                                                             AppDomain.CurrentDomain.Evidence,
                                                             oSetup);

                newDomain.SetData("logRoot",
                                  Path.Combine(
                                      Directory.GetParent(
                                          AppDomain.CurrentDomain.BaseDirectory.TrimEnd(new char[] { '\\' })).FullName,
                                      "logs"));

                IService service = newDomain.CreateInstanceAndUnwrap(ServiceContext.Current.AssemblyName,
                                                                     ServiceContext.Current.TargetType) as IService;

                Sponsor <IService> s = new Sponsor <IService>(service);

                service.Start();

                ServiceContext.Current.ServiceDomain = newDomain;
                ServiceContext.Current.Service       = s;

                retValue = true;
            }
            catch (Exception eX)
            {
                msg = eX.Message;
                msg.Error();
                eX.Exception();
            }

            return(retValue);
        }
        static void Main_ObjectInstance(string[] args)
        {
            //有了一个类型对象后(Type的派生类实例如RuntimeType实例), 如何用他创建一个对象
            Version  v     = typeof(System.Object).Assembly.GetName().Version;
            string   asb   = "System.Messaging, PublicKeyToken=b03f5f7f11d50a3a, Culture=neutral, Version=" + v.ToString();
            Assembly msxml = Assembly.Load(asb);

            Type[] types = msxml.GetExportedTypes();
            Console.WriteLine("All types defined in System.Messaging.dll:");
            foreach (Type ty in types)
            {
                Console.WriteLine(ty.FullName);
            }
            Console.WriteLine(Environment.NewLine);

            Type   t            = types[types.Length - 5];
            string assemblyName = t.Assembly.FullName;
            string typename     = t.FullName;

            Console.WriteLine(typename);
            Console.WriteLine(assemblyName);
            Console.WriteLine(Environment.NewLine);

            //-
            object m1 = System.Activator.CreateInstance(t); //Type参数及ctor参数

            Console.WriteLine("m1 : " + m1.GetType());

            //-
            //ObjectHandle oh = Activator.CreateComInstanceFrom(assemblyName, typename); //TODO 怎么传
            //object m2 = oh.Unwarp();

            //-
            AppDomain ad = AppDomain.CurrentDomain;
            object    m3 = ad.CreateInstanceAndUnwrap(assemblyName, typename);

            Console.WriteLine("m3 : " + m3.GetType());

            //-
            //object m4 = t.InvokeMember();

            //-
            //object m5 = t.GetConstructor().Invoke(null);

            //- 数组
            int[] arr = (int[])System.Array.CreateInstance(typeof(int), 5);
            Console.WriteLine("Array : " + arr.GetType());
            Console.WriteLine(arr.Length);

            //- 委托
            MyDel md = (MyDel)System.Delegate.CreateDelegate(typeof(MyDel), typeof(Chapter23_Assembly_ObjectInstance).GetMethod("SomeMethod"), true);

            Console.WriteLine("Delegate : " + md.GetType());
            Console.WriteLine(md.GetInvocationList().Length);

            //- 泛型类型
            Type   open  = typeof(TestGeneraic <,>);
            Type   close = open.MakeGenericType(typeof(string), typeof(int));
            object m6    = Activator.CreateInstance(close);

            Console.WriteLine("m6 : " + m6.GetType());
        }
Exemplo n.º 33
0
        public static void DebugScreen(String strLayoutXMLPath, String strSourceCode, String strViewNo, ViewMode mode)
        {
            ABCHelper.ABCWaitingDialog.Show("", ". . .");

            try
            {
                ABCBaseScreen screen = null;
                Type          type   = null;
                Assembly      ass    = null;

                #region Build
                if (String.IsNullOrWhiteSpace(strSourceCode) == false)
                {
                    ass = ABCScreenFactory.CompileScreenSouceCode(strSourceCode, strViewNo);
                    if (ass != null)
                    {
                        type = ass.GetType("ABCApp.Screens." + strViewNo + "Screen");
                    }
                }
                if (type == null)
                {
                    type = typeof(ABCBaseScreen);
                }
                #endregion

                Assembly         asBase     = null;
                ABCScreenManager globalBase = null;

                AppDomain domain = AppDomain.CreateDomain("DebugABCScreen", AppDomain.CurrentDomain.Evidence, AppDomain.CurrentDomain.SetupInformation);
                try
                {
                    asBase     = domain.Load(typeof(ABCScreenManager).Assembly.FullName);
                    globalBase = (ABCScreenManager)domain.CreateInstanceAndUnwrap("ABCBaseScreen", "ABCScreen.ABCScreenManager");
                    globalBase.CallInitialize();

                    if (ass != null)
                    {
                        domain.Load(ass.GetName());
                    }

                    screen = (ABCBaseScreen)domain.CreateInstanceAndUnwrap(type.Assembly.FullName, type.FullName);
                    if (screen != null)
                    {
                        screen.LoadScreen(strLayoutXMLPath, mode);
                        ABCHelper.ABCWaitingDialog.Close();
                        screen.ShowDialog();
                    }
                }
                catch (Exception ex)
                {
                }

                screen     = null;
                globalBase = null;
                asBase     = null;

                AppDomain.Unload(domain);
                domain = null;
            }
            catch (Exception exx)
            { }

            GC.Collect();                  // collects all unused memory
            GC.WaitForPendingFinalizers(); // wait until GC has finished its work
            GC.Collect();
            ABCHelper.ABCWaitingDialog.Close();
        }
Exemplo n.º 34
0
        public void LoadAssemblies()
        {
            if (ad != null)
            {
                System.Console.Error.WriteLine("Unloading domain");
                AppDomain.Unload(ad);
            }

            ad = AppDomain.CreateDomain("MyAppDomain");
            object o = ad.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, "CompleteSharp+MyAppDomain+Hack");
            Hack h = o as Hack;
            h.ad = this;
            int idx = 0;

            foreach (string a in assemblies)
            {
                try
                {
                    FileInfo fi = new FileInfo(a);
                    times[idx] = fi.LastWriteTime;
                    idx++;

                    System.Console.Error.WriteLine("Loading: " + a);
                    h.Load(a);
                }
                catch (Exception e)
                {
                    reportError(e);
                }
            }
        }
        /// <summary>
        /// Creates the app-domain and the instance of the ResourceRetriever and
        /// sets the private fields with the references.
        /// </summary>
        /// 
        private void CreateAppDomain()
        {
            if (_domain == null)
            {
                // Create an app-domain to load the resource assemblies in so that they can be
                // unloaded.

                _domain = AppDomain.CreateDomain("ResourceIndirectDomain");
                _resourceRetriever =
                    (ResourceRetriever)_domain.CreateInstanceAndUnwrap(
                        Assembly.GetExecutingAssembly().FullName,
                        "System.Management.Automation.ResourceRetriever");
            }
        }