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);
            }
        }
Beispiel #2
0
        public void ProcessAssembly(string filename)
        {
            FileInfo fileInfo = new FileInfo(filename);
            AppDomainSetup setup = new AppDomainSetup();
            setup.ApplicationBase = fileInfo.DirectoryName;
            setup.PrivateBinPath = AppDomain.CurrentDomain.BaseDirectory;
            setup.ApplicationName = "Loader";
            setup.ShadowCopyFiles = "true";

            try
            {
                appDomain = AppDomain.CreateDomain("Loading Domain", null, setup);
                AssemblyProcessor processor = (AssemblyProcessor)
                   appDomain.CreateInstanceFromAndUnwrap(
                   "TestAssembly.dll",
                   "TestAssembly.AssemblyProcessor");
                string name = fileInfo.Name.Replace(fileInfo.Extension, "");
                Console.WriteLine(name);
                processor.Load(name);
                processor.Process();
            }
            finally
            {
                if (appDomain != null)
                {
                    AppDomain.Unload(appDomain);
                    appDomain = null;
                }
            }
        }
		public void SetUp()
		{
			string path = new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath;

			_localDomain = AppDomain.CreateDomain("NewDomain");
			_localDomain.Load(typeof(DataAccessor).Assembly.GetName());
			_localTest = (DataAccessorBuilderTest)_localDomain.CreateInstanceFromAndUnwrap(path, GetType().FullName);
		}
        private void InitDomain(string name, AppDomainSetup setup)
        {
#if STATIC

#else
            _currDomain = AppDomain.CreateDomain(name, null, setup);
            var type = typeof(ScriptDomainContext);
            _context = (ScriptDomainContext)_currDomain.CreateInstanceFromAndUnwrap(type.Assembly.GetName().CodeBase, type.FullName);
#endif
        }
		public MathAssembly(string expression, string variable)
		{
			var mathAssembly = new MathFuncAssemblyCecil();
			_fileName = "MathFuncLib" + "_" + GenerateRandomString(6) + ".dll";
			mathAssembly.CompileFuncAndDerivative(expression, variable, "", _fileName);
			_domain = AppDomain.CreateDomain("MathFuncDomain");
			_mathFuncObj = _domain.CreateInstanceFromAndUnwrap(_fileName, mathAssembly.NamespaceName + "." + mathAssembly.ClassName);
			var mathFuncObjType = _mathFuncObj.GetType();
			FuncMethodInfo = mathFuncObjType.GetMethod(mathAssembly.FuncName);
			FuncDerivativeMethodInfo = mathFuncObjType.GetMethod(mathAssembly.FuncDerivativeName);
		}
Beispiel #6
0
		RemoteSetupDomain GetDomain ()
		{
			lock (this) {
				if (useCount++ == 0) {
					AppDomain.CurrentDomain.AssemblyResolve += MonoAddinsAssemblyResolve;
					domain = AppDomain.CreateDomain ("SetupDomain", null, AppDomain.CurrentDomain.SetupInformation);
					var type = typeof(RemoteSetupDomain);
					remoteSetupDomain = (RemoteSetupDomain) domain.CreateInstanceFromAndUnwrap (type.Assembly.Location, type.FullName);
				}
				return remoteSetupDomain;
			}
		}
Beispiel #7
0
 public static AssemblyLoader CreateAssemblyLoader(AppDomain appDomain) {
    try {
       var assemblyLoader = appDomain.CreateInstanceFromAndUnwrap(
          typeof(AssemblyLoader).Assembly.CodeBase,
          typeof(AssemblyLoader).FullName);
       return assemblyLoader as AssemblyLoader;
    }
    catch (Exception ex) {
       Debug.WriteLine(ex);
       return null;
    }
 }
        public AssemblyExecutor(string fileNname, string domainName)
        {
            assemblyFileName = fileNname;
            AppDomainSetup setup = new AppDomainSetup();
            setup.ApplicationBase = Path.GetDirectoryName(assemblyFileName);
            setup.PrivateBinPath = AppDomain.CurrentDomain.BaseDirectory;
            setup.ApplicationName = Path.GetFileName(Assembly.GetExecutingAssembly().Location);
            setup.ShadowCopyFiles = "true";
            setup.ShadowCopyDirectories = Path.GetDirectoryName(assemblyFileName);
            appDomain = AppDomain.CreateDomain(domainName, null, setup);

            remoteExecutor = (RemoteExecutor)appDomain.CreateInstanceFromAndUnwrap(Assembly.GetExecutingAssembly().Location, typeof(RemoteExecutor).ToString());
        }
Beispiel #9
0
        public ILoader Create()
        {
            AppDomainSetup adSetup = new AppDomainSetup();
            adSetup.ShadowCopyFiles = "true"; // not a boolean

            m_LoaderDomain = createAppDomainForLoader(adSetup);
            string dir = m_LoaderDomain.SetupInformation.ApplicationBase;

            string selfAssemblyName = (new System.Uri(Assembly.GetExecutingAssembly().CodeBase)).AbsolutePath;

            ILoader loader = (ILoader) m_LoaderDomain.CreateInstanceFromAndUnwrap(selfAssemblyName, "Cider_x64.Loader");
            return loader;
        }
Beispiel #10
0
        public ILoader Create()
        {
            AppDomainSetup adSetup = new AppDomainSetup();
            adSetup.ShadowCopyFiles = "true"; // not a boolean

            m_LoaderDomain = createAppDomainForLoader(adSetup);
            string dir = m_LoaderDomain.SetupInformation.ApplicationBase;

            string selfAssemblyName = (new System.Uri(Assembly.GetExecutingAssembly().CodeBase)).AbsolutePath;
            selfAssemblyName = Uri.UnescapeDataString(selfAssemblyName); // e.g. otherwise, spaces in the path of our .EXE would be represented as '%20'

            ILoader loader = (ILoader) m_LoaderDomain.CreateInstanceFromAndUnwrap(selfAssemblyName, "Cider_x64.Loader");
            return loader;
        }
        private static SiloHost CreateSiloHost(AppDomain appDomain, ClusterConfiguration clusterConfig)
        {
            var args = new object[] { nameof(SiloInitializationIsRetryableTest), clusterConfig };

            return (SiloHost)appDomain.CreateInstanceFromAndUnwrap(
                "OrleansRuntime.dll",
                typeof(SiloHost).FullName,
                false,
                BindingFlags.Default,
                null,
                args,
                CultureInfo.CurrentCulture,
                new object[] { });
        }
 private static DomainHostingStarterAgent CreateAgent(AppDomain domain)
 {
     try
     {
         return (DomainHostingStarterAgent)domain.CreateInstanceAndUnwrap(
             typeof(DomainHostingStarterAgent).Assembly.FullName,
             typeof(DomainHostingStarterAgent).FullName);
     }
     catch
     {
         return (DomainHostingStarterAgent)domain.CreateInstanceFromAndUnwrap(
             typeof(DomainHostingStarterAgent).Assembly.Location,
             typeof(DomainHostingStarterAgent).FullName);
     }
 }
Beispiel #13
0
        // Methods ========================================================================
        public void Load(string filePath)
        {
            AssemblyPath = filePath;
            AssemblyName = Path.GetFileName(filePath);

            domain = AppDomain.CreateDomain(AssemblyName);
            proxy = (AppDomainProxy)domain.CreateInstanceFromAndUnwrap(
                Assembly.GetExecutingAssembly().CodeBase, typeof(AppDomainProxy).FullName);

            try {
                proxy.LoadAssembly(filePath);
            } catch (Exception) {
                AppDomain.Unload(domain);
                throw;
            }
        }
			public RecyclableAppDomain (string name)
			{
				var info = new AppDomainSetup () {
					//appbase needs to allow loading this assembly, for remoting
					ApplicationBase = System.IO.Path.GetDirectoryName (typeof (TemplatingAppDomainRecycler).Assembly.Location),
					DisallowBindingRedirects = false,
					DisallowCodeDownload = true,
                    DisallowApplicationBaseProbing = false,
					ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile,
				};
				domain = AppDomain.CreateDomain (name, null, info);
                var t = typeof(DomainAssemblyLoader);
                AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
                assemblyMap = (DomainAssemblyLoader) domain.CreateInstanceFromAndUnwrap(t.Assembly.Location, t.FullName);
                AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomain_AssemblyResolve;
                domain.AssemblyResolve += assemblyMap.Resolve;// new DomainAssemblyLoader(assemblyMap).Resolve;
			}
        public EfMigrator(string assemblyPath, string qualifiedDbConfigName, string appConfigPath, string connectionString, string connectionProvider,
                          ILogger logger)
        {
            _logger = logger;

            appConfigPath = Path.GetFullPath(appConfigPath);
            if (!File.Exists(appConfigPath))
            {
                throw new EfMigrationException($"The {nameof(appConfigPath)} '{appConfigPath}' must exist.");
            }

            var domainSetup = AppDomain.CurrentDomain.SetupInformation;
            domainSetup.ConfigurationFile = appConfigPath;
            _logger.Debug($"Prepared AppDomain setup using {appConfigPath} as the appconfig.");

            var domainName = $"EfMigrator:{Guid.NewGuid()}";
            _domain = AppDomain.CreateDomain(domainName, null, domainSetup);
            _logger.Debug($"Created new AppDomain named {domainName}.");

            var type = typeof(EfMigratorBackend);

            var fullPath = Assembly.GetAssembly(typeof(EfMigratorBackend)).Location;
            //var domain = AppDomain.CurrentDomain.GetAssemblies()
            //                      .Where(x => !x.IsDynamic)
            //                      .Where(x => !x.GlobalAssemblyCache)
            //                      .Select(x => Path.GetDirectoryName(x.Location))
            //                      .Distinct();

            //var domains = string.Join(", ", domain);
            //logger.Debug($"Loading assemblies into appDomain: {domains}.");

            Debug.Assert(fullPath != null, "fullPath != null");

            var migrator = (EfMigratorBackend) _domain.CreateInstanceFromAndUnwrap(fullPath, type.FullName);
            _logger.Debug("Created new instance.");
            migrator.Initialize(assemblyPath, qualifiedDbConfigName, connectionString, connectionProvider);

            _logger.Debug($"Initialized new {nameof(EfMigratorBackend)} within {domainName}.");

            CurrentMigration = migrator.GetCurrentMigration() ?? InitialDatabase;
            var currentMigrationStr = CurrentMigration == InitialDatabase ? "$InitialDatabase" : CurrentMigration;
            _logger.Information($"Current Migration is {currentMigrationStr}.");

            _migratorBackend = migrator;
        }
Beispiel #16
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;
    }
 }
        private void Initialize()
        {
            if (_info.GeneratorFolder == null)
            {
                throw new InvalidOperationException(
                          "The RemoteAppDomainTestGeneratorFactory has to be configured with the Setup() method before initialization.");
            }


            var appDomainSetup = new AppDomainSetup
            {
                ShadowCopyFiles = "true",
            };

            _appDomain = System.AppDomain.CreateDomain("AppDomainForTestGeneration", null, appDomainSetup);

            var testGeneratorFactoryTypeFullName = typeof(TestGeneratorFactory).FullName;

            Debug.Assert(testGeneratorFactoryTypeFullName != null);

            _tracer.Trace(string.Format("TestGeneratorFactory: {0}", testGeneratorFactoryTypeFullName), LogCategory);

            _tracer.Trace("AssemblyResolve Event added", LogCategory);
            System.AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainOnAssemblyResolve;


            var remoteAppDomainAssembly = _remoteAppDomainResolverType.Assembly;

            _remoteAppDomainResolver = (RemoteAppDomainResolver)_appDomain.CreateInstanceFromAndUnwrap(remoteAppDomainAssembly.Location, _remoteAppDomainResolverType.FullName, true, BindingFlags.Default, null, null, null, null);
            _remoteAppDomainResolver.Init(_info.GeneratorFolder);

            var generatorFactoryObject = _appDomain.CreateInstanceAndUnwrap(_info.RemoteGeneratorAssemblyName, testGeneratorFactoryTypeFullName);

            _remoteTestGeneratorFactory = generatorFactoryObject as ITestGeneratorFactory;

            if (_remoteTestGeneratorFactory == null)
            {
                throw new InvalidOperationException("Could not load test generator factory.");
            }

            _usageCounter = new UsageCounter(LoseReferences);
            _tracer.Trace("AppDomain for generator created", LogCategory);
        }
Beispiel #18
0
        private void RunApplication(string action)
        {
            if (watcher == null)
            {
                watcher = new FileSystemWatcher(AppDomain.CurrentDomain.BaseDirectory, "*.dll");
                watcher.Changed += delegate(object sender, FileSystemEventArgs e)
                {
                    StopRunner(string.Format(System.Globalization.CultureInfo.CurrentCulture,"One or more DLLs have changed - waiting {0}s", restartTime));
                    waitTimer.Stop();
                    waitTimer.Start();
                };
                watcher.EnableRaisingEvents = true;
                watcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite | NotifyFilters.Size;
            }

            // Allow the user to turn shadow-copying off
            var setting = ConfigurationManager.AppSettings["ShadowCopy"] ?? string.Empty;
            var useShadowCopying = !(string.Equals(setting, "off", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(setting, "false", StringComparison.OrdinalIgnoreCase));
            try
            {
                this.runnerDomain = CreateNewDomain(useShadowCopying);
            }
            catch (FileLoadException)
            {
                // Unable to use shadow-copying (no user profile?), therefore turn off shadow-copying
                useShadowCopying = false;
                this.runnerDomain = CreateNewDomain(useShadowCopying);
            }
            runner = runnerDomain.CreateInstanceFromAndUnwrap(Assembly.GetExecutingAssembly().Location,
                typeof(AppRunner).FullName) as AppRunner;
            try
            {
                runner.Run(action, useShadowCopying);
            }
            catch (SerializationException)
            {
                var configFilename = ConfigurationManager.AppSettings["ccnet.config"];
                configFilename = string.IsNullOrEmpty(configFilename) ? Path.Combine(Environment.CurrentDirectory, "ccnet.log") : configFilename;
                throw new ApplicationException(
                    string.Format(System.Globalization.CultureInfo.CurrentCulture,"A fatal error has occurred while starting CCService. Please check '{0}' for any details.", configFilename));
            }
        }
        private void Create(bool recreate = false)
        {
            if (domain == null || recreate)
            {
                if (domain != null)
                {
                    frm.Hide();
                    AppDomain.Unload(domain);
                    domain = null;
                }

                var myLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                var info = new AppDomainSetup
                {
                    ShadowCopyFiles = "true"
                };

                domain = AppDomain.CreateDomain("TranscodingDomain", null, info);
                frm = (RemoteImageViewer)domain.CreateInstanceFromAndUnwrap(typeof(RemoteImageViewer).Assembly.Location, typeof(RemoteImageViewer).FullName);

                frm.InitPlugin(pluginPath);
            }

            frm.SetFramesPerSecond(framesPerSecond);
            frm.SetOnError(onError);
            
            if(sessionDataPath != null)
                frm.SetSessionDataPath(sessionDataPath);

            if( backgroundImage != null)
                frm.SetBackgroundImage(backgroundImage);
            frm.ClientSize = clientSize;
            frm.SetPosition(left, top);
            frm.SetPlaybackSpeed(playbackSpeed);
            frm.SetOnAnimationTick(onAnimationTick);
            frm.SetDrawAction(drawAction);
            frm.SetPaused(isPaused);

            frm.Refresh();
        }
        public SystemReflectionProvider(string assembly)
        {
            try
            {
                var domainSetup = new AppDomainSetup
                                      {
                    ApplicationBase = Path.GetDirectoryName(assembly),
                    ApplicationName = AppDomain.CurrentDomain.SetupInformation.ApplicationName,
                    LoaderOptimization = LoaderOptimization.MultiDomainHost
                };
                _childDomain = AppDomain.CreateDomain("Type locator app domain", null, domainSetup);

                // Create an instance of the runtime in the second AppDomain. 
                // A proxy to the object is returned.
                _locator = (ISystemReflectionProvider_Internal)_childDomain.CreateInstanceFromAndUnwrap(Assembly.GetExecutingAssembly().Location, typeof(SystemReflectionProvider_Internal).FullName);
                _locator.Load(assembly);
            }
            catch (Exception ex)
            {
                Logging.Logger.Write(ex);
            }
        }
Beispiel #21
0
        /// <summary>
        /// Creates a remote instance of a type within another AppDomain.
        /// </summary>
        /// <remarks>
        /// This method first uses <see cref="AppDomain.CreateInstanceAndUnwrap(string, string)" /> to
        /// try create an instance of the type.  If that fails, it uses <see cref="AppDomain.CreateInstanceFromAndUnwrap(string, string)" />
        /// to load the assembly that contains the type into the AppDomain then create an instance of the type.
        /// </remarks>
        /// <param name="appDomain">The AppDomain in which to create the instance.</param>
        /// <param name="type">The type to instantiate.</param>
        /// <param name="args">The constructor arguments for the type.</param>
        /// <returns>The remote instance.</returns>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="appDomain"/> or <paramref name="type"/>
        /// is null.</exception>
        public static object CreateRemoteInstance(AppDomain appDomain, Type type, params object[] args)
        {
            if (appDomain == null)
                throw new ArgumentNullException("appDomain");

            // FIX
#pragma warning disable 618
            Assembly assembly = type.Assembly;
            try
            {
                return appDomain.CreateInstanceAndUnwrap(assembly.FullName, type.FullName, false,
                    BindingFlags.Default, null, args, null, null, null);
            }
            catch (Exception)
            {
                string assemblyFile = AssemblyUtils.GetFriendlyAssemblyLocation(type.Assembly);
                return appDomain.CreateInstanceFromAndUnwrap(assemblyFile, type.FullName, false,
                    BindingFlags.Default, null, args, null, null, null);
            }
#pragma warning restore 618
        }
        void DetectResharperLoading(AppDomain vsAppDomain)
        {
            while (_retries <= MAX_RETRIES)
            {
                Assembly resharperAssembly;
                try
                {
                    resharperAssembly = vsAppDomain.Load("JetBrains.Platform.ReSharper.Shell");
                }
                catch
                {
                    resharperAssembly = null;
                }
                if (resharperAssembly == null && _retries++ <= MAX_RETRIES)
                {
                    _output.Write("ReSharper not found, try {0}/{1}, sleeping for 2 seconds.", _retries, MAX_RETRIES);
                    Thread.Sleep(TimeSpan.FromSeconds(2));
                    continue;
                }
                var resharperVersion = resharperAssembly.GetName().Version;
                var pluginManagerType = LoadTypeFromVersion(resharperVersion);
                if (pluginManagerType == null) return;

                var assemblyLocation = pluginManagerType.Assembly.Location;
                var destinationAssemblyFile = CopyAndSign(assemblyLocation);

                _pluginManager = vsAppDomain.CreateInstanceFromAndUnwrap(destinationAssemblyFile.Path, pluginManagerType.FullName);
                return;
            }
        }
Beispiel #23
0
        public static ScriptDomain Load(string path)
        {
            int num;

            List <string> list;
            List <string> list2;

            path = Path.GetFullPath(path);
            AppDomainSetup info = new AppDomainSetup {
                ApplicationBase       = path,
                ShadowCopyFiles       = "true",
                ShadowCopyDirectories = path
            };

            StrongName[]     fullTrustAssemblies = new StrongName[0];
            System.AppDomain domain = System.AppDomain.CreateDomain("ScriptDomain_" + (path.GetHashCode() * Environment.TickCount).ToString("X"), null, info, new PermissionSet(PermissionState.Unrestricted), fullTrustAssemblies);
            domain.InitializeLifetimeService();
            ScriptDomain domain2 = null;

            try
            {
                domain2 = (ScriptDomain)domain.CreateInstanceFromAndUnwrap(typeof(ScriptDomain).Assembly.Location, typeof(ScriptDomain).FullName);
            }
            catch (Exception exception1)
            {
                string[] strArray2 = new string[] { "Failed to create script domain '", domain.FriendlyName, "':", Environment.NewLine, exception1.ToString() };
                GTA.Log("[ERROR]", strArray2);
                System.AppDomain.Unload(domain);
                return(null);
            }
            string[] message = new string[] { "Loading scripts from '", path, "' into script domain '", domain.FriendlyName, "' ..." };
            GTA.Log("[INFO]", message);
            if (!Directory.Exists(path))
            {
                string[] strArray7 = new string[] { "Failed to reload scripts because the directory is missing." };
                GTA.Log("[ERROR]", strArray7);
                return(domain2);
            }
            else
            {
                list2 = new List <string>();
                list  = new List <string>();
                try
                {
                    list2.AddRange(Directory.GetFiles(path, "*.vb", SearchOption.AllDirectories));
                    list2.AddRange(Directory.GetFiles(path, "*.cs", SearchOption.AllDirectories));
                    list.AddRange(Directory.GetFiles(path, "*.dll", SearchOption.AllDirectories));
                }
                catch (Exception exception5)
                {
                    string[] strArray6 = new string[] { "Failed to reload scripts:", Environment.NewLine, exception5.ToString() };
                    GTA.Log("[ERROR]", strArray6);
                    System.AppDomain.Unload(domain);
                    return(null);
                }
                num = 0;
            }
            while (true)
            {
                if (num >= list.Count)
                {
                    List <string> .Enumerator enumerator2 = list2.GetEnumerator();
                    if (enumerator2.MoveNext())
                    {
                        do
                        {
                            string current = enumerator2.Current;
                            domain2.LoadScript(current);
                        }while (enumerator2.MoveNext());
                    }
                    List <string> .Enumerator enumerator = list.GetEnumerator();
                    if (enumerator.MoveNext())
                    {
                        do
                        {
                            string current = enumerator.Current;
                            domain2.LoadAssembly(current);
                        }while (enumerator.MoveNext());
                    }
                    break;
                }
                try
                {
                    string assemblyFile = list[num];
                    if (AssemblyName.GetAssemblyName(assemblyFile).Name == "ScriptHookVDotNet")
                    {
                        string[] strArray5 = new string[] { "Removing assembly file '", Path.GetFileName(assemblyFile), "'." };
                        GTA.Log("[WARNING]", strArray5);
                        num += -1;
                        list.RemoveAt(num);
                        try
                        {
                            File.Delete(assemblyFile);
                        }
                        catch (Exception exception6)
                        {
                            string[] strArray4 = new string[] { "Failed to delete assembly file:", Environment.NewLine, exception6.ToString() };
                            GTA.Log("[ERROR]", strArray4);
                        }
                    }
                }
                catch (BadImageFormatException)
                {
                }
                catch (Exception exception7)
                {
                    string[] strArray3 = new string[] { "Failed to load assembly ", list[num], Environment.NewLine, exception7.ToString() };
                    GTA.Log("[ERROR]", strArray3);
                }
                num++;
            }
            return(domain2);
        }
Beispiel #24
0
        private static Silo LoadSiloInNewAppDomain(string siloName, Silo.SiloType type, ClusterConfiguration config, out AppDomain appDomain)
        {
            AppDomainSetup setup = GetAppDomainSetupInfo();

            appDomain = AppDomain.CreateDomain(siloName, null, setup);

            // Load each of the additional assemblies.
            Silo.TestHookups.CodeGeneratorOptimizer optimizer = null;
            foreach (var assembly in additionalAssemblies)
            {
                if (optimizer == null)
                {
                    optimizer =
                        (Silo.TestHookups.CodeGeneratorOptimizer)
                        appDomain.CreateInstanceFromAndUnwrap(
                            "OrleansRuntime.dll",
                            typeof(Silo.TestHookups.CodeGeneratorOptimizer).FullName,
                            false,
                            BindingFlags.Default,
                            null,
                            null,
                            CultureInfo.CurrentCulture,
                            new object[] { });
                }

                if (assembly.Value != null)
                {
                    optimizer.AddCachedAssembly(assembly.Key, assembly.Value);
                }
            }

            var args = new object[] { siloName, type, config };

            var silo = (Silo)appDomain.CreateInstanceFromAndUnwrap(
                "OrleansRuntime.dll", typeof(Silo).FullName, false,
                BindingFlags.Default, null, args, CultureInfo.CurrentCulture,
                new object[] { });

            appDomain.UnhandledException += ReportUnobservedException;

            return silo;
        }
        /// <summary>
        /// Add new device profile.
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public GXDeviceProfilesUpdateResponse Post(GXDeviceProfilesUpdateRequest request)
        {
            List <GXEventsItem> events         = new List <GXEventsItem>();
            GXAmiDeviceProfile  DeviceProfiles = null;

            lock (Db)
            {
                using (var trans = Db.OpenTransaction(IsolationLevel.ReadCommitted))
                {
                    string filename = Path.GetTempFileName();
                    using (FileStream stream = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        BinaryWriter w = new BinaryWriter(stream);
                        w.Write(request.Data);
                    }
                    string pathToDll = this.GetType().Assembly.CodeBase;
                    // Create an Application Domain:
                    AppDomainSetup domainSetup = new AppDomainSetup {
                        PrivateBinPath = pathToDll
                    };
                    System.AppDomain td  = null;
                    string           dir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + Path.DirectorySeparatorChar);
                    //Try to load device template and unload assmbly.
                    try
                    {
                        td = AppDomain.CreateDomain("TestDomain", null, domainSetup);
                        GXProxyClass pc = (GXProxyClass)(td.CreateInstanceFromAndUnwrap(pathToDll, typeof(GXProxyClass).FullName));
                        if (!Directory.Exists(dir))
                        {
                            Directory.CreateDirectory(dir);
                        }
                        byte[]          data;
                        string          addInType, assemblyName;
                        List <object[]> items              = pc.Import(filename, dir, out data, out assemblyName, out addInType);
                        ulong           DeviceProfileID    = 0;
                        ulong           categoryTemplateID = 0;
                        ulong           propertyTemplateID = 0;
                        ulong           tableTemplateID    = 0;
                        int             version            = 0;
                        foreach (object[] it in items)
                        {
                            if (it[1] is GXAmiDeviceProfile)
                            {
                                DeviceProfiles = it[1] as GXAmiDeviceProfile;
                                events.Add(new GXEventsItem(ActionTargets.DeviceProfile, Actions.Add, DeviceProfiles));
                                //Find new version number for the template.
                                foreach (GXAmiDeviceProfile dt in Db.Select <GXAmiDeviceProfile>(q => q.Guid == DeviceProfiles.Guid))
                                {
                                    if (dt.ProfileVersion > version)
                                    {
                                        version = dt.ProfileVersion;
                                    }
                                }
                                ++version;
                                DeviceProfiles.ProtocolAddInType = addInType;
                                DeviceProfiles.ProtocolAssembly  = assemblyName;
                                DeviceProfiles.ProfileVersion    = version;
                            }
                            else if (it[1] is GXAmiCategoryTemplate)
                            {
                                tableTemplateID = 0;
                                (it[1] as GXAmiCategoryTemplate).DeviceID        = DeviceProfileID;
                                (it[1] as GXAmiCategoryTemplate).Id             += DeviceProfileID << 16;
                                (it[1] as GXAmiCategoryTemplate).TemplateVersion = version;
                            }
                            else if (it[1] is GXAmiDataTableTemplate)
                            {
                                categoryTemplateID = 0;
                                (it[1] as GXAmiDataTableTemplate).DeviceID        = DeviceProfileID;
                                (it[1] as GXAmiDataTableTemplate).Id             += DeviceProfileID << 16;
                                (it[1] as GXAmiDataTableTemplate).TemplateVersion = version;
                            }
                            else if (it[1] is GXAmiPropertyTemplate)
                            {
                                (it[1] as GXAmiPropertyTemplate).DeviceID        = DeviceProfileID;
                                (it[1] as GXAmiPropertyTemplate).TemplateVersion = version;
                                if (categoryTemplateID != 0)
                                {
                                    (it[1] as GXAmiPropertyTemplate).ParentID = categoryTemplateID;
                                }
                                else if (tableTemplateID != 0)
                                {
                                    (it[1] as GXAmiPropertyTemplate).ParentID = tableTemplateID;
                                }
                                else
                                {
                                    throw new ArgumentOutOfRangeException("Parent ID.");
                                }
                                (it[1] as GXAmiPropertyTemplate).Id += DeviceProfileID << 16;
                            }
                            else if (it[1] is GXAmiParameterTemplate)
                            {
                                (it[1] as GXAmiParameterTemplate).DeviceID        = DeviceProfileID;
                                (it[1] as GXAmiParameterTemplate).TemplateVersion = version;
                                if (it[0] is GXAmiDeviceProfile)
                                {
                                    (it[1] as GXAmiParameterTemplate).ParentID = DeviceProfileID << 16;
                                }
                                else if (it[0] is GXAmiCategoryTemplate)
                                {
                                    (it[1] as GXAmiParameterTemplate).ParentID = categoryTemplateID;
                                }
                                else if (it[0] is GXAmiDataTableTemplate)
                                {
                                    (it[1] as GXAmiParameterTemplate).ParentID = tableTemplateID;
                                }
                                else if (it[0] is GXAmiPropertyTemplate)
                                {
                                    (it[1] as GXAmiParameterTemplate).ParentID = propertyTemplateID;
                                }
                            }
                            Db.Insert(it[1]);
                            if (it[1] is GXAmiDeviceProfile)
                            {
#if !SS4
                                ulong value = (ulong)Db.GetLastInsertId();
#else
                                ulong value = (ulong)Db.LastInsertId();
#endif
                                (it[1] as GXAmiDeviceProfile).Id = value;
                                DeviceProfileID = value;
                                //Update allowed media types.
                                foreach (GXAmiMediaType mt in (it[1] as GXAmiDeviceProfile).AllowedMediaTypes)
                                {
                                    mt.DeviceProfileId = DeviceProfileID;
                                    Db.Insert(mt);
                                }
                            }
                            else if (it[1] is GXAmiCategoryTemplate)
                            {
                                categoryTemplateID = (it[1] as GXAmiCategoryTemplate).Id;
                            }
                            else if (it[1] is GXAmiDataTableTemplate)
                            {
                                tableTemplateID = (it[1] as GXAmiDataTableTemplate).Id;
                            }
                            else if (it[1] is GXAmiPropertyTemplate)
                            {
                                propertyTemplateID = (it[1] as GXAmiPropertyTemplate).Id;
                                if ((it[1] as GXAmiPropertyTemplate).Values != null && (it[1] as GXAmiPropertyTemplate).Values.Length != 0)
                                {
#if !SS4
                                    ulong value = (ulong)Db.GetLastInsertId();
#else
                                    ulong value = (ulong)Db.LastInsertId();
#endif
                                    foreach (GXAmiValueItem vi in (it[1] as GXAmiPropertyTemplate).Values)
                                    {
                                        vi.ProfileId  = DeviceProfileID;
                                        vi.PropertyId = value;
                                        Db.Insert(vi);
                                    }
                                }
                            }
                            else if (it[1] is GXAmiParameterTemplate)
                            {
                                if ((it[1] as GXAmiParameterTemplate).Values != null && (it[1] as GXAmiParameterTemplate).Values.Length != 0)
                                {
#if !SS4
                                    ulong value = (ulong)Db.GetLastInsertId();
#else
                                    ulong value = (ulong)Db.LastInsertId();
#endif
                                    foreach (GXAmiValueItem vi in (it[1] as GXAmiParameterTemplate).Values)
                                    {
                                        vi.ProfileId   = DeviceProfileID;
                                        vi.ParameterId = value;
                                        Db.Insert(vi);
                                    }
                                }
                            }
                        }
                        //Save device template to data blocks.
                        foreach (GXAmiDeviceProfilesDataBlock it in SplitDataToPackets(DeviceProfileID, filename))
                        {
                            Db.Insert(it);
                        }
                        foreach (GXAmiDeviceProfilesDataBlock it in SplitDataToPackets(DeviceProfileID, filename))
                        {
                            Db.Insert(it);
                        }
                        if (request.UserGroups != null)
                        {
                            foreach (long ugId in request.UserGroups)
                            {
                                GXAmiUserGroupDeviceProfile it = new GXAmiUserGroupDeviceProfile();
                                it.DeviceProfileID = DeviceProfileID;
                                it.UserGroupID     = ugId;
                                Db.Insert(it);
                            }
                        }
                    }
                    finally
                    {
                        // Unload the application domain:
                        if (td != null)
                        {
                            System.AppDomain.Unload(td);
                        }
                        if (dir != null)
                        {
                            try
                            {
                                Directory.Delete(dir, true);
                            }
                            catch
                            {
                                //It's OK if this fails.
                            }
                        }
                    }
                    trans.Commit();
                }
            }
            AppHost host = this.ResolveService <AppHost>();
            host.SetEvents(Db, this.Request, 0, events);
            return(new GXDeviceProfilesUpdateResponse(request.UserGroups, DeviceProfiles));
        }
Beispiel #26
0
		public static BamlDecompiler CreateBamlDecompilerInAppDomain(ref AppDomain appDomain, string assemblyFileName)
		{
			if (appDomain == null) {
				// Construct and initialize settings for a second AppDomain.
				AppDomainSetup bamlDecompilerAppDomainSetup = new AppDomainSetup();
				bamlDecompilerAppDomainSetup.ApplicationBase = "file:///" + Path.GetDirectoryName(assemblyFileName);
				bamlDecompilerAppDomainSetup.DisallowBindingRedirects = false;
				bamlDecompilerAppDomainSetup.DisallowCodeDownload = true;
				bamlDecompilerAppDomainSetup.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;

				// Create the second AppDomain.
				appDomain = AppDomain.CreateDomain("BamlDecompiler AD", null, bamlDecompilerAppDomainSetup);
			}
			return (BamlDecompiler)appDomain.CreateInstanceFromAndUnwrap(typeof(BamlDecompiler).Assembly.Location, typeof(BamlDecompiler).FullName);
		}
 /// <summary>
 /// Gets the current proxy.
 /// </summary>
 /// <returns>ParadoxCommandsProxy.</returns>
 public static ParadoxCommandsProxy CreateProxy(AppDomain domain)
 {
     if (domain == null) throw new ArgumentNullException("domain");
     return (ParadoxCommandsProxy)domain.CreateInstanceFromAndUnwrap(typeof(ParadoxCommandsProxy).Assembly.Location, typeof(ParadoxCommandsProxy).FullName);
 }
        private static void InstallerStageTwo(AppDomain appDomain) {
            if( Cancelling ) {
                return;
            }
            // stage two: close our bootstrap GUI, and start the Installer in the new AppDomain, 
            // of course, this has all got to happen on the original thread. *sigh*
            Logger.Message("Got to Installer Stage Two");
#if DEBUG
            var localAssembly = AcquireFile("CoApp.Toolkit.Engine.Client.dll");
            Logger.Message("Local Assembly: " + localAssembly);

            if (!string.IsNullOrEmpty(localAssembly)) {
                // use the one found locally.
                appDomain.CreateInstanceFromAndUnwrap(localAssembly, "CoApp.Toolkit.Engine.Client.Installer", false, BindingFlags.Default, null, new[] { MsiFilename }, null, null);
                // if it didn't throw here, we can assume that the CoApp service is running, and we can get to our assembly.
                Logger.Warning("Done! Exiting  (debug)");
                ExitQuick();
            }
#endif 
            // meh. use strong named assembly
            appDomain.CreateInstanceAndUnwrap( "CoApp.Toolkit.Engine.Client, Version=1.0.0.0, Culture=neutral, PublicKeyToken=820d50196d4e8857",
                "CoApp.Toolkit.Engine.Client.Installer", false, BindingFlags.Default, null, new[] { MsiFilename }, null, null);

            // since we've done everything we need to do, we're out of here. Right Now.
            Logger.Warning("Done! Exiting");
            ExitQuick();
        }
Beispiel #29
0
        private void CompileAndExecute(string[] files, string[] args, IScriptManagerCallback callback, string[] filesToEmbed)
        {
            try
            {
                // Create an AppDomain to compile and execute the code
                // This enables us to cancel the execution if needed
                executionDomain = AppDomain.CreateDomain("ExecutionDomain");
                var manager = (IScriptManager)executionDomain.CreateInstanceFromAndUnwrap(typeof(BaseApp).Assembly.Location, typeof(ScriptManager).FullName);
                manager.CompileAndExecuteFile(files, args, this, filesToEmbed);
            }
            catch(UnsupportedLanguageExecption e)
            {
                ShowErrorMessageFromResource("UnsupportedLanguage", e.Extension);
            }
            catch(AppDomainUnloadedException e)
            {
                System.Diagnostics.Trace.WriteLine(e.Message);
            }
            catch(Exception e)
            {
                ShowErrorMessage(e.Message);
            }

            TerminateExecutionLoop();
        }
Beispiel #30
0
        private static Silo LoadSiloInNewAppDomain(string siloName, Silo.SiloType type, ClusterConfiguration config, out AppDomain appDomain)
        {
            AppDomainSetup setup = GetAppDomainSetupInfo();

            appDomain = AppDomain.CreateDomain(siloName, null, setup);

            var args = new object[] { siloName, type, config };

            var silo = (Silo)appDomain.CreateInstanceFromAndUnwrap(
                "OrleansRuntime.dll", typeof(Silo).FullName, false,
                BindingFlags.Default, null, args, CultureInfo.CurrentCulture,
                new object[] { });

            appDomain.UnhandledException += ReportUnobservedException;

            return silo;
        }
Beispiel #31
0
        internal List<Job.Base.Job> FindJobsIn(AppDomain appDom)
        {
            var jobs = new List<Job.Base.Job>();
            var loader = GetLoader(appDom);
            var jobTypes = loader.GetJobTypes();

            foreach (var jobType in jobTypes)
            {
                var job = appDom.CreateInstanceFromAndUnwrap(jobType.Item1, jobType.Item2) as Job.Base.Job;

                if (job != null)
                {
                    jobs.Add(job);
                }
            }

            return jobs;
        }
Beispiel #32
0
 private AssemblyLoader GetLoader(AppDomain appDomain)
 {
     return appDomain.CreateInstanceFromAndUnwrap(
         Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Scurry.Executor.Loader.dll"),
         "Scurry.Executor.Loader.AssemblyLoader") as AssemblyLoader;
 }
Beispiel #33
0
 private void Resolve(AppDomain appDomain)
 {
     appDomain.CreateInstanceFromAndUnwrap(
         Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Scurry.Executor.Loader.dll"),
         "Scurry.Executor.Loader.Resolver",
         false, 0, null,
         new object[] { AppDomain.CurrentDomain.BaseDirectory,
             new string[] { AppDomain.CurrentDomain.BaseDirectory } },
         null, null);
 }