SetData() public méthode

public SetData ( string name, object data ) : void
name string
data object
Résultat void
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            OpenFileDialog configform = new OpenFileDialog();
            configform.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            configform.Filter = "程序集文件(*.dll,*.exe)|*.dll;*.exe";
            configform.FilterIndex = 1;
            configform.RestoreDirectory = true;
            if (configform.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if (currentDomain != null)
                        AppDomain.Unload(currentDomain);
                    currentDomain = AppDomain.CreateDomain("temp");
                    string configfile = configform.FileName + ".config";
                    string filedic = Path.GetDirectoryName(configform.FileName);
                    var m = typeof(AppDomainSetup).GetMethod("UpdateContextProperty", BindingFlags.NonPublic | BindingFlags.Static);
                    var funsion = typeof(AppDomain).GetMethod("GetFusionContext", BindingFlags.NonPublic | BindingFlags.Instance);
                    if(File.Exists(configfile))
                        currentDomain.SetData("APP_CONFIG_FILE", configfile);
                    var test = currentDomain.SetupInformation;
                    exDataAccess = (ExDataAccess)currentDomain.CreateInstanceAndUnwrap(typeof(ExDataAccess).Assembly.FullName, typeof(ExDataAccess).FullName);
                    currentDomain.SetData("APPBASE", filedic);
                    m.Invoke(null, new object[] { funsion.Invoke(currentDomain, null), "APPBASE", filedic });
                    this.textEdit1.Text = configform.FileName;
                    var results = exDataAccess.FindAttributes(configform.FileName);
                    if (results.Count > 0)
                    {
                        this.treeList1.ClearNodes();
                        foreach (var result in results)
                        {
                            this.treeList1.Nodes.Add(result[0], result[1], result[2]);
                        }
                    }

                    currentDomain.SetupInformation.ConfigurationFile =configform.FileName+".config";
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
        public static void Main(string[] args)
        {
            var obj = new ComObject();

            obj.Report("Object created.");

            System.AppDomain domain = System.AppDomain.CreateDomain("New domain");

            // via GCHandle
            var gcHandle = GCHandle.Alloc(obj);

            domain.SetData("gcCookie", GCHandle.ToIntPtr(gcHandle));

            // via COM GIT
            var git       = (ComExt.IGlobalInterfaceTable)(Activator.CreateInstance(Type.GetTypeFromCLSID(ComExt.CLSID_StdGlobalInterfaceTable)));
            var comCookie = git.RegisterInterfaceInGlobal(obj, ComExt.IID_IUnknown);

            domain.SetData("comCookie", comCookie);

            // via COM CCW
            var unkCookie = Marshal.GetIUnknownForObject(obj);

            domain.SetData("unkCookie", unkCookie);

            // invoke in another domain
            domain.DoCallBack(() =>
            {
                Program.Report("Another domain");

                // trying GCHandle - fails
                var gcCookie2 = (IntPtr)(System.AppDomain.CurrentDomain.GetData("gcCookie"));
                var gcHandle2 = GCHandle.FromIntPtr(gcCookie2);
                try
                {
                    var gcObj2 = (ComObject)(gcHandle2.Target);
                    gcObj2.Report("via GCHandle");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

                // trying COM GIT - works
                var comCookie2 = (uint)(System.AppDomain.CurrentDomain.GetData("comCookie"));
                var git2       = (ComExt.IGlobalInterfaceTable)(Activator.CreateInstance(Type.GetTypeFromCLSID(ComExt.CLSID_StdGlobalInterfaceTable)));
                var obj2       = (ITest)git2.GetInterfaceFromGlobal(comCookie2, ComExt.IID_IUnknown);
                obj2.Report("via GIT");

                // trying COM CCW
                var unkCookie2 = (IntPtr)(System.AppDomain.CurrentDomain.GetData("unkCookie"));
                // this casting works because we derived from MarshalByRefObject
                var unkObj2 = (ComObject)Marshal.GetObjectForIUnknown(unkCookie2);
                obj2.Report("via CCW");
            });

            Console.ReadLine();
        }
		protected override HostedService CreateRemoteHost(AppDomain appDomain)
		{
			appDomain.SetData("ConnectionString",_connectionString);
			appDomain.DoCallBack(SetConnectionStringInAppDomain);
			var service = base.CreateRemoteHost(appDomain);
			return service;
		}
Exemple #4
0
        private System.AppDomain CreateDomain(string domainName, string containerName)
        {
            System.AppDomain appDomain = null;
            try
            {
                // Create the AppDomain for each container and initialize the container with AppDomain

                appDomain = System.AppDomain.CreateDomain(containerName);

                // Create an instance of the container in that domain and initialize it.

                string fullName = typeof(ContainerManager).Assembly.FullName;
                string typeName = typeof(ContainerManager).FullName;

                ContainerManager manager = (ContainerManager)appDomain.CreateInstanceAndUnwrap(fullName, typeName);

                if (manager != null)
                {
                    appDomain.SetData("ContainerManager", manager);
                    manager.Initialize(domainName, containerName);
                }
            }
            catch (System.Exception ex)
            {
                string errorString = GenerateErrorString(ex);
                if (appDomain != null)
                {
                    System.AppDomain.Unload(appDomain);
                    appDomain = null;
                }
            }
            return(appDomain);
        }
Exemple #5
0
        private void ReStart()
        {
            Process thisprocess = Process.GetCurrentProcess();
            string  me          = thisprocess.MainModule.FileName;

            string sApplicationDirectory = AppDomain.CurrentDomain.BaseDirectory;
            string sAppName = "RadarBidClient";

            System.AppDomainSetup oSetup = new System.AppDomainSetup();
            string sApplicationFile      = null;

            // Use this to ensure that if the application is running when the user performs the update, that we don't run into file locking issues.
            oSetup.ShadowCopyFiles = "true";
            oSetup.ApplicationName = sAppName;

            // Generate the name of the DLL we are going to launch
            sApplicationFile = Path.Combine(sApplicationDirectory, sAppName + ".exe");

            oSetup.ApplicationBase    = sApplicationDirectory;
            oSetup.ConfigurationFile  = sApplicationFile + ".config";
            oSetup.LoaderOptimization = LoaderOptimization.MultiDomain;

            // Launch the application
            System.AppDomain oAppDomain = AppDomain.CreateDomain(sAppName, AppDomain.CurrentDomain.Evidence, oSetup);
            oAppDomain.SetData("App", sAppName);
            // oAppDomain.SetData("User", sUserName);
            // oAppDomain.SetData("Pwd", sUserPassword);

            oAppDomain.ExecuteAssembly(sApplicationFile);

            // When the launched application closes, close this application as well
            // Application.Exit();
            Application.Current.Shutdown();
        }
 public static void SetShadowPathForNativeDll(AppDomain appDomain, string dllFileName, string dllPath)
 {
     if (dllFileName == null) throw new ArgumentNullException("dllFileName");
     if (dllPath == null) throw new ArgumentNullException("dllPath");
     var key = AppDomainCustomDllPathKey + dllFileName.ToLowerInvariant();
     appDomain.SetData(key, dllPath);
 }
        static void Load()
        {
            if (AppDomain.CurrentDomain.FriendlyName != "OnlineVideosSiteUtilDlls")
            {
                if (_useSeperateDomain)
                {
                    _domain = AppDomain.CreateDomain("OnlineVideosSiteUtilDlls", null, null, null, true);

                    // we need to subscribe to AssemblyResolve on the MP2 AppDomain because OnlineVideos.dll is loaded in the LoadFrom Context
                    // and when unwrapping transparent proxy from our AppDomain, resolving types will fail because it looks only in the default Load context
                    // we simply help .Net by returning the already loaded assembly from the LoadFrom context
                    AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolve;

                    _pluginLoader = (PluginLoader)_domain.CreateInstanceFromAndUnwrap(
                      Assembly.GetExecutingAssembly().Location,
                      typeof(PluginLoader).FullName);

                    AppDomain.CurrentDomain.AssemblyResolve -= AssemblyResolve;

                    _domain.SetData(typeof(PluginLoader).FullName, _pluginLoader);
                }
                else
                {
                    _domain = AppDomain.CurrentDomain;
                    _pluginLoader = new PluginLoader();
                }
            }
            else
            {
                _domain = AppDomain.CurrentDomain;
                _pluginLoader = (PluginLoader)AppDomain.CurrentDomain.GetData(typeof(PluginLoader).FullName);
            }
        }
Exemple #8
0
		public void ConfigureNewDomain(AppDomain domain)
		{
			if (!string.IsNullOrWhiteSpace(AssemblyFolder))
				domain.SetData("Folder", AssemblyFolder);

			if (domain == AppDomain.CurrentDomain)
				ResolveCustomAssemblies();
			else
				domain.DoCallBack(new CrossAppDomainDelegate(ResolveCustomAssemblies));
		}
Exemple #9
0
        //private static void domain_DomainUnload(object sender, EventArgs e)
        //{
        //    Trace.WriteLine("domain_DomainUnload()");
        //}

        static void Run(object runSourceRestartParameters)
        {
            __domain = AppDomain.CreateDomain(__runsourceDomainName);
            if (runSourceRestartParameters != null)
            {
                __domain.SetData(__domainRestartParametersName, runSourceRestartParameters);
                runSourceRestartParameters = null;
            }
            __domain.ExecuteAssembly(Path.Combine(zapp.GetAppDirectory(), __runsourceExeName));
        }
Exemple #10
0
 //ncrunch: no coverage start
 public AssemblyStarter(string assemblyFilePath, bool copyToLocalFolderForExecution)
 {
     if (!File.Exists(assemblyFilePath))
         throw new FileNotFoundException("Assembly not found, unable to start it", assemblyFilePath);
     rememberedDirectory = Directory.GetCurrentDirectory();
     var assemblyFullPath = GetFullPathFromRelativeOrAbsoluteFilePath(assemblyFilePath);
     if (copyToLocalFolderForExecution)
         CopyAssemblyFileAndAllDependencies(assemblyFullPath);
     else if (!string.IsNullOrEmpty(assemblyFullPath))
         Directory.SetCurrentDirectory(assemblyFullPath);
     domain = AppDomain.CreateDomain(DomainName, null, CreateDomainSetup(assemblyFullPath));
     domain.SetData("EntryAssembly", Path.GetFullPath(assemblyFilePath));
 }
Exemple #11
0
        protected override IManagedAppBase CreateAndStartServerInstance()
        {
            IManagedApp appServer;

            try
            {
                m_HostDomain = CreateHostAppDomain();

                m_HostDomain.SetData(typeof(IsolationMode).Name, IsolationMode.AppDomain);

                var marshalServerType = typeof(MarshalManagedApp);

                appServer = (IManagedApp)m_HostDomain.CreateInstanceAndUnwrap(marshalServerType.Assembly.FullName,
                    marshalServerType.FullName,
                    true,
                    BindingFlags.CreateInstance,
                    null,
                    new object[] { GetMetadata().AppType },
                    null,
                    new object[0]);

                if (!appServer.Setup(Bootstrap, Config))
                {
                    OnExceptionThrown(new Exception("Failed to setup MarshalManagedApp"));
                    return null;
                }

                if (!appServer.Start())
                {
                    OnExceptionThrown(new Exception("Failed to start MarshalManagedApp"));
                    return null;
                }

                m_HostDomain.DomainUnload += new EventHandler(m_HostDomain_DomainUnload);

                return appServer;
            }
            catch (Exception e)
            {
                if (m_HostDomain != null)
                {
                    AppDomain.Unload(m_HostDomain);
                    m_HostDomain = null;
                }

                OnExceptionThrown(e);
                return null;
            }
        }
        /// <summary>
        /// Starts this server instance.
        /// </summary>
        /// <returns>
        /// return true if start successfull, else false
        /// </returns>
        protected override IWorkItemBase Start()
        {
            IWorkItem appServer;

            try
            {
                m_HostDomain = CreateHostAppDomain();

                m_HostDomain.SetData(typeof(IsolationMode).Name, IsolationMode.AppDomain);

                var marshalServerType = typeof(MarshalAppServer);

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

                if (!appServer.Setup(Bootstrap, ServerConfig, Factories))
                {
                    OnExceptionThrown(new Exception("Failed to setup MarshalAppServer"));
                    return null;
                }

                if (!appServer.Start())
                {
                    OnExceptionThrown(new Exception("Failed to start MarshalAppServer"));
                    return null;
                }

                m_HostDomain.DomainUnload += new EventHandler(m_HostDomain_DomainUnload);

                return appServer;
            }
            catch (Exception e)
            {
                if (m_HostDomain != null)
                {
                    AppDomain.Unload(m_HostDomain);
                    m_HostDomain = null;
                }

                OnExceptionThrown(e);
                return null;
            }
        }
Exemple #13
0
 public static RemoteLoader CreateInstance(AppDomain remoteDomain, string csUnitRoot) {
    try {
       remoteDomain.SetData("csUnitRoot", csUnitRoot);
       var remoteLoader = (RemoteLoader) remoteDomain.CreateInstanceFromAndUnwrap(
             Path.Combine(csUnitRoot, "csUnit.Core.dll"),
             typeof(RemoteLoader).FullName);
       return remoteLoader;
    }
    catch (Exception ex) {
       Debug.WriteLine(string.Format("## Listing assemblies in domain '{0}'##", remoteDomain.FriendlyName));
       foreach (var assembly in remoteDomain.GetAssemblies()) {
          Debug.WriteLine(assembly.FullName);
       }
       Debug.WriteLine("## end of list ##");
       Debug.WriteLine("Could not instantiate remote loader. " + ex);
       return null;
    }
 }
Exemple #14
0
        public static void Main(string[] args)
        {
            Program.Report("app start");
            System.AppDomain domain = System.AppDomain.CreateDomain("New domain");

            var ctxOb = new CtxObject();

            ctxOb.Report("ctxOb object");

            domain.SetData("ctxOb", ctxOb);
            domain.DoCallBack(() =>
            {
                Program.Report("inside another domain");
                var ctxOb2 = (CtxObject)System.AppDomain.CurrentDomain.GetData("ctxOb");
                ctxOb2.Report("ctxOb called from another domain");
            });

            Console.ReadLine();
        }
        public ProjectExecutionContext(Project project, IServiceProvider serviceProvider)
        {
            Debug.Assert(project != null, "project is null.");
            Debug.Assert(!VsUtils.IsMiscellaneousProject(project), "project is misc files project.");

            _domain = AppDomain.CreateDomain(
                "ProjectExecutionContextDomain",
                null,
                new AppDomainSetup
                    {
                        ApplicationBase = VsUtils.GetProjectTargetDir(project, serviceProvider),
                        ConfigurationFile = VsUtils.GetProjectConfigurationFile(project, serviceProvider),
                        ShadowCopyFiles = "true" // Prevents locking
                    });

            var dataDirectory = VsUtils.GetProjectDataDirectory(project, serviceProvider);
            if (dataDirectory != null)
            {
                _domain.SetData("DataDirectory", dataDirectory);
            }

            _executor = new ExecutorWrapper(_domain, VsUtils.GetProjectTargetFileName(project));
        }
        // Main
        public static void Main(string[] args)
        {
            var ob = new MyController();

            Action <string> newDomainAction = (name) =>
            {
                System.AppDomain domain = System.AppDomain.CreateDomain(name);
                domain.SetData("ob", ob);
                domain.DoCallBack(DomainCallback);
            };

            Console.WriteLine("\nPress Enter to test domains...");
            Console.ReadLine();

            var task1 = Task.Run(() => newDomainAction("domain1"));
            var task2 = Task.Run(() => newDomainAction("domain2"));

            Task.WaitAll(task1, task2);

            Console.WriteLine("\nPress Enter to test ob.Test...");
            Console.ReadLine();
            ob.Test();

            Console.WriteLine("\nPress Enter to test ob2.TestAsync...");
            Console.ReadLine();
            var ob2 = new MyController();

            ob2.TaskAsync().Wait();

            Console.WriteLine("\nPress Enter to test TestContext...");
            Console.ReadLine();
            TestContext();

            Console.WriteLine("\nPress Enter to exit...");
            Console.ReadLine();
        }
Exemple #17
0
		void SetRunnerDomainData (object[] data, AppDomain domain)
		{
			int len = data != null ? data.Length : 0;
			if (len == 0)
				return;

			if (len % 2 != 0)
				throw new ArgumentException ("Must have an even number of elements.", "data");

			string name;
			for (int i = 0; i < len; i += 2) {
				name = data [i] as string;
				if (String.IsNullOrEmpty (name))
					throw new InvalidOperationException (String.Format ("Name at index {0} must not be null or empty.", i));

				domain.SetData (name, data [i + 1]);
			}
		}
        public void Init(bool fullBind)
        {
            string name = Path.GetRandomFileName();
            tempDir = Path.Combine(Path.GetTempPath(), name);
            string robocodeShadow = Path.Combine(tempDir, Path.GetFileName(robocodeAssembly.Location));
            string hostShadow = Path.Combine(tempDir, Path.GetFileName(hostAssembly.Location));
            string controlShadow = Path.Combine(tempDir, Path.GetFileName(controlAssembly.Location));
            string jniShadow = Path.Combine(tempDir, Path.GetFileName(jniAssembly.Location));

            Directory.CreateDirectory(tempDir);
            File.Copy(robocodeAssembly.Location, robocodeShadow);
            File.Copy(controlAssembly.Location, controlShadow);
            File.Copy(hostAssembly.Location, hostShadow);
            File.Copy(jniAssembly.Location, jniShadow);

            var trustAssemblies = new[]
                                      {
                                          Reflection.GetStrongName(robocodeAssembly),
                                          Reflection.GetStrongName(controlAssembly),
                                          Reflection.GetStrongName(hostAssembly),
                                          Reflection.GetStrongName(jniAssembly),
                                      };
            var domainSetup = new AppDomainSetup();
            Evidence securityInfo = AppDomain.CurrentDomain.Evidence;
            var permissionSet = new PermissionSet(PermissionState.None);
            permissionSet.AddPermission(
                new SecurityPermission(SecurityPermissionFlag.Execution | SecurityPermissionFlag.Assertion));
            permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read, tempDir));
            permissionSet.AddPermission(new UIPermission(PermissionState.None));
            //permissionSet.AddPermission(HostProtection);

            domainSetup.ApplicationBase = tempDir;

            domainSetup.ApplicationName = name;
            //domainSetup.SandboxInterop = true;
            domainSetup.DisallowBindingRedirects = true;
            domainSetup.DisallowCodeDownload = true;
            domainSetup.DisallowPublisherPolicy = true;
            domainSetup.AppDomainInitializer = AppDomainSeed.Load;
            

            domain = AppDomain.CreateDomain(name, securityInfo, domainSetup, permissionSet, trustAssemblies);
            domain.SetData("fullBind", fullBind);
            domain.SetData("JavaHome", Bridge.Setup.JavaHome);
            domain.DoCallBack(AppDomainSeed.Bind);
        }
        static void Load()
        {
            if (AppDomain.CurrentDomain.FriendlyName != "OnlineVideosSiteUtilDlls")
            {
                if (useSeperateDomain)
                {
                    domain = AppDomain.CreateDomain("OnlineVideosSiteUtilDlls", null, null, null, true);

                    pluginLoader = (PluginLoader)domain.CreateInstanceAndUnwrap(
                      typeof(PluginLoader).Assembly.FullName,
                      typeof(PluginLoader).FullName);

                    domain.SetData(typeof(PluginLoader).FullName, pluginLoader);
                }
                else
                {
                    domain = AppDomain.CurrentDomain;
                    pluginLoader = new PluginLoader();
                }
            }
            else
            {
                domain = AppDomain.CurrentDomain;
                pluginLoader = (PluginLoader)AppDomain.CurrentDomain.GetData(typeof(PluginLoader).FullName);
            }
        }
        private void LoadAllRunnersIntoAppDomain()
        {
            domain = AppDomain.CreateDomain("Delta Engine Assembly Updater", null, CreateDomainSetup());
            domain.SetData("resolver", resolver);
            domain.SetData("domainInitializationCode", domainInitializationCode);
            domain.DoCallBack(InitializeInDomain);

            foreach (string assembly in AssemblyFilenames)
                LoadRunners(assembly);
        }
Exemple #21
0
        } // PrepareDataForSetup

        private static Object Setup(Object arg)
        {
            Contract.Requires(arg != null && arg is Object[]);
            Contract.Requires(((Object[])arg).Length >= 8);

            Object[]       args                     = (Object[])arg;
            String         friendlyName             = (String)args[0];
            AppDomainSetup setup                    = (AppDomainSetup)args[1];
            IntPtr         parentSecurityDescriptor = (IntPtr)args[2];
            bool           generateDefaultEvidence  = (bool)args[3];

            byte[] serializedEvidence = (byte[])args[4];
            AppDomainInitializerInfo initializerInfo = (AppDomainInitializerInfo)args[5];
            string sandboxName = (string)args[6];

            string[] propertyNames  = (string[])args[7]; // can contain null elements
            string[] propertyValues = (string[])args[8]; // can contain null elements
            // extract evidence
            Evidence providedSecurityInfo = null;
            Evidence creatorsSecurityInfo = null;

            AppDomain      ad       = AppDomain.CurrentDomain;
            AppDomainSetup newSetup = new AppDomainSetup(setup, false);

            if (propertyNames != null && propertyValues != null)
            {
                for (int i = 0; i < propertyNames.Length; i++)
                {
                    // We want to set native dll probing directories before any P/Invokes have a
                    // chance to fire. The Path class, for one, has P/Invokes.
                    if (propertyNames[i] == "NATIVE_DLL_SEARCH_DIRECTORIES")
                    {
                        if (propertyValues[i] == null)
                        {
                            throw new ArgumentNullException("NATIVE_DLL_SEARCH_DIRECTORIES");
                        }

                        string paths = propertyValues[i];
                        if (paths.Length == 0)
                        {
                            break;
                        }

                        nSetNativeDllSearchDirectories(paths);
                    }
                }

                for (int i = 0; i < propertyNames.Length; i++)
                {
                    if (propertyNames[i] == "APPBASE") // make sure in sync with Fusion
                    {
                        if (propertyValues[i] == null)
                        {
                            throw new ArgumentNullException("APPBASE");
                        }

                        if (PathInternal.IsPartiallyQualified(propertyValues[i]))
                        {
                            throw new ArgumentException(SR.Argument_AbsolutePathRequired);
                        }

                        newSetup.ApplicationBase = NormalizePath(propertyValues[i], fullCheck: true);
                    }
                    else if (propertyNames[i] == "LOADER_OPTIMIZATION")
                    {
                        if (propertyValues[i] == null)
                        {
                            throw new ArgumentNullException("LOADER_OPTIMIZATION");
                        }

                        switch (propertyValues[i])
                        {
                        case "SingleDomain": newSetup.LoaderOptimization = LoaderOptimization.SingleDomain; break;

                        case "MultiDomain": newSetup.LoaderOptimization = LoaderOptimization.MultiDomain; break;

                        case "MultiDomainHost": newSetup.LoaderOptimization = LoaderOptimization.MultiDomainHost; break;

                        case "NotSpecified": newSetup.LoaderOptimization = LoaderOptimization.NotSpecified; break;

                        default: throw new ArgumentException(SR.Argument_UnrecognizedLoaderOptimization, "LOADER_OPTIMIZATION");
                        }
                    }
                    else if (propertyNames[i] == "TRUSTED_PLATFORM_ASSEMBLIES" ||
                             propertyNames[i] == "PLATFORM_RESOURCE_ROOTS" ||
                             propertyNames[i] == "APP_PATHS" ||
                             propertyNames[i] == "APP_NI_PATHS")
                    {
                        string values = propertyValues[i];
                        if (values == null)
                        {
                            throw new ArgumentNullException(propertyNames[i]);
                        }

                        ad.SetData(propertyNames[i], NormalizeAppPaths(values));
                    }
                    else if (propertyNames[i] != null)
                    {
                        ad.SetData(propertyNames[i], propertyValues[i]);     // just propagate
                    }
                }
            }

            ad.SetupFusionStore(newSetup, null); // makes FusionStore a ref to newSetup

            // technically, we don't need this, newSetup refers to the same object as FusionStore
            // but it's confusing since it isn't immediately obvious whether we have a ref or a copy
            AppDomainSetup adSetup = ad.FusionStore;

            adSetup.InternalSetApplicationTrust(sandboxName);

            // set up the friendly name
            ad.nSetupFriendlyName(friendlyName);

#if FEATURE_COMINTEROP
            if (setup != null && setup.SandboxInterop)
            {
                ad.nSetDisableInterfaceCache();
            }
#endif // FEATURE_COMINTEROP

            ad.CreateAppDomainManager(); // could modify FusionStore's object
            ad.InitializeDomainSecurity(providedSecurityInfo,
                                        creatorsSecurityInfo,
                                        generateDefaultEvidence,
                                        parentSecurityDescriptor,
                                        true);

            // can load user code now
            if (initializerInfo != null)
            {
                adSetup.AppDomainInitializer = initializerInfo.Unwrap();
            }
            RunInitializer(adSetup);

            return(null);
        }
Exemple #22
0
 public static void LoadFrom(AppDomain appDomain,string file)
 {
     appDomain.SetData(Thread.CurrentThread.ManagedThreadId + "LoadFile", file);
     appDomain.DoCallBack(() =>
     {
         Assembly ass2 = Assembly.LoadFrom((string)AppDomain.CurrentDomain.GetData(Thread.CurrentThread.ManagedThreadId + "LoadFile"));
     });
 }
        void LoadAppDomain()
        {
            Notify("Loading packages...");

            try
            {
                var packages = Preloader.GetPackageFolders(Preloader.RemoteInstall.None, _rootPath, null, "openwrap").ToArray();

                foreach (var package in packages) Notify("Loading package " + package);
                _appDomain = AppDomain.CreateDomain("OpenWrap Visual Studio Integration (default scope)");
                //_appDomain.SetupInformation = new AppDomainSetup() { ShadowCopyFiles = true }
                _appDomain.SetData("openwrap.vs.version", _dte.Version);
                _appDomain.SetData("openwrap.vs.currentdirectory", _rootPath);
                _appDomain.SetData("openwrap.vs.packages", packages.ToArray());
                _appDomain.SetData("openwrap.vs.appdomain", AppDomain.CurrentDomain);

                // replace that with the location in the codebase we just registered, ensuring the correct version is loaded
                var location = Type.GetTypeFromProgID(_progId).Assembly.Location;
                AppDomain.CurrentDomain.AssemblyResolve += HandleSelfLoad;
                _appDomainManager = (IDisposable)_appDomain.CreateInstanceFromAndUnwrap(location, typeof(AddInAppDomainManager).FullName);
                AppDomain.CurrentDomain.AssemblyResolve -= HandleSelfLoad;
                _appDomain.DomainUnload += HandleAppDomainChange;
            }
            catch (Exception e)
            {
                Notify("Could not load bootstrap packages.");
                Notify(e.ToString());
            }
        }
 public virtual void Run()
 {
     this.TryObtainLock();
     try
     {
         this.Preconditions(Pre.SiteSet | Pre.RootNamespaceSet | Pre.RootMonikerSet | Pre.EngineNotRunning | Pre.EngineNotClosed);
         System.AppDomain currentDomain = System.AppDomain.CurrentDomain;
         if (this.haveCompiledState)
         {
             if (this.rootNamespace != this.compiledRootNamespace)
             {
                 throw new JSVsaException(JSVsaError.RootNamespaceInvalid);
             }
             this.loadedAssembly = this.LoadCompiledState();
             currentDomain.SetData(this.engineMoniker, this.loadedAssembly);
         }
         else
         {
             if (this.failedCompilation)
             {
                 throw new JSVsaException(JSVsaError.EngineNotCompiled);
             }
             this.startupClass   = null;
             this.loadedAssembly = currentDomain.GetData(this.engineMoniker) as System.Reflection.Assembly;
             if (this.loadedAssembly == null)
             {
                 string name  = this.engineMoniker + "/" + currentDomain.GetHashCode().ToString(CultureInfo.InvariantCulture);
                 Mutex  mutex = new Mutex(false, name);
                 if (mutex.WaitOne())
                 {
                     try
                     {
                         this.loadedAssembly = currentDomain.GetData(this.engineMoniker) as System.Reflection.Assembly;
                         if (this.loadedAssembly == null)
                         {
                             byte[] buffer;
                             byte[] buffer2;
                             this.engineSite.GetCompiledState(out buffer, out buffer2);
                             if (buffer == null)
                             {
                                 throw new JSVsaException(JSVsaError.GetCompiledStateFailed);
                             }
                             this.loadedAssembly = System.Reflection.Assembly.Load(buffer, buffer2, this.executionEvidence);
                             currentDomain.SetData(this.engineMoniker, this.loadedAssembly);
                         }
                     }
                     finally
                     {
                         mutex.ReleaseMutex();
                         mutex.Close();
                     }
                 }
             }
         }
         try
         {
             if (this.startupClass == null)
             {
                 this.startupClass = this.loadedAssembly.GetType(this.rootNamespace + "._Startup", true);
             }
         }
         catch (Exception exception)
         {
             throw new JSVsaException(JSVsaError.BadAssembly, exception.ToString(), exception);
         }
         try
         {
             this.startupInstance = (BaseVsaStartup)Activator.CreateInstance(this.startupClass);
             this.isEngineRunning = true;
             this.startupInstance.SetSite(this.engineSite);
             this.startupInstance.Startup();
         }
         catch (Exception exception2)
         {
             throw new JSVsaException(JSVsaError.UnknownError, exception2.ToString(), exception2);
         }
     }
     finally
     {
         this.ReleaseLock();
     }
 }
Exemple #25
0
        internal static void PrepareForInception(AppDomain inception)
        {
            lock (threadLock)
            {
                string pipeName = (string)AppDomain.CurrentDomain.GetData("AddOnePIPE");

                if (application == null && company == null)
                    B1Connect(GetVersion());
                inception.SetData("SAPCompany", company);
                inception.SetData("SAPApplication", application);
                inception.SetData("AddOnePIPE", pipeName);
                // app instances in all AppDomains references this singleton from this AppDomain.
                inception.SetData("appHandler", ContainerManager.Container.Resolve<IAppEventHandler>());
            }
        }
 public void AssociateWithAppDomain(AppDomain domain) {
     Contract.RequiresNotNull(domain, "domain");
     domain.SetData(AppDomainDataKey, this);
 }
        internal static IPluginCreator GetCreator(AppDomain domain, ILoggerFactory logfactory)
        {
            if (domain == null)
            throw new ArgumentNullException("domain");

              if (logfactory == null)
            throw new ArgumentNullException("logfactory");

              IPluginCreator creator = domain.GetData(PLUGINCREATORKEY) as IPluginCreator;
              if (creator == null)
              {
            domain.SetData(LOGGERFACTORYKEY, new ProxyLoggerFactory(logfactory));
            domain.DoCallBack(() =>
            {
              Logger.Singleton.LoggerFactory = AppDomain.CurrentDomain.GetData(LOGGERFACTORYKEY) as ILoggerFactory;
              AppDomain.CurrentDomain.SetData(PLUGINCREATORKEY, new PluginCreator());
            });
            domain.SetData(LOGGERFACTORYKEY, null);
            creator = domain.GetData(PLUGINCREATORKEY) as IPluginCreator;
              }
              return creator;
        }
 /// <summary>
 /// Writes to domain.
 /// </summary>
 /// <param name="parameters">The parameters.</param>
 /// <param name="domain">The domain.</param>
 public static void WriteToDomain(BootstrapperParameters parameters, AppDomain domain)
 {
     domain.SetData(bootstrapperDataKey, parameters.BootstrapperFile);
     domain.SetData(bootstrapperConfigurationDataKey, parameters.ConfigurationFile);
 }
Exemple #29
0
        } // PrepareDataForSetup

        private static object Setup(object arg)
        {
            var args           = (object[])arg;
            var friendlyName   = (string)args[0];
            var setup          = (AppDomainSetup)args[1];
            var propertyNames  = (string[])args[2]; // can contain null elements
            var propertyValues = (string[])args[3]; // can contain null elements

            AppDomain ad       = CurrentDomain;
            var       newSetup = new AppDomainSetup(setup, copyDomainBoundData: false);

            if (propertyNames != null && propertyValues != null)
            {
                for (int i = 0; i < propertyNames.Length; i++)
                {
                    // We want to set native dll probing directories before any P/Invokes have a
                    // chance to fire. The Path class, for one, has P/Invokes.
                    if (propertyNames[i] == "NATIVE_DLL_SEARCH_DIRECTORIES")
                    {
                        if (propertyValues[i] == null)
                        {
                            throw new ArgumentNullException("NATIVE_DLL_SEARCH_DIRECTORIES");
                        }

                        string paths = propertyValues[i];
                        if (paths.Length == 0)
                        {
                            break;
                        }

                        nSetNativeDllSearchDirectories(paths);
                    }
                }

                for (int i = 0; i < propertyNames.Length; i++)
                {
                    if (propertyNames[i] == "APPBASE") // make sure in sync with Fusion
                    {
                        if (propertyValues[i] == null)
                        {
                            throw new ArgumentNullException("APPBASE");
                        }

                        if (PathInternal.IsPartiallyQualified(propertyValues[i]))
                        {
                            throw new ArgumentException(SR.Argument_AbsolutePathRequired);
                        }

                        newSetup.ApplicationBase = NormalizePath(propertyValues[i], fullCheck: true);
                    }
                    else if (propertyNames[i] == "TRUSTED_PLATFORM_ASSEMBLIES" ||
                             propertyNames[i] == "PLATFORM_RESOURCE_ROOTS" ||
                             propertyNames[i] == "APP_PATHS" ||
                             propertyNames[i] == "APP_NI_PATHS")
                    {
                        string values = propertyValues[i];
                        if (values == null)
                        {
                            throw new ArgumentNullException(propertyNames[i]);
                        }

                        ad.SetData(propertyNames[i], NormalizeAppPaths(values));
                    }
                    else if (propertyNames[i] != null)
                    {
                        ad.SetData(propertyNames[i], propertyValues[i]);     // just propagate
                    }
                }
            }

            ad.SetupFusionStore(newSetup, null); // makes FusionStore a ref to newSetup

            // technically, we don't need this, newSetup refers to the same object as FusionStore
            // but it's confusing since it isn't immediately obvious whether we have a ref or a copy
            AppDomainSetup adSetup = ad.FusionStore;

            // set up the friendly name
            ad.nSetupFriendlyName(friendlyName);

            ad.CreateAppDomainManager(); // could modify FusionStore's object

            return(null);
        }
Exemple #30
0
 /// <summary>
 /// Initializes the application domain with the debugger proxy.
 /// </summary>
 /// <param name="scriptDomain">The script domain.</param>
 internal static void InitializeAppDomain(AppDomain scriptDomain)
 {
     scriptDomain.SetData(VSDebuggerProxy.AppDomainDataName, debuggerProxy);
 }
Exemple #31
0
 /// <summary>Переустановить умолчательное окружение для другого <see cref="System.AppDomain"/>.</summary>
 /// <param name="e">Окружение, которое будет умолчательным.</param>
 /// <param name="domain"><see cref="AppDomain"/> для которого надо изменить окружение.</param>
 /// <remarks>Обычно, приложению нет необходимости вызывать метод <see cref="SetDefault"/>.</remarks>
 public static void SetDefault(AppDomain domain, IEnvironment e)
 {
     lock (typeof(Environment)) {
         domain.SetData(defaultEnvironmentName, e);
     }
 }
 private static void ConfigureNewDomain(AppDomain domain)
 {
     domain.SetData("LINQPad.InstanceID", Program.AppInstanceID);
     domain.SetData("LINQPad.Path", typeof(AppDomainUtil).Assembly.Location);
     ((AddAssemblyResolver) domain.CreateInstanceFromAndUnwrap(typeof(AddAssemblyResolver).Assembly.Location, typeof(AddAssemblyResolver).FullName)).Go();
 }
        /// <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_HostDomain.SetData(typeof(IsolationMode).Name, IsolationMode.AppDomain);

                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();
        }