Beispiel #1
0
 static object InstantiateDecimal(AppDomain appDomain, Binder binder, CultureInfo cultureInfo, string UName, string P2PUri)
 {
     try
     {
         object instance = appDomain.CreateInstance(
             "Video.Presentation",
             "Video.Presentation.P2PVideoClient",
             false,
             BindingFlags.Default,
             binder,
             new object[] { UName, P2PUri },
             cultureInfo,
             null,
             null
             );
         return(instance);
     }
     catch (Exception exp)
     {
         exp.Data.Add("My Key", "InstantiateDecimal()--:--P2PVideoDummyClient.cs--:--" + exp.Message + " :--:--");
         //ClsException.LogError(exp);
         //ClsException.WriteToErrorLogFile(exp);
         System.Text.StringBuilder sb = new StringBuilder();
         sb.AppendLine(exp.Message);
         sb.AppendLine();
         sb.AppendLine("StackTrace : " + exp.StackTrace);
         sb.AppendLine();
         sb.AppendLine("Location : " + exp.Data["My Key"].ToString());
         sb.AppendLine();
         sb1 = CreateTressInfo();
         sb.Append(sb1.ToString());
         VMuktiAPI.ClsLogging.WriteToTresslog(sb);
         return(null);
     }
 }
Beispiel #2
0
 static object InstantiateDecimal(AppDomain appDomain, Binder binder, CultureInfo cultureInfo, string MyName, string UName, int Id, string netP2pUri, string httpUri)
 {
     try
     {
         object instance = appDomain.CreateInstance(
             "AutoProgressivePhone.Presentation.",
             "AutoProgressivePhone.Presentation.AudioDummy",
             false,
             BindingFlags.Default,
             binder,
             new object[] { MyName, UName, Id, netP2pUri, httpUri },
             cultureInfo,
             null,
             null
             );
         return(instance);
     }
     catch (Exception ex)
     {
         ex.Data.Add("My Key", "VMukti--:--VmuktiModules--:--VmuktiModules--:--Call Center--:--AutoProgressiveSoftPhone--:--AutoProgressivePhone.Presentation--:--DummyClient.cs--:--AudioClient()--");
         ClsException.LogError(ex);
         ClsException.WriteToErrorLogFile(ex);
         if (ex.InnerException != null)
         {
             ClsException.LogError(ex);
             ClsException.WriteToErrorLogFile(ex);
         }
         throw ex;
         return(null);
     }
 }
        //static object InstantiateDecimal(AppDomain appDomain, Binder binder, CultureInfo cultureInfo, string MyName, string UName, int Id, string netP2pUri, string httpUri)
        //{
        //    try
        //    {
        //        object instance = appDomain.CreateInstance(
        //           "Weblink.Presentation",
        //           "Weblink.Presentation.WebLinkDummies",
        //           false,
        //           BindingFlags.Default,
        //           binder,
        //           new object[] { MyName, UName, Id, netP2pUri, httpUri },
        //           cultureInfo,
        //           null,
        //           null
        //        );
        //        return instance;
        //    }
        //    catch (Exception exp)
        //    {
        //        System.Windows.MessageBox.Show("InstantiateDecimal" + exp.Message);
        //        if (exp.InnerException != null)
        //        {
        //            System.Windows.MessageBox.Show("InstantiateDecimal " + exp.InnerException.Message);
        //        }
        //        throw exp;
        //        return null;
        //    }
        //}

        static object InstantiateDecimal(AppDomain appDomain, Binder binder, CultureInfo cultureInfo, string MyName, string UName, int Id, string netP2pUri, string httpUri)
        {
            try
            {
                object instance = appDomain.CreateInstance(
                    "Video.Presentation",
                    "Video.Presentation.MainVideoDummies",
                    false,
                    BindingFlags.Default,
                    binder,
                    new object[] { MyName, UName, Id, netP2pUri, httpUri },
                    cultureInfo,
                    null,
                    null
                    );
                return(instance);
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "--InstantiateDecimal()---VMukti--:--VmuktiModules--:--Collaborative--:--Video.Presentation--:--MainVideoDummyClient.cs--:");
                //ClsException.LogError(ex);
                //ClsException.WriteToErrorLogFile(ex);
                System.Text.StringBuilder sb = new StringBuilder();
                sb.AppendLine(ex.Message);
                sb.AppendLine();
                sb.AppendLine("StackTrace : " + ex.StackTrace);
                sb.AppendLine();
                sb.AppendLine("Location : " + ex.Data["My Key"].ToString());
                sb.AppendLine();
                sb1 = CreateTressInfo();
                sb.Append(sb1.ToString());
                VMuktiAPI.ClsLogging.WriteToTresslog(sb);
                return(null);
            }
        }
Beispiel #4
0
        static void Main()
        {
            Console.WriteLine("[{0}] {1}", System.AppDomain.CurrentDomain.FriendlyName, "Entered Main");

            //stvara novu aplikacijsku domenu
            AppDomain ad2 = AppDomain.CreateDomain("Shape Domain");

            //Assembly a = Assambly.LoadForm("ProgCSharp.exe");
            //Object theShape = a.CreateInstance("Shape");
            //Instanciranje Shape objekta
            System.Runtime.Remoting.ObjectHandle oh = ad2.CreateInstance(
                "Marshaling",
                "Marshaling.Shape", false,
                BindingFlags.CreateInstance,
                null, new object[] { 3, 5 }, null, null);


            Shape s1 = (Shape)oh.Unwrap();

            s1.ShowUpperLeft(); //zahtjeva od objekta da prikaze

            //dobili ste lokalnu kopiju posrednika
            Point localPoint = s1.GetUpperLeft();

            //dodjeljuje nove vrijednosti
            localPoint.X = 500;
            localPoint.Y = 600;

            //prikazuje vrijednosti lokalnog pointa
            Console.WriteLine("[{0}] localPoint: {1}, {2}", System.AppDomain.CurrentDomain.FriendlyName, localPoint.X, localPoint.Y);

            s1.ShowUpperLeft(); //prikazuje vrijednost jos jednom
        }
Beispiel #5
0
 static object InstantiateFileSearch(AppDomain appDomain, Binder binder, CultureInfo cultureInfo, string MyName, string UName, int Id, string netP2pUri, string httpUri)
 {
     try
     {
         object instance = appDomain.CreateInstance(
             "FileSearch.Presentation",
             "FileSearch.Presentation.FileSearchDummy",
             false,
             BindingFlags.Default,
             binder,
             new object[] { MyName, UName, Id, netP2pUri, httpUri },
             cultureInfo,
             null,
             null
             );
         return(instance);
     }
     catch (Exception exp)
     {
         if (exp.InnerException != null)
         {
             // System.Windows.MessageBox.Show(exp.InnerException.Message);
         }
         else
         {
             //System.Windows.MessageBox.Show("exp.Message " + exp.Message);
         }
         VMuktiAPI.VMuktiHelper.ExceptionHandler(exp, "InstantiateFileSearch", "DummyClient.cs");
         return(null);
     }
 }
Beispiel #6
0
        // TODO implement launching in a seperate App Domain
        private RunnerResult ExecuteInAppDomain(NUnitTestData test)
        {
            // spawn new domain in specified directory
            AppDomainSetup domSetup = new AppDomainSetup();

            domSetup.ApplicationBase   = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            domSetup.ConfigurationFile = Project.GetFullPath(test.AppConfigFile);
            domSetup.ApplicationName   = "NAnt Remote Domain";

            PermissionSet domainPermSet = new PermissionSet(PermissionState.Unrestricted);
            AppDomain     newDomain     = AppDomain.CreateDomain(domSetup.ApplicationName, AppDomain.CurrentDomain.Evidence,
                                                                 domSetup, domainPermSet);

            // instantiate subclassed test runner in new domain
            Type         runnerType = typeof(RemoteNUnitTestRunner);
            ObjectHandle oh         = newDomain.CreateInstance(
                runnerType.Assembly.FullName,
                runnerType.FullName,
                false, 0, null,
                new object[] { test },
                null, null, null
                );
            RemoteNUnitTestRunner runner = (RemoteNUnitTestRunner)(oh.Unwrap());

            Log(Level.Info, "Running '{0}'.", test.Class);

            runner.Run(string.Empty, Verbose);
            return(runner.ResultCode);
        }
Beispiel #7
0
    public static void Main()
    {
        Console.WriteLine("The hash code of the default AppDomain is {0}.",
                          AppDomain.CurrentDomain.GetHashCode());
        Console.WriteLine("");

        // Creates another AppDomain.
        AppDomain domain = AppDomain.CreateDomain("AnotherDomain",
                                                  null,
                                                  (AppDomainSetup)null);

        // Creates an instance of MyType defined in the assembly called ObjectHandleAssembly.
        ObjectHandle obj = domain.CreateInstance("ObjectHandleAssembly", "MyType");

        // Unwrapps the proxy to the MyType object created in the other AppDomain.
        MyType testObj = (MyType)obj.Unwrap();

        if (RemotingServices.IsTransparentProxy(testObj))
        {
            Console.WriteLine("The unwrapped object is a proxy.");
        }
        else
        {
            Console.WriteLine("The unwrapped object is not a proxy!");
        }

        Console.WriteLine("");
        Console.Write("Calling a method on the object located in an AppDomain with the hash code ");
        Console.WriteLine(testObj.GetAppDomainHashCode());
    }
Beispiel #8
0
        public InterfaceAppDomainProxy(Type appDomainSetupType, bool appDomainSetupTypeLoadFromMainModule = false)
        {
            AppDomain.MonitoringIsEnabled = true;
            AppDomainSetupType            = appDomainSetupType;
            PermissionSet grantSet  = new PermissionSet(PermissionState.Unrestricted);
            AppDomain     appDomain = AppDomain.CreateDomain("Interface", null, new AppDomainSetup
            {
                ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase
            }, grantSet);
            string assemblyFile = System.Diagnostics.Process.GetCurrentProcess()?.MainModule?.FileName;

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

            InterfaceAppDomainSetup.Setup();
            Proxy = (AppDomainProxyByte)appDomain.CreateInstanceAndUnwrap(typeFromHandle.Assembly.FullName, typeFromHandle.FullName);
            InterfaceAppDomain = appDomain;
        }
        private static List <DllInstance> Instances = new List <DllInstance>(); // Keeps track of loaded instances.

        /// <summary>
        /// Loads an instance of a class from a DLL file.
        /// </summary>
        /// <param name="dllFile">full path to the dll file</param>
        /// <param name="typeName">type of class to instantiate</param>
        /// <returns>the loaded instance or null if there was an exception</returns>
        public static object Load(string dllFile, string typeName)
        {
            try
            {
                if (!File.Exists(dllFile))
                {
                    return(null);
                }

                AppDomain domain   = AppDomain.CreateDomain("AppDomain" + (NextDomainCounter++).ToString());
                object    instance = domain.CreateInstance(dllFile, typeName).Unwrap();

                DllInstance dll = new DllInstance();
                dll.Domain   = domain;
                dll.Path     = dllFile;
                dll.TypeName = typeName;
                dll.Instance = instance;
                Instances.Add(dll);

                return(instance);
            }
            catch (Exception ex)
            {
                Core.HandleEx(ex);
                return(null);
            }
        }
Beispiel #10
0
        //----< Load and Test is responsible for testing >---------------

        ILoadAndTest installLoader(AppDomain ad)
        {
            ad.Load("LoadAndTest");
            //showAssemblies(ad);
            //Console.WriteLine();

            // create proxy for LoadAndTest object in child AppDomain

            ObjectHandle oh
                = ad.CreateInstance("LoadAndTest", "TestHarness.LoadAndTest");
            object ob = oh.Unwrap();        // unwrap creates proxy to ChildDomain
                                            // Console.Write("\n  {0}", ob);

            // set reference to LoadAndTest object in child

            ILoadAndTest landt = (ILoadAndTest)ob;

            // create Callback object in parent domain and pass reference
            // to LoadAndTest object in child

            landt.setCallback(cb_);
            lock (sync_)
            {
                filePath_ = TLS[Thread.CurrentThread.ManagedThreadId];
                landt.loadPath(filePath_);      // send file path to LoadAndTest
            }
            return(landt);
        }
Beispiel #11
0
        public object CreateInstance(string assemblyName, string typeName)
        {
            System.Runtime.Remoting.ObjectHandle a;
            a = _domain.CreateInstance(assemblyName, typeName);

            return(a.CreateObjRef(typeof(IPluginOld)));
        }
Beispiel #12
0
 public void CreateChildDomain() //Creating child AppDomain
 {
     try
     {
         AppDomainSetup domaininfo = new AppDomainSetup();
         domaininfo.ApplicationBase
             = "file:///" + System.Environment.CurrentDirectory;                               //Defining search path
         Evidence  adevidence = AppDomain.CurrentDomain.Evidence;
         AppDomain ad         = AppDomain.CreateDomain("ChildDomain", adevidence, domaininfo); //Creating child AppDomain
         ad.Load("LoadAndExecute");                                                            //Loading Dll Files in the child AppDomain
         showAssemblies(ad);
         Console.Write("\n\n");
         try
         {
             ObjectHandle oh
                 = ad.CreateInstance("LoadAndExecute", "TestH.TestHarness");
             object ob = oh.Unwrap();               //Creates a proxy task that creates async operation, creates proxy.
             Console.Write("\n  {0}", ob);
             TestH.TestHarness h = (TestH.TestHarness)ob;
             h.LoadTests(@"../../../Server/Test's"); //Path for location of DLL files.
             h.run();
             AppDomain.Unload(ad);                   //Unloading AppDomain for memory efficeiency
             Console.Write("\n\n");
         }
         catch (Exception except)
         {
             Console.Write("test  {0}\n\n", except.Message);
         }
     }
     catch (Exception except)
     {
         Console.Write("\n  {0}\n\n", except.Message);
     }
 }
Beispiel #13
0
        static void Main()
        {
            Console.WriteLine("Метод Main выполняется в домене      : {0}",
                              AppDomain.CurrentDomain.Id);

            // Создание второго домена приложения.
            AppDomain domain = AppDomain.CreateDomain("Second Domain");

            string assemblyName = Assembly.GetExecutingAssembly().GetName().Name;
            string typeName     = typeof(MyClass).FullName;

            // Создание объекта во втором домене.
            ObjectHandle handle = domain.CreateInstance(assemblyName, typeName);

            // Создание прозрачного прокси-переходника для взаимодействия с объектом во втором домене.
            MyClass instance = handle.Unwrap() as MyClass;

            Console.WriteLine("instance {0}", instance.GetHashCode());

            // Проверка: Действительно ли прозрачный переходник предоставлен?
            Console.WriteLine("IsTransparentProxy(instance) : {0}",
                              RemotingServices.IsTransparentProxy(instance));

            // Вызов метода объекта, находящегося во втором домене.
            instance.Operation();

            // Delay
            Console.ReadKey();
        }
Beispiel #14
0
    private static RegistrationHelper GetRegistrationHelper(bool bCreateAppDomain, out AppDomain domain)
    {
        RegistrationHelper reg = null;

        domain = null;

        if (!bCreateAppDomain)
        {
            reg = new RegistrationHelper();
        }

        else
        {
            String dir = Path.GetDirectoryName(regConfig.AssemblyFile);

            AppDomainSetup domainOptions = new AppDomainSetup();

            domainOptions.ApplicationBase = dir;
            domain = AppDomain.CreateDomain("RegSvcs",
                                            null,
                                            domainOptions);
            if (domain != null)
            {
                AssemblyName n = typeof(RegistrationHelper).Assembly.GetName();
                ObjectHandle h = domain.CreateInstance(n.FullName, typeof(RegistrationHelper).FullName);
                if (h != null)
                {
                    reg = (RegistrationHelper)h.Unwrap();
                }
            }
        }

        return(reg);
    }
Beispiel #15
0
        /// <summary>
        /// Initialize the AppDomain and load the types of the dll
        /// </summary>
        /// <returns>the types of the dll</returns>
        public void CreateAppDomain()
        {
            string currentDirectory = Environment.CurrentDirectory;
            string cachePath        = Path.Combine(
                currentDirectory,
                "__cache");

            PermissionSet  permissionSet  = new PermissionSet(PermissionState.Unrestricted);
            AppDomainSetup appDomainSetup = new AppDomainSetup
            {
                ApplicationBase = AppDomain.CurrentDomain.BaseDirectory,
                ShadowCopyFiles = "true",
                CachePath       = cachePath
            };

            _testsDomain = AppDomain.CreateDomain("TestDomain", null, appDomainSetup, permissionSet);

            try
            {
                ITypesLoaderFactory typesLoaderFactory = (ITypesLoaderFactory)_testsDomain.CreateInstance(Assembly.GetExecutingAssembly().FullName, " RegTesting.Tests.Core.TypesLoaderFactory").Unwrap();
                object[]            constructArgs      = new object[] { };
                ITypesLoader        typesLoader        = typesLoaderFactory.Create(Assembly.GetExecutingAssembly().FullName, " RegTesting.Tests.Core.TypesLoader", constructArgs);
                Types = typesLoader.GetTypes(_testsFile);
            }
            catch (NullReferenceException)
            {
            }
        }
Beispiel #16
0
        public static bool CheckDependencies(ref string message)
        {
            // Create an instance of dependent classes in a new AppDomain
            try
            {
                string rulesEngineConfigFile = CommonFunc.GetAppSettingsStringValue("NotSupportedByAzureSQLDb");
                if (rulesEngineConfigFile.Length > 0 && !File.Exists(rulesEngineConfigFile))
                {
                    message = CommonFunc.FormatString(Properties.Resources.ErrorFileNotFound, rulesEngineConfigFile);
                    return(false);
                }

                AppDomain newAppDomain = AppDomain.CreateDomain("DependencyChecker");
                foreach (Dependency depOn in Dependencies)
                {
                    newAppDomain.CreateInstance(depOn.Assembly, depOn.Type);
                }
            }
            catch (Exception ex)
            {
                Assembly     assem     = Assembly.GetEntryAssembly();
                AssemblyName assemName = assem.GetName();

                message = CommonFunc.FormatString(Properties.Resources.ErrorMissingDependencies, assemName.Name, ex.Message);
                return(false);
            }
            return(true);
        }
Beispiel #17
0
        public void creatAppDomain()
        {
            //步骤一:设置domain的环境
            AppDomainSetup setup = new AppDomainSetup();

            setup.ApplicationName       = "AppLoader";
            setup.ApplicationBase       = AppDomain.CurrentDomain.BaseDirectory;
            setup.PrivateBinPath        = AppDomain.CurrentDomain.BaseDirectory;// "plugins";
            setup.CachePath             = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CachePath");;
            setup.ShadowCopyFiles       = "true";
            setup.ShadowCopyDirectories = string.Concat(setup.ApplicationBase, ";", setup.PrivateBinPath);

            //步骤二:生成一个新的domain
            this._domain = AppDomain.CreateDomain(string.Concat("AppLoaderDomain_", Guid.NewGuid().ToString()), null, setup);

            //步骤三:在新的domain里面创建实例

            ///方法一:CreateInstanceAndUnwrap
            ///这是合并的便捷方法 CreateInstance和 ObjectHandleUnwrap。此方法调用的默认构造函数typeName。
            ///
            ///CreateInstanceAndUnwrap 会与新的dll绑定,因为返回一个引用是用到新的dll,而这个引用是在父Domain里的。
            ///使用,就要加上AppDomain.CurrentDomain.SetShadowCopyFiles()这一句,就可以覆盖dll
            ///
            //AppDomain.CurrentDomain.SetShadowCopyFiles();
            //var ret = _domain.CreateInstanceAndUnwrap("Plugin1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Plugin1.pluginClass");

            ///方法二:CreateInstance
            ///
            _domain.CreateInstance("pluginWinD", "pluginWinD.pluginClass");

            AppDomain.Unload(_domain);
        }
Beispiel #18
0
        /// <summary>
        /// Create the instance named or inherited by typeFullName
        /// </summary>
        /// <param name="code">code string or source code file name</param>
        /// <param name="typeFullName">the full name of type</param>
        /// <param name="fromFile">from file or from code string</param>
        /// <returns>instance object</returns>
        /// <remarks>If the type named or inherited by typefullname does not exits, return null</remarks>
        private object InnerCreateInstance(string code, string typeFullName, bool fromFile)
        {
            bool reCompile = false;

            if (fromFile)
            {
                reCompile = CompileFromFile(code);
            }
            else
            {
                reCompile = Compile(code);
            }

            if (reCompile)
            {
                AppDomainSetup appDomainSetup;

                appDomainSetup = new AppDomainSetup();
                appDomainSetup.LoaderOptimization    = LoaderOptimization.SingleDomain;
                appDomainSetup.ApplicationBase       = AppDomain.CurrentDomain.BaseDirectory;
                appDomainSetup.ShadowCopyDirectories = appDomainSetup.ApplicationBase;
                appDomainSetup.ShadowCopyFiles       = "true";
                _AppDomain = AppDomain.CreateDomain(AssemblyFileName, null, appDomainSetup);
            }

            RemoteLoader remoteLoader =
                (RemoteLoader)_AppDomain.CreateInstance("Compiler.Dynamic", "RemoteAccess.RemoteLoader").Unwrap();

            return(remoteLoader.Create(AssemblyFileName, typeFullName, null));
        }
Beispiel #19
0
        static void Main(string[] args)
        {
            //Информация о Main
            DomainClass main = new DomainClass();

            main.Function("Main");

            //Создание домена
            AppDomain domain = AppDomain.CreateDomain("Second domain");

            string assemblyName = Assembly.GetExecutingAssembly().GetName().Name;
            string typeName     = typeof(DomainClass).FullName;


            try
            {
                // Создание объекта во втором домене.
                ObjectHandle handel = domain.CreateInstance(assemblyName, typeName);

                // Создание прозрачного прокси-переходника для взаимодействия с объектом из другого домена.
                DomainClass instance = handel.Unwrap() as DomainClass;

                // Вызов метода объекта, находящегося во втором домене.
                instance.Function("Second domain");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception message: {0}", ex.Message);
            }

            // Выгрузка домена приложения.
            AppDomain.Unload(domain);

            Console.ReadKey();
        }
Beispiel #20
0
        public virtual int ExecuteTemplate()
        {
            // Execute the (initial) template by GenerationHost in separate AppDomain:
            AppDomain      appDomain = null;
            GenerationHost genHost   = null;

            try
            {
                AppDomainSetup info = new AppDomainSetup();
                info.ApplicationBase = new FileInfo(Assembly.GetEntryAssembly().Location).Directory.FullName;
                info.ShadowCopyFiles = "true";
                appDomain            = AppDomain.CreateDomain("CodeGenSpace", AppDomain.CurrentDomain.Evidence, info);
                genHost = (GenerationHost)appDomain.CreateInstance(typeof(GenerationHost).Assembly.FullName, typeof(GenerationHost).FullName).Unwrap();
                genHost.Initialize(this.Settings);
                return(this.ExecuteTemplate(genHost));
            }
            finally
            {
                if (genHost != null)
                {
                    genHost.Dispose();
                }
                if (appDomain != null)
                {
                    AppDomain.Unload(appDomain);
                }
            }
        }
Beispiel #21
0
        static void Main()
        {
            AppDomain domain = AppDomain.CreateDomain("Second Domain");

            domain.FirstChanceException += Domain_FirstChanceException;

            string assemblyName = Assembly.GetExecutingAssembly().GetName().Name;
            string typeName     = typeof(MyClass).FullName;

            ObjectHandle handle = domain.CreateInstance(assemblyName, typeName);

            MyClass instance = handle.Unwrap() as MyClass;

            try
            {
                instance.Operation();
            }
            catch (Exception ex)
            {
                Console.WriteLine("\nОбработчик исключения try-catch");
                Console.WriteLine("Исключение возникло в домене : {0}", domain.FriendlyName);
                Console.WriteLine("ex.Message                   : {0}", ex.Message);
            }

            Console.WriteLine("\nДомен {0} работоспособен.", AppDomain.CurrentDomain.FriendlyName);
            Console.WriteLine("Домен {0} работоспособен.", domain.FriendlyName);

            // Delay
            Console.ReadKey();
        }
 public static T CreateTypeIn <T>(AppDomain domain)
 {
     return
         ((T)
          domain.CreateInstance(GetAssemblyName <T>(),
                                typeof(T).FullName).Unwrap());
 }
        private object InvokeOperationImpl(string operation, Hashtable arguments, bool isVoid = false)
        {
            var resultHandler = new OperationResultHandler();

            // TODO: Set current directory
            _domain.CreateInstance(
                AssemblyName,
                TypeName + "+" + operation,
                false,
                0,
                null,
                new[] { _executor, resultHandler, arguments },
                null,
                null);

            if (resultHandler.ErrorType != null)
            {
                throw new WrappedOperationException(
                          resultHandler.ErrorMessage,
                          resultHandler.ErrorStackTrace,
                          resultHandler.ErrorType);
            }
            if (!isVoid &&
                !resultHandler.HasResult)
            {
                throw new InvalidOperationException(
                          $"A value was not returned for operation '{operation}'.");
            }

            return(resultHandler.Result);
        }
        //added by LiuShu 20101108
        /// <summary>
        /// 点击btnStrategyBrowse按钮加载策略
        /// </summary>
        /// <remarks>加载策略按钮按下时将用户选择的策略保存,同时提取队伍名称,将队伍名称发送给服务端</remarks>
        private void btnStrategyBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Filter       = "dll files (*.dll)|*.dll|All files (*.*)|*.*"; // 过滤文件类型
            openFileDialog.ShowReadOnly = true;                                          //设定文件是否只读

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                txtStrategy.Text     = openFileDialog.SafeFileName;                                    // 获取文件名
                _strStrategyFullName = openFileDialog.FileName;                                        // 获取包含完整路径的文件名
                string strStrategyCachePath      = Application.StartupPath + "\\StrategyCache\\";      // StrategyCache目录
                string strCachedStrategyFullName = strStrategyCachePath + openFileDialog.SafeFileName; // Cache的dll文件
                try
                {
                    if (!System.IO.Directory.Exists(strStrategyCachePath))
                    {
                        // 策略缓存目录不存在则新建
                        System.IO.Directory.CreateDirectory(strStrategyCachePath);
                    }

                    // 如果已经加载过策略dll则先卸载前一次加载策略所使用的应用程序域即可卸载已加载的dll文件
                    if (_appDomainForStrategy != null)
                    {
                        AppDomain.Unload(_appDomainForStrategy);
                        _appDomainForStrategy = null;
                        _strategyInterface    = null;
                    }
                    System.IO.File.Copy(_strStrategyFullName, strCachedStrategyFullName, true);
                }
                catch (System.IO.IOException)
                {//当有两支队伍加载同一个策略文件时会出现异常现象,这时
                    strCachedStrategyFullName = strCachedStrategyFullName.Replace(".dll", string.Format(" {0:0000}{1:00}{2:00} {3:00}{4:00}{5:00}.dll",
                                                                                                        DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day,
                                                                                                        DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second));

                    System.IO.File.Copy(_strStrategyFullName, strCachedStrategyFullName, true);
                }

                #region 使用AppDomain加载策略组件dll
                _appDomainForStrategy = AppDomain.CreateDomain("Client AppDomain For Strategy");

                // 使用AppDomain创建策略接口工厂类(StrategyInterfaceFactory)实例
                StrategyInterfaceFactory factory = (StrategyInterfaceFactory)_appDomainForStrategy.CreateInstance(
                    "URWPGSim2D.StrategyLoader", typeof(StrategyInterfaceFactory).FullName).Unwrap();

                // 使用策略接口工厂类实例创建策略接口实例
                _strategyInterface = factory.Create(strCachedStrategyFullName, "URWPGSim2D.Strategy.Strategy", null);
                #endregion

                // 将队伍名字显示到lblTeamName上
                lblTeamName.Text = _strategyInterface.GetTeamName();
                btnReady.Enabled = true;

                // 将TeamName传送给Client服务实例使其Announce给Server服务实例
                _fromClientUiPort.Post(new FromClientUiMsg(FromClientUiMsg.MsgEnum.STRATEGY_LOADED,
                                                           new string[] { lblTeamName.Text }));
            }
        }
        //-------------------< loader proxy instance by using ChildAppDomain >------------------------------
        public LoaderProxy getLoaderProxyInstance()
        {
            childAppDomain.Load("Loader");
            ObjectHandle oh          = childAppDomain.CreateInstance(typeof(LoaderProxy).Assembly.FullName, typeof(LoaderProxy).FullName);
            LoaderProxy  loaderProxy = oh.Unwrap() as LoaderProxy;

            return(loaderProxy);
        }
Beispiel #26
0
        private static void InitConfigInNewAppDomain(AppDomain appDomain)
        {
            Type             helperType = typeof(ConfigInitHelper);
            ObjectHandle     h          = appDomain.CreateInstance(helperType.Module.Assembly.FullName, helperType.FullName);
            ConfigInitHelper helper     = (ConfigInitHelper)h.Unwrap();

            helper.InitConfig();
        }
Beispiel #27
0
 public object CreateObject(object[] args)
 {
     try
     {
         retObject = Domain.CreateInstance(AsName, CsName, false, bfi, null, args, null, null).Unwrap();
     }
     catch {; }
     return(retObject);
 }
Beispiel #28
0
        public static IConstructionReturnMessage DoSimpleXADActivation(IConstructionCallMessage msg)
        {
            int       domain_no = Interlocked.Increment(ref _domain_no);
            AppDomain ad        = AppDomain.CreateDomain("AutoDomain #" + domain_no, null, null);

            activator a = (activator)(ad.CreateInstance(null, typeof(activator).FullName)).Unwrap();

            return(a.Activate(msg));
        }
 static void InstantiateMyDynamicType(AppDomain domain)
 {
     try {
         // You must supply a valid fully qualified assembly name here.
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyDynamicType");
     } catch (Exception e) {
         Console.WriteLine(e.Message);
     }
 }
Beispiel #30
0
        public void AppDomainCreator(List <Test> testList_)
        {
            {
                FileManager file = new FileManager();
                try
                {
                    AppDomain main = AppDomain.CurrentDomain;
                    Console.Write("\n  Starting in AppDomain {0}\n", main.FriendlyName);

                    // Create application domain setup information for new AppDomain
                    AppDomainSetup domaininfo = new AppDomainSetup();
                    domaininfo.ApplicationBase
                        = System.Environment.CurrentDirectory; // defines search path for assemblies

                    //Create evidence for the new AppDomain from evidence of current
                    Evidence adevidence = AppDomain.CurrentDomain.Evidence;

                    // Create Child AppDomain
                    AppDomain ad
                        = AppDomain.CreateDomain("ChildDomain", adevidence, domaininfo);

                    /////////////////////////////////////////////////////////////////////
                    //  Way to create ChildDomain using default evidence and domaininfo
                    //    AppDomain ad = AppDomain.CreateDomain("ChildDomain", null);
                    //Assembly assembly =Assembly.LoadFrom("TestDrive");
                    //Type names = assembly.GetType();
                    //Console.Write("jkdhfkjsdh"+names.FullName);
                    //Type type =(Type) assembly.GetExportedType();

                    Console.Write("\n\n");


                    ad.Load("Loader");
                    ObjectHandle oh
                        = ad.CreateInstance("Loader", "Loader.Loader");
                    object ob = oh.Unwrap();    // unwrap creates proxy to ChildDomain
                    // Console.Write("\n  {0}", ob);

                    Loader.Loader loader = (Loader.Loader)ob;
                    loader.getAssemblies(testList_);
                    List <TestData> testDriver = loader.executeTestCases();

                    results = loader.run(testDriver);
                    string fileName = testList_[0].author + DateTime.Now.ToFileTime();
                    StoreResultsInFile(fileName, results);


                    AppDomain.Unload(ad);
                    Console.Write("\n\n");
                }
                catch (Exception except)
                {
                    Console.Write("\n  {0}\n\n", except.Message);
                }
            }
        }