Example #1
1
		internal StackFrame(Thread thread, ICorDebugILFrame corILFrame, uint chainIndex, uint frameIndex)
		{
			this.process = thread.Process;
			this.thread = thread;
			this.appDomain = process.AppDomains[corILFrame.GetFunction().GetClass().GetModule().GetAssembly().GetAppDomain()];
			this.corILFrame = corILFrame;
			this.corILFramePauseSession = process.PauseSession;
			this.corFunction = corILFrame.GetFunction();
			this.chainIndex = chainIndex;
			this.frameIndex = frameIndex;
			
			MetaDataImport metaData = thread.Process.Modules[corFunction.GetClass().GetModule()].MetaData;
			int methodGenArgs = metaData.EnumGenericParams(corFunction.GetToken()).Length;
			// Class parameters are first, then the method ones
			List<ICorDebugType> corGenArgs = ((ICorDebugILFrame2)corILFrame).EnumerateTypeParameters().ToList();
			// Remove method parametrs at the end
			corGenArgs.RemoveRange(corGenArgs.Count - methodGenArgs, methodGenArgs);
			List<DebugType> genArgs = new List<DebugType>(corGenArgs.Count);
			foreach(ICorDebugType corGenArg in corGenArgs) {
				genArgs.Add(DebugType.CreateFromCorType(this.AppDomain, corGenArg));
			}
			
			DebugType debugType = DebugType.CreateFromCorClass(
				this.AppDomain,
				null,
				corFunction.GetClass(),
				genArgs.ToArray()
			);
			this.methodInfo = (DebugMethodInfo)debugType.GetMember(corFunction.GetToken());
		}
Example #2
0
    void ExecuteInOwnAppDomain()
    {
        if (WeaversHistory.HasChanged(Weavers.Select(x => x.AssemblyPath)) || appDomain == null)
        {
            if (appDomain != null)
            {
                AppDomain.Unload(appDomain);
            }

            var appDomainSetup = new AppDomainSetup
                                     {
                                         ApplicationBase = AssemblyLocation.CurrentDirectory(),
                                     };
            appDomain = AppDomain.CreateDomain("Fody", null, appDomainSetup);
        }
        var innerWeaver = (IInnerWeaver) appDomain.CreateInstanceAndUnwrap("FodyIsolated", "InnerWeaver");
        innerWeaver.AssemblyPath = AssemblyPath;
        innerWeaver.References = References;
        innerWeaver.KeyFilePath = KeyFilePath;
        innerWeaver.Logger = Logger;
        innerWeaver.AssemblyPath = AssemblyPath;
        innerWeaver.Weavers = Weavers;
        innerWeaver.IntermediateDir = IntermediateDir;
        innerWeaver.Execute();
    }
Example #3
0
 private static AppDomain BuildChildDomain(AppDomain parentDomain)
 {
     var evidence = new Evidence(parentDomain.Evidence);
     AppDomainSetup setup = parentDomain.SetupInformation;
     return AppDomain.CreateDomain("DiscoveryRegion",
         evidence, setup);
 }
Example #4
0
	public static Foo GetRemote (AppDomain domain)
	{
		Foo test = (Foo) domain.CreateInstanceAndUnwrap (
			typeof (Foo).Assembly.FullName,
			typeof (Foo).FullName, new object [0]);
		return test;
	}
Example #5
0
 static void DisplayDADStats(AppDomain domain)
 {
     // Get access to the AppDomain for the current thread
     Console.WriteLine("Name of this domain: {0}", domain.FriendlyName);
     Console.WriteLine("ID of domain in this process: {0}", domain.Id);
     Console.WriteLine("Is this the default domain?: {0}", domain.IsDefaultAppDomain());
     Console.WriteLine("Base Directory of this domain: {0}", domain.BaseDirectory);
 }
		internal SecurityFrame (RuntimeSecurityFrame frame)
		{
			_domain = null;
			_method = null;
			_assert = null;
			_deny = null;
			_permitonly = null;
			InitFromRuntimeFrame (frame);
		}
Example #7
0
File: test.cs Project: mono/gert
	static CrossDomainTester CreateCrossDomainTester (AppDomain domain)
	{
		Type testerType = typeof (CrossDomainTester);

		return (CrossDomainTester) domain.CreateInstanceAndUnwrap (
			testerType.Assembly.FullName, testerType.FullName, false,
			BindingFlags.Public | BindingFlags.Instance, null, new object [0],
			CultureInfo.InvariantCulture, new object [0], domain.Evidence);
	}
 private static void Main()
 {
     Class32.appDomain_0 = AppDomain.CreateDomain("NovoFatum R3", null);
     Class1.smethod_0();
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Class0.main_0 = new Main();
     Application.Run(Class0.main_0);
 }
Example #9
0
 static void ListAllAssembliesInAppDomain(AppDomain domain)
 {
     Assembly[] loadedAssemblies = domain.GetAssemblies();
     Console.WriteLine("**** Here are the assemblies loaded in {0} ******\n",
             domain.FriendlyName);
     foreach (Assembly a in loadedAssemblies) {
         Console.WriteLine("-> Name: {0}", a.GetName().Name);
         Console.WriteLine("-> Version: {0}", a.GetName().Version);
     }
 }
		internal SecurityFrame (int skip)
		{
			_domain = null;
			_method = null;
			_assert = null;
			_deny = null;
			_permitonly = null;

			InitFromRuntimeFrame (_GetSecurityFrame (skip + 2));

			// TODO - add the imperative informations into the frame
		}
	static int Main ()
	{
		AppDomain.Unload (AppDomain.CreateDomain ("Warmup unload code"));
		Console.WriteLine (".");
		ad = AppDomain.CreateDomain ("NewDomain");
		ad.DoCallBack (Bla);
		var t = new Thread (UnloadIt);
		t.IsBackground = true;
		t.Start ();
		evt.WaitOne ();
		return 0;
	}
Example #12
0
    static void ListAllAssembliesInAppDomain2(AppDomain domain)
    {
        var loadedAssemblies = from a in domain.GetAssemblies()
            orderby a.GetName().Name select a;

        Console.WriteLine("**** Here are the assemblies loaded in {0} ******\n",
                domain.FriendlyName);
        foreach (var a in loadedAssemblies) {
            Console.WriteLine("-> Name: {0}", a.GetName().Name);
            Console.WriteLine("-> Version: {0}", a.GetName().Version);
        }
    }
Example #13
0
	static Assembly DefineDynamicAssembly (AppDomain domain)
	{
		AssemblyName assemblyName = new AssemblyName ();
		assemblyName.Name = "MyDynamicAssembly";

		AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly (assemblyName, AssemblyBuilderAccess.Run);
		ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule ("MyDynamicModule");
		TypeBuilder typeBuilder = moduleBuilder.DefineType ("MyDynamicType", TypeAttributes.Public);
		ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor (MethodAttributes.Public, CallingConventions.Standard, null);
		ILGenerator ilGenerator = constructorBuilder.GetILGenerator ();
		ilGenerator.EmitWriteLine ("MyDynamicType instantiated!");
		ilGenerator.Emit (OpCodes.Ret);
		typeBuilder.CreateType ();
		return assemblyBuilder;
	}
Example #14
0
    static void InitDAD(AppDomain domain)
    {
        // this prints out the name of any assembly
        // loaded into the domain, after it has been
        // created.
        domain.AssemblyLoad += (o, s) =>
        {
            Console.WriteLine("\n{0} has just now been loaded!!\n", s.LoadedAssembly.GetName().Name);
        };

        domain.ProcessExit += (o, s) =>
        {
            Console.WriteLine("\nAD has just been unloaded!!\n");
        };
    }
        internal ManifestRunner (AppDomain domain, ActivationContext activationContext) {
            m_domain = domain;

            string file, parameters;
            CmsUtils.GetEntryPoint(activationContext, out file, out parameters);
            if (parameters == null || parameters.Length == 0)
                m_args = new string[0];
            else
                m_args = parameters.Split(' ');

            m_apt = ApartmentState.Unknown;

            // get the 'merged' application directory path.
            string directoryName = activationContext.ApplicationDirectory;
            m_path = Path.Combine(directoryName, file);
        }
Example #16
0
		Eval(AppDomain appDomain, string description, EvalStarter evalStarter)
		{
			this.appDomain = appDomain;
			this.process = appDomain.Process;
			this.description = description;
			this.state = EvalState.Evaluating;
			this.thread = GetEvaluationThread(appDomain);
			this.corEval = thread.CorThread.CreateEval();
			
			try {
				evalStarter(this);
			} catch (COMException e) {
				if ((uint)e.ErrorCode == 0x80131C26) {
					throw new GetValueException("Can not evaluate in optimized code");
				} else if ((uint)e.ErrorCode == 0x80131C28) {
					throw new GetValueException("Object is in wrong AppDomain");
				} else if ((uint)e.ErrorCode == 0x8013130A) {
					// Happens on getting of Sytem.Threading.Thread.ManagedThreadId; See SD2-1116
					throw new GetValueException("Function does not have IL code");
				} else if ((uint)e.ErrorCode == 0x80131C23) {
					// The operation failed because it is a GC unsafe point. (Exception from HRESULT: 0x80131C23)
					// This can probably happen when we break and the thread is in native code
					throw new GetValueException("Thread is in GC unsafe point");
				} else if ((uint)e.ErrorCode == 0x80131C22) {
					// The operation is illegal because of a stack overflow.
					throw new GetValueException("Can not evaluate after stack overflow");
				} else if ((uint)e.ErrorCode == 0x80131313) {
					// Func eval cannot work. Bad starting point.
					// Reproduction circumstancess are unknown
					throw new GetValueException("Func eval cannot work. Bad starting point.");
				} else {
					#if DEBUG
						throw; // Expose for more diagnostics
					#else
						throw new GetValueException(e.Message);
					#endif
				}
			}
			
			appDomain.Process.ActiveEvals.Add(this);
			
			if (appDomain.Process.Options.SuspendOtherThreads) {
				appDomain.Process.AsyncContinue(DebuggeeStateAction.Keep, new Thread[] { thread }, CorDebugThreadState.THREAD_SUSPEND);
			} else {
				appDomain.Process.AsyncContinue(DebuggeeStateAction.Keep, this.Process.UnsuspendedThreads, CorDebugThreadState.THREAD_RUN);
			}
		}
        internal ManifestRunner (AppDomain domain, ActivationContext activationContext) {
            m_domain = domain;

            string file, parameters;
            CmsUtils.GetEntryPoint(activationContext, out file, out parameters);

            if (String.IsNullOrEmpty(file))
                throw new ArgumentException(Environment.GetResourceString("Argument_NoMain"));

            if (String.IsNullOrEmpty(parameters))
                m_args = new string[0];
            else
                m_args = parameters.Split(' ');

            m_apt = ApartmentState.Unknown;

            // get the 'merged' application directory path.
            string directoryName = activationContext.ApplicationDirectory;
            m_path = Path.Combine(directoryName, file);
        }
Example #18
0
        internal Module(AppDomain appDomain, ICorDebugModule corModule)
        {
            this.appDomain = appDomain;
            this.process = appDomain.Process;
            this.corModule = corModule;

            metaData = new MetaDataImport(corModule);

            if (IsDynamic || IsInMemory) {
                name     = corModule.GetName();
            } else {
                fullPath = corModule.GetName();
                name     = System.IO.Path.GetFileName(FullPath);
            }
            asmFilename = corModule.GetAssembly().GetName();

            SetJITCompilerFlags();

            LoadSymbolsFromDisk(process.Options.SymbolsSearchPaths);
            ResetJustMyCodeStatus();
        }
Example #19
0
   private static Type MyCreateCallee(AppDomain domain)
   {
      AssemblyName myAssemblyName = new AssemblyName();
      myAssemblyName.Name = "EmittedAssembly";
      // Define a dynamic assembly in the current application domain.
      AssemblyBuilder myAssembly =
                  domain.DefineDynamicAssembly(myAssemblyName,AssemblyBuilderAccess.Run);
      // Define a dynamic module in this assembly.
      ModuleBuilder myModuleBuilder = myAssembly.DefineDynamicModule("EmittedModule");
      // Construct a 'TypeBuilder' given the name and attributes.
      TypeBuilder myTypeBuilder = myModuleBuilder.DefineType("HelloWorld",
         TypeAttributes.Public);
      // Define a constructor of the dynamic class.
      ConstructorBuilder myConstructor = myTypeBuilder.DefineConstructor(
               MethodAttributes.Public, CallingConventions.Standard, new Type[]{typeof(String)});
      ILGenerator myILGenerator = myConstructor.GetILGenerator();
      myILGenerator.Emit(OpCodes.Ldstr, "Constructor is invoked");
      myILGenerator.Emit(OpCodes.Ldarg_1);
      MethodInfo myMethodInfo =
                     typeof(Console).GetMethod("WriteLine",new Type[]{typeof(string)});
      myILGenerator.Emit(OpCodes.Call, myMethodInfo);
      myILGenerator.Emit(OpCodes.Ret);
      Type myType = typeof(MyAttribute);
      ConstructorInfo myConstructorInfo = myType.GetConstructor(new Type[]{typeof(object)});
      try
      {
        CustomAttributeBuilder methodCABuilder = new CustomAttributeBuilder (myConstructorInfo, new object [] { TypeCode.Double } );        

         myConstructor.SetCustomAttribute(methodCABuilder);
      }
      catch(ArgumentNullException ex)
      {
         Console.WriteLine("The following exception has occured : "+ex.Message);
      }
      catch(Exception ex)
      {
         Console.WriteLine("The following exception has occured : "+ex.Message);
      }
      return myTypeBuilder.CreateType();
   }
Example #20
0
        internal Value(AppDomain appDomain, ICorDebugValue corValue)
        {
            if (corValue == null)
                throw new ArgumentNullException("corValue");
            this.appDomain = appDomain;
            this.corValue = corValue;
            this.corValue_pauseSession = this.Process.PauseSession;

            this.isNull = corValue is ICorDebugReferenceValue && ((ICorDebugReferenceValue)corValue).IsNull() != 0;

            if (corValue is ICorDebugReferenceValue &&
                ((ICorDebugReferenceValue)corValue).GetValue() == 0 &&
                ((ICorDebugValue2)corValue).GetExactType() == null)
            {
                // We were passed null reference and no metadata description
                // (happens during CreateThread callback for the thread object)
                this.type = appDomain.ObjectType;
            } else {
                ICorDebugType exactType = ((ICorDebugValue2)this.CorValue).GetExactType();
                this.type = DebugType.CreateFromCorType(appDomain, exactType);
            }
        }
Example #21
0
 private static void InstallAssemblyLoader(AppDomain domain)
 {
     domain.ReflectionOnlyAssemblyResolve += (sender, args) => Assembly.ReflectionOnlyLoadFrom(
         Path.Combine(ProgramDirectory, args.Name.Substring(0, args.Name.IndexOf(',')) + ".dll"));
 }
Example #22
0
        //multiple app domains
        private static void Example2()
        {
            //create instance for running threads in the current AppDomain
            AppDomain domain1 = AppDomain.CreateDomain("Domain-1");
            AppDomain domain2 = AppDomain.CreateDomain("Domain-2");
            Program   p1      = (Program)domain1.CreateInstanceFromAndUnwrap("2_TLSContext.exe", "_2_TLSContext.Program");
            Program   p2      = (Program)domain2.CreateInstanceFromAndUnwrap("2_TLSContext.exe", "_2_TLSContext.Program");

            //start on same domain...
            ThreadPool.QueueUserWorkItem((x) => p1.SomeMethod(1));
            ThreadPool.QueueUserWorkItem((x) => p1.SomeMethod(2));
            ThreadPool.QueueUserWorkItem((x) => p1.SomeMethod(3));
            ThreadPool.QueueUserWorkItem((x) => p1.SomeMethod(4));
            ThreadPool.QueueUserWorkItem((x) => p1.SomeMethod(5));
            ThreadPool.QueueUserWorkItem((x) => p1.SomeMethod(6));
            ThreadPool.QueueUserWorkItem((x) => p1.SomeMethod(7));
            ThreadPool.QueueUserWorkItem((x) => p1.SomeMethod(8));
            ThreadPool.QueueUserWorkItem((x) => p1.SomeMethod(9));
            ThreadPool.QueueUserWorkItem((x) => p1.SomeMethod(10));

            //now demonstrate 2nd AppDomain uniqueness
            ThreadPool.QueueUserWorkItem((x) => p2.SomeMethod(10));
            ThreadPool.QueueUserWorkItem((x) => p2.SomeMethod(11));
            ThreadPool.QueueUserWorkItem((x) => p2.SomeMethod(12));
            ThreadPool.QueueUserWorkItem((x) => p2.SomeMethod(13));
            ThreadPool.QueueUserWorkItem((x) => p2.SomeMethod(14));
            ThreadPool.QueueUserWorkItem((x) => p2.SomeMethod(15));
            ThreadPool.QueueUserWorkItem((x) => p2.SomeMethod(16));
            ThreadPool.QueueUserWorkItem((x) => p2.SomeMethod(17));
            ThreadPool.QueueUserWorkItem((x) => p2.SomeMethod(18));
            ThreadPool.QueueUserWorkItem((x) => p1.SomeMethod(19));
            ThreadPool.QueueUserWorkItem((x) => p1.SomeMethod(20));

            /* Output
             * Creating new context. Thread: 12 AppDomain: Domain-1
             * Creating new context. Thread: 14 AppDomain: Domain-1
             * Creating new context. Thread: 13 AppDomain: Domain-1
             * Thread 14 AppDomain: Domain-1                  Prev Value:  0 New Value:  4
             * Thread 12 AppDomain: Domain-1                  Prev Value:  0 New Value:  3
             * Thread 14 AppDomain: Domain-1                  Prev Value:  4 New Value:  5
             * Thread 13 AppDomain: Domain-1                  Prev Value:  0 New Value:  1
             * Creating new context. Thread: 11 AppDomain: Domain-1
             * Thread 11 AppDomain: Domain-1                  Prev Value:  0 New Value:  2
             * Thread 12 AppDomain: Domain-1                  Prev Value:  3 New Value:  6
             * Thread 14 AppDomain: Domain-1                  Prev Value:  5 New Value:  7
             * Thread 13 AppDomain: Domain-1                  Prev Value:  1 New Value:  8
             * Thread 11 AppDomain: Domain-1                  Prev Value:  2 New Value:  9
             * Thread 12 AppDomain: Domain-1                  Prev Value:  6 New Value: 10
             * Creating new context. Thread: 12 AppDomain: Domain-2
             * Creating new context. Thread: 14 AppDomain: Domain-2
             * Creating new context. Thread: 11 AppDomain: Domain-2
             * Thread 14 AppDomain: Domain-2                  Prev Value:  0 New Value: 10
             * Creating new context. Thread: 13 AppDomain: Domain-2
             * Thread 11 AppDomain: Domain-2                  Prev Value:  0 New Value: 12
             * Thread 14 AppDomain: Domain-2                  Prev Value: 10 New Value: 14
             * Thread 11 AppDomain: Domain-2                  Prev Value: 12 New Value: 15
             * Thread 13 AppDomain: Domain-2                  Prev Value:  0 New Value: 11
             * Thread 12 AppDomain: Domain-2                  Prev Value:  0 New Value: 13
             * Thread 14 AppDomain: Domain-2                  Prev Value: 14 New Value: 16
             * Thread 13 AppDomain: Domain-2                  Prev Value: 11 New Value: 18
             * Thread 11 AppDomain: Domain-2                  Prev Value: 15 New Value: 17
             * Thread 12 AppDomain: Domain-1                  Prev Value: 10 New Value: 19
             * Thread 14 AppDomain: Domain-1                  Prev Value:  7 New Value: 20 */
        }
Example #23
0
		static AppDomain()
		{
			CurrentDomain = new AppDomain();
		}
Example #24
0
        public static EmbeddedAssemblyLoader Register(string resourceNamespace, Assembly assembly = null, AppDomain domain = null)
        {
            assembly = assembly ?? Assembly.GetCallingAssembly();
            var loader = new EmbeddedAssemblyLoader(resourceNamespace, assembly);

            loader.Register(domain);
            return(loader);
        }
Example #25
0
        private void LoadPlugin(PluginInfo info, string[] excludedPlugins)
        {
            lock (SyncObject)
            {
                var domainSetup = new AppDomainSetup();
                domainSetup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
                domainSetup.PrivateBinPath  = "plugins;bin";

                var permissions = new PermissionSet(PermissionState.None);
                permissions.AddPermission(new UIPermission(PermissionState.Unrestricted));

                permissions.AddPermission(new SecurityPermission(
                                              SecurityPermissionFlag.Execution |
                                              SecurityPermissionFlag.SerializationFormatter |
                                              SecurityPermissionFlag.UnmanagedCode)); // TODO: wpf need it :(

                permissions.AddPermission(new FileIOPermission(
                                              FileIOPermissionAccess.PathDiscovery |
                                              FileIOPermissionAccess.Write |
                                              FileIOPermissionAccess.Read,
                                              AppDomain.CurrentDomain.BaseDirectory));

                var engineStrongName = typeof(TPlugin).Assembly.Evidence.GetHostEvidence <StrongName>();
                if (engineStrongName == null)
                {
                    OnError("Can't load plugins. Engine library without strong name.", null);
                    return;
                }

                var pluginName = string.Empty;
                var domainName = string.Format("Plugin Domain [{0}]", Path.GetFileNameWithoutExtension(info.AssemblyPath));
                var domain     = AppDomain.CreateDomain(domainName, null, domainSetup, permissions, engineStrongName);
                try
                {
                    var plugin = (TPlugin)domain.CreateInstanceFromAndUnwrap(info.AssemblyPath, info.TypeName);
                    info.Name  = plugin.Name;
                    pluginName = plugin.Name;

                    if (Plugins.ContainsKey(pluginName) || (excludedPlugins != null && excludedPlugins.Contains(pluginName)))
                    {
                        AppDomain.Unload(domain);
                        return;
                    }

                    var model = new TModel();

                    plugin.Initialize(model);

                    var container = new PluginContainer(domain, plugin, model);
                    Plugins.Add(pluginName, container);

                    OnPluginLoaded(container);
                }
                catch (Exception e)
                {
                    OnError(string.Format("Plugin failed: {0}", pluginName), e);

                    if (UnloadPlugin(pluginName))
                    {
                        return;
                    }

                    AppDomain.Unload(domain);
                }
            }
        }
Example #26
0
        public ToolingFacade(
            string migrationsAssemblyName,
            string contextAssemblyName,
            string configurationTypeName,
            string workingDirectory,
            string configurationFilePath,
            string dataDirectory,
            DbConnectionInfo connectionStringInfo)
        {
            Check.NotEmpty(migrationsAssemblyName, "migrationsAssemblyName");

            _migrationsAssemblyName = migrationsAssemblyName;
            _contextAssemblyName = contextAssemblyName;
            _configurationTypeName = configurationTypeName;
            _connectionStringInfo = connectionStringInfo;

            var info = new AppDomainSetup
                {
                    ShadowCopyFiles = "true"
                };

            if (!string.IsNullOrWhiteSpace(workingDirectory))
            {
                info.ApplicationBase = workingDirectory;
            }

            _configurationFile = new ConfigurationFileUpdater().Update(configurationFilePath);
            info.ConfigurationFile = _configurationFile;

            var friendlyName = "MigrationsToolingFacade" + Convert.ToBase64String(Guid.NewGuid().ToByteArray());

            _appDomain = AppDomain.CreateDomain(friendlyName, null, info);

            if (!string.IsNullOrWhiteSpace(dataDirectory))
            {
                _appDomain.SetData("DataDirectory", dataDirectory);
            }
        }
Example #27
0
 public void GetCurrentThreadId()
 {
     Assert.Equal(AppDomain.GetCurrentThreadId(), Environment.CurrentManagedThreadId);
 }
Example #28
0
    public static Type BuildMyType()
    {
        AppDomain    myDomain  = Thread.GetDomain();
        AssemblyName myAsmName = new AssemblyName();

        myAsmName.Name = "MyDynamicAssembly";

        AssemblyBuilder myAsmBuilder = myDomain.DefineDynamicAssembly(
            myAsmName,
            AssemblyBuilderAccess.Run);
        ModuleBuilder myModBuilder = myAsmBuilder.DefineDynamicModule(
            "MyJumpTableDemo");

        TypeBuilder myTypeBuilder = myModBuilder.DefineType("JumpTableDemo",
                                                            TypeAttributes.Public);
        MethodBuilder myMthdBuilder = myTypeBuilder.DefineMethod("SwitchMe",
                                                                 MethodAttributes.Public |
                                                                 MethodAttributes.Static,
                                                                 typeof(string),
                                                                 new Type[] { typeof(int) });

        ILGenerator myIL = myMthdBuilder.GetILGenerator();

        Label defaultCase = myIL.DefineLabel();
        Label endOfMethod = myIL.DefineLabel();

        // We are initializing our jump table. Note that the labels
        // will be placed later using the MarkLabel method.

        Label[] jumpTable = new Label[] { myIL.DefineLabel(),
                myIL.DefineLabel(),
                myIL.DefineLabel(),
                myIL.DefineLabel(),
                myIL.DefineLabel() };

        // arg0, the number we passed, is pushed onto the stack.
        // In this case, due to the design of the code sample,
        // the value pushed onto the stack happens to match the
        // index of the label (in IL terms, the index of the offset
        // in the jump table). If this is not the case, such as
        // when switching based on non-integer values, rules for the correspondence
        // between the possible case values and each index of the offsets
        // must be established outside of the ILGenerator.Emit calls,
        // much as a compiler would.

        myIL.Emit(OpCodes.Ldarg_0);
        myIL.Emit(OpCodes.Switch, jumpTable);

        // Branch on default case
        myIL.Emit(OpCodes.Br_S, defaultCase);

        // Case arg0 = 0
        myIL.MarkLabel(jumpTable[0]);
        myIL.Emit(OpCodes.Ldstr, "are no bananas");
        myIL.Emit(OpCodes.Br_S, endOfMethod);

        // Case arg0 = 1
        myIL.MarkLabel(jumpTable[1]);
        myIL.Emit(OpCodes.Ldstr, "is one banana");
        myIL.Emit(OpCodes.Br_S, endOfMethod);

        // Case arg0 = 2
        myIL.MarkLabel(jumpTable[2]);
        myIL.Emit(OpCodes.Ldstr, "are two bananas");
        myIL.Emit(OpCodes.Br_S, endOfMethod);

        // Case arg0 = 3
        myIL.MarkLabel(jumpTable[3]);
        myIL.Emit(OpCodes.Ldstr, "are three bananas");
        myIL.Emit(OpCodes.Br_S, endOfMethod);

        // Case arg0 = 4
        myIL.MarkLabel(jumpTable[4]);
        myIL.Emit(OpCodes.Ldstr, "are four bananas");
        myIL.Emit(OpCodes.Br_S, endOfMethod);

        // Default case
        myIL.MarkLabel(defaultCase);
        myIL.Emit(OpCodes.Ldstr, "are many bananas");

        myIL.MarkLabel(endOfMethod);
        myIL.Emit(OpCodes.Ret);

        return(myTypeBuilder.CreateType());
    }
Example #29
0
 private SiloHandle StartOrleansSilo(Silo.SiloType type, TestingSiloOptions options, int instanceCount, AppDomain shared = null)
 {
     return(StartOrleansSilo(this, type, options, instanceCount, shared));
 }
Example #30
0
        public static int RunFromMostRecent(System.Reflection.MethodInfo method, string[] cmdargs, AutoUpdateStrategy defaultstrategy = AutoUpdateStrategy.CheckDuring)
        {
            // If the update is disabled, go straight in
            if (DISABLE_UPDATE_DOMAIN)
            {
                return(RunMethod(method, cmdargs));
            }

            // If we are not the primary domain, just execute
            if (!AppDomain.CurrentDomain.IsDefaultAppDomain())
            {
                int r = 0;
                WrapWithUpdater(defaultstrategy, () => {
                    r = RunMethod(method, cmdargs);
                });

                return(r);
            }

            // If we are a re-launch, wait briefly for the other process to exit
            var sleepmarker = System.Environment.GetEnvironmentVariable(string.Format(SLEEP_ENVNAME_TEMPLATE, APPNAME));

            if (!string.IsNullOrWhiteSpace(sleepmarker))
            {
                System.Environment.SetEnvironmentVariable(string.Format(SLEEP_ENVNAME_TEMPLATE, APPNAME), null);
                System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10));
            }

            // Check if there are updates installed, otherwise use current
            KeyValuePair <string, UpdateInfo> best = new KeyValuePair <string, UpdateInfo>(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, SelfVersion);

            if (HasUpdateInstalled)
            {
                best = m_hasUpdateInstalled.Value;
            }

            if (INSTALLDIR != null && System.IO.File.Exists(System.IO.Path.Combine(INSTALLDIR, CURRENT_FILE)))
            {
                try
                {
                    var current = System.IO.File.ReadAllText(System.IO.Path.Combine(INSTALLDIR, CURRENT_FILE)).Trim();
                    if (!string.IsNullOrWhiteSpace(current))
                    {
                        var targetfolder    = System.IO.Path.Combine(INSTALLDIR, current);
                        var currentmanifest = ReadInstalledManifest(targetfolder);
                        if (currentmanifest != null && VerifyUnpackedFolder(targetfolder, currentmanifest))
                        {
                            best = new KeyValuePair <string, UpdateInfo>(targetfolder, currentmanifest);
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (OnError != null)
                    {
                        OnError(ex);
                    }
                }
            }

            Environment.SetEnvironmentVariable(string.Format(INSTALLDIR_ENVNAME_TEMPLATE, APPNAME), InstalledBaseDir);

            var folder = best.Key;

            // Basic idea with the loop is that the running AppDomain can use
            // RUN_UPDATED_ENVNAME_TEMPLATE to signal that a new version is ready
            // when the caller exits, the new update is executed
            //
            // This allows more or less seamless updates
            //

            int result = 0;

            while (!string.IsNullOrWhiteSpace(folder) && System.IO.Directory.Exists(folder))
            {
                var prevfolder = folder;
                // Create the new domain
                var domain = AppDomain.CreateDomain(
                    "UpdateDomain",
                    null,
                    folder,
                    "",
                    false
                    );

                result = domain.ExecuteAssemblyByName(method.DeclaringType.Assembly.GetName().Name, cmdargs);

                folder = (string)domain.GetData(RUN_UPDATED_FOLDER_PATH);

                try { AppDomain.Unload(domain); }
                catch (Exception ex)
                {
                    Console.WriteLine("Appdomain unload error: {0}", ex);
                }

                if (!string.IsNullOrWhiteSpace(folder))
                {
                    if (!VerifyUnpackedFolder(folder))
                    {
                        folder = prevfolder; //Go back and run the previous version
                    }
                    else if (RequiresRespawn)
                    {
                        // We have a valid update, and the current instance is terminated.
                        // But due to external libraries, we need to re-spawn the original process

                        try
                        {
                            var args = Environment.CommandLine;
                            var app  = Environment.GetCommandLineArgs().First();
                            args = args.Substring(app.Length);

                            if (!System.IO.Path.IsPathRooted(app))
                            {
                                app = System.IO.Path.Combine(InstalledBaseDir, app);
                            }


                            // Re-launch but give the OS a little time to fully unload all open handles, etc.
                            var si = new System.Diagnostics.ProcessStartInfo(app, args);
                            si.UseShellExecute = false;
                            si.EnvironmentVariables.Add(string.Format(SLEEP_ENVNAME_TEMPLATE, APPNAME), "1");

                            System.Diagnostics.Process.Start(si);

                            return(0);
                        }
                        catch (Exception ex)
                        {
                            if (OnError != null)
                            {
                                OnError(ex);
                            }
                            folder = prevfolder;
                        }
                    }
                }
            }

            return(result);
        }
Example #31
0
        /// <summary>
        /// This closes the scrpit, removes it from any known spots, and disposes of itself.
        /// </summary>
        /// <param name="Silent">Should we back up this script and fire state_exit?</param>
        public void CloseAndDispose(bool Silent)
        {
// this is still broken ?
            m_ScriptEngine.MaintenanceThread.RemoveFromEventSchQueue(this, true);

            if (!Silent)
            {
                if (Script != null)
                {
                    /*
                     * //Fire this directly so its not closed before its fired
                     * SetEventParams("state_exit", new DetectParams[0]);
                     *
                     * m_ScriptEngine.MaintenanceThread.ProcessQIS(new QueueItemStruct()
                     * {
                     *  ID = this,
                     *  CurrentlyAt = null,
                     *  functionName = "state_exit",
                     *  param = new object[0],
                     *  llDetectParams = new DetectParams[0],
                     *  VersionID = VersionID
                     * });
                     */
                    // dont think we should fire state_exit here
                    //                    m_ScriptEngine.MaintenanceThread.DoAndWaitEventSch(this, "state_exit",
                    //                        new DetectParams[0], VersionID, EventPriority.FirstStart, new object[0]);
                    m_ScriptEngine.StateSave.SaveStateTo(this);
                }
            }
            VersionID += 5;
            m_ScriptEngine.MaintenanceThread.SetEventSchSetIgnoreNew(this, false);

            //Give the user back any controls we took
            ReleaseControls();

            // Tell script not to accept new requests
            //These are fine to set as the state wont be saved again
            if (!Silent)
            {
                Running  = false;
                Disabled = true;
            }

            // Remove from internal structure
            ScriptEngine.ScriptProtection.RemoveScript(this);
//            if (!Silent) //Don't remove on a recompile because we'll make it under a different assembly
//                ScriptEngine.ScriptProtection.RemovePreviouslyCompiled(Source);

            //Remove any errors that might be sitting around
            m_ScriptEngine.ScriptErrorReporter.RemoveError(ItemID);

            #region Clean out script parts

            //Only if this script changed target omega do we reset it
            if (TargetOmegaWasSet)
            {
                Part.AngularVelocity = Vector3.Zero;                  // Removed in SL
                Part.ScheduleUpdate(PrimUpdateFlags.AngularVelocity); // Send changes to client.
            }

            #endregion

            if (Script != null)
            {
                // Stop long command on script
                m_ScriptEngine.RemoveScript(Part.UUID, ItemID);

                //Release the script and destroy it
                ILease lease = (ILease)RemotingServices.GetLifetimeService(Script as MarshalByRefObject);
                if (lease != null)
                {
                    lease.Unregister(Script.Sponsor);
                }

                Script.Close();
                Script = null;
            }

            if (AppDomain == null)
            {
                return;
            }

            // Tell AppDomain that we have stopped script
            m_ScriptEngine.AppDomainManager.UnloadScriptAppDomain(AppDomain);
            AppDomain = null;

            m_log.Debug("[" + m_ScriptEngine.ScriptEngineName + "]: Closed Script " + InventoryItem.Name + " in " + Part.Name);
        }
Example #32
0
        public static PluginLifetimeStatus CheckPluginLifetimeStatus(Exception ex)
        {
            Boolean pluginDisconnected =
                (ex is RemotingException) && (ex.Message.EndsWith(LifetimeExpiredMsgEnd));

            if (!pluginDisconnected)
            {
                return(PluginLifetimeStatus.Active);
            }

            string pluginWrapperFile        = Assembly.GetCallingAssembly().Location;
            TcPluginLoadingInfo loadingInfo = FindPluginLoadingInfoByWrapperFileName(pluginWrapperFile);

            if (loadingInfo == null)
            {
                return(PluginLifetimeStatus.NotLoaded);
            }

            StackTrace stackTrace = new StackTrace(true);

#if TRACE
            string category = loadingInfo.PluginNumber.ToString(CultureInfo.InvariantCulture);
            string text;
#endif
            var stackFrames = stackTrace.GetFrames();
            if (stackFrames != null)
            {
                foreach (StackFrame sf in stackFrames)
                {
                    Type declaringType = sf.GetMethod().DeclaringType;
                    if (declaringType != null &&
                        (declaringType.FullName.StartsWith("OY.TotalCommander.WfxWrapper") &&
                         !sf.GetMethod().Name.Equals("ProcessException")))
                    {
#if TRACE
                        text = String.Format(TraceMsg15, declaringType.FullName.Substring(29), sf.GetMethod().Name);
                        TraceError(text, category);
#endif
                        break;
                    }
                }
            }

            // Plugin remote object has expired, try to unload plugin AppDomain
            loadingInfo.LifetimeStatus = PluginLifetimeStatus.Expired;
            if (loadingInfo.UnloadExpired)
            {
                AppDomain pluginDomain = loadingInfo.Domain;
                try {
                    AppDomain.Unload(pluginDomain);
#if TRACE
                    text = "Plugin Lifetime Expired - Plugin \"" + pluginWrapperFile + "\" was disconnected from TC.";
                    TraceError(text, category);
#endif
                    MessageBox.Show(
                        "Plugin " + Path.GetFileNameWithoutExtension(pluginWrapperFile)
                        + " has expired and was disconnected From TC.",
                        "Plugin disconnected", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    OpenTcPluginHome();
                    loadingInfo.LifetimeStatus = PluginLifetimeStatus.PluginUnloaded;
                } catch (Exception e) {
#if TRACE
                    text = "Unload ERROR: " + e.Message;
                    TraceError(text, category);
#endif
                }
            }
            else
            {
                MessageBox.Show(
                    "Plugin " + Path.GetFileNameWithoutExtension(pluginWrapperFile) + " has expired.",
                    "Plugin expired", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return(loadingInfo.LifetimeStatus);
        }
        public static void HandledAllExceptions()
        {
            AppDomain currentDomain = AppDomain.CurrentDomain;

            currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
        }
        public Step7ProjectV15_1(string projectfile, CultureInfo culture = null, Credentials credentials = null)
        {
            _credentials = credentials;
            if (culture == null)
            {
                Culture = CultureInfo.CurrentCulture;
            }
            else
            {
                Culture = culture;
            }

            AppDomain currentDomain = AppDomain.CurrentDomain;

            currentDomain.AssemblyResolve += currentDomain_AssemblyResolve;

            ProjectFile = projectfile;

            if (ProjectFile.ToLower().EndsWith("zip") || ProjectFile.ToLower().EndsWith("zap15_1"))
            {
                if (string.IsNullOrEmpty(ProjectFile))
                {
                    ProjectFile = ZipHelper.GetFirstZipEntryWithEnding(ProjectFile, ".ap15_1");
                }
                if (string.IsNullOrEmpty(ProjectFile))
                {
                    ProjectFile = ZipHelper.GetFirstZipEntryWithEnding(ProjectFile, ".al15_1");
                }

                if (string.IsNullOrEmpty(projectfile))
                {
                    throw new Exception("Zip-File contains no valid TIA Project !");
                }
                this._ziphelper = new ZipHelper(projectfile);
            }

            try
            {
                using (var stream = _ziphelper.GetReadStream(projectfile))
                {
                    var xmlDoc = new XmlDocument();
                    xmlDoc.Load(stream);

                    XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
                    nsmgr.AddNamespace("x", "http://www.siemens.com/2007/07/Automation/CommonServices/DataInfoValueData");

                    var nd = xmlDoc.SelectSingleNode("x:Data", nsmgr);
                    this.ProjectName = nd.Attributes["Name"].Value;
                }
            }
            catch (Exception)
            { }

            DataFile      = Path.GetDirectoryName(projectfile) + "\\System\\PEData.plf";
            ProjectFolder = projectfile.Substring(0, projectfile.LastIndexOf(Path.DirectorySeparatorChar)) + Path.DirectorySeparatorChar;

            //BinaryParseTIAFile();
            //LoadProject();
            OpenViaOpennessDlls(credentials);

            currentDomain.AssemblyResolve -= currentDomain_AssemblyResolve;
        }
		public void CreateAppDomain(ICorDebugProcess pProcess, ICorDebugAppDomain pAppDomain)
		{
			EnterCallback("CreateAppDomain", pAppDomain);

			pAppDomain.Attach();
			AppDomain appDomain = new AppDomain(process, pAppDomain);
			process.appDomains.Add(appDomain);
			process.OnAppDomainCreated(appDomain);

			ExitCallback();
		}
Example #36
0
        /// <summary>
        /// Start a new silo in the target cluster
        /// </summary>
        /// <param name="host">The target cluster</param>
        /// <param name="type">The type of the silo to deploy</param>
        /// <param name="options">The options to use for the silo</param>
        /// <param name="instanceCount">The instance count of the silo</param>
        /// <param name="shared">The shared AppDomain to use</param>
        /// <returns>A handle to the deployed silo</returns>
        public static SiloHandle StartOrleansSilo(TestingSiloHost host, Silo.SiloType type, TestingSiloOptions options, int instanceCount, AppDomain shared = null)
        {
            if (host == null)
            {
                throw new ArgumentNullException("host");
            }

            // Load initial config settings, then apply some overrides below.
            ClusterConfiguration config = new ClusterConfiguration();

            try
            {
                if (options.SiloConfigFile == null)
                {
                    config.StandardLoad();
                }
                else
                {
                    config.LoadFromFile(options.SiloConfigFile.FullName);
                }
            }
            catch (FileNotFoundException)
            {
                if (options.SiloConfigFile != null &&
                    !string.Equals(options.SiloConfigFile.Name, TestingSiloOptions.DEFAULT_SILO_CONFIG_FILE, StringComparison.InvariantCultureIgnoreCase))
                {
                    // if the user is not using the defaults, then throw because the file was legitimally not found
                    throw;
                }

                config = ClusterConfiguration.LocalhostPrimarySilo();
                config.AddMemoryStorageProvider("Default");
                config.AddMemoryStorageProvider("MemoryStore");
            }

            int basePort = options.BasePort < 0 ? BasePort : options.BasePort;


            if (config.Globals.SeedNodes.Count > 0 && options.BasePort < 0)
            {
                config.PrimaryNode = config.Globals.SeedNodes[0];
            }
            else
            {
                config.PrimaryNode = new IPEndPoint(IPAddress.Loopback, basePort);
            }
            config.Globals.SeedNodes.Clear();
            config.Globals.SeedNodes.Add(config.PrimaryNode);

            if (!String.IsNullOrEmpty(host.DeploymentId))
            {
                config.Globals.DeploymentId = host.DeploymentId;
            }

            config.Defaults.PropagateActivityId = options.PropagateActivityId;
            if (options.LargeMessageWarningThreshold > 0)
            {
                config.Defaults.LargeMessageWarningThreshold = options.LargeMessageWarningThreshold;
            }

            config.Globals.LivenessType        = options.LivenessType;
            config.Globals.ReminderServiceType = options.ReminderServiceType;
            if (!String.IsNullOrEmpty(options.DataConnectionString))
            {
                config.Globals.DataConnectionString = options.DataConnectionString;
            }

            host.Globals = config.Globals;

            string siloName;

            switch (type)
            {
            case Silo.SiloType.Primary:
                siloName = "Primary";
                break;

            default:
                siloName = "Secondary_" + instanceCount.ToString(CultureInfo.InvariantCulture);
                break;
            }

            NodeConfiguration nodeConfig = config.GetOrCreateNodeConfigurationForSilo(siloName);

            nodeConfig.HostNameOrIPAddress = "loopback";
            nodeConfig.Port = basePort + instanceCount;
            nodeConfig.DefaultTraceLevel   = config.Defaults.DefaultTraceLevel;
            nodeConfig.PropagateActivityId = config.Defaults.PropagateActivityId;
            nodeConfig.BulkMessageLimit    = config.Defaults.BulkMessageLimit;

            int?gatewayport = null;

            if (nodeConfig.ProxyGatewayEndpoint != null && nodeConfig.ProxyGatewayEndpoint.Address != null)
            {
                gatewayport = (options.ProxyBasePort < 0 ? ProxyBasePort : options.ProxyBasePort) + instanceCount;
                nodeConfig.ProxyGatewayEndpoint = new IPEndPoint(nodeConfig.ProxyGatewayEndpoint.Address, gatewayport.Value);
            }

            config.Globals.ExpectedClusterSize = 2;

            config.Overrides[siloName] = nodeConfig;

            AdjustForTest(config, options);

            WriteLog("Starting a new silo in app domain {0} with config {1}", siloName, config.ToString(siloName));
            return(AppDomainSiloHandle.Create(siloName, type, config, nodeConfig, host.additionalAssemblies));
        }
Example #37
0
 internal BlogBodyViewModel(Blog blog)
 {
     SettingManager = SettingManager.Current;
     AppDomain = AppDomain.Current;
     Blog = blog;
 }
Example #38
0
        private static ProxyBuilder CreateProxyBuilder(string proxyName, Type interfaceType, Type channelType, Type ctorArgType)
        {
            AppDomain domain = Thread.GetDomain();
            // create a new assembly for the proxy
            AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(PROXY_ASSEMBLY), AssemblyBuilderAccess.Run);

            // create a new module for the proxy
            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(PROXY_MODULE);

            // Set the class to be public and sealed
            TypeAttributes typeAttributes = TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed;

            // Construct the type builder
            TypeBuilder typeBuilder   = moduleBuilder.DefineType(interfaceType.Name + PROXY, typeAttributes, channelType);
            List <Type> allInterfaces = new List <Type>(interfaceType.GetInterfaces());

            allInterfaces.Add(interfaceType);

            //add the interface
            typeBuilder.AddInterfaceImplementation(interfaceType);

            //construct the constructor
            Type[] ctorArgTypes = new Type[] { typeof(Type), ctorArgType };
            CreateConstructor(channelType, typeBuilder, ctorArgTypes);

            //construct the type maps
            Dictionary <Type, OpCode> ldindOpCodeTypeMap = new Dictionary <Type, OpCode>();

            ldindOpCodeTypeMap.Add(typeof(Boolean), OpCodes.Ldind_I1);
            ldindOpCodeTypeMap.Add(typeof(Byte), OpCodes.Ldind_U1);
            ldindOpCodeTypeMap.Add(typeof(SByte), OpCodes.Ldind_I1);
            ldindOpCodeTypeMap.Add(typeof(Int16), OpCodes.Ldind_I2);
            ldindOpCodeTypeMap.Add(typeof(UInt16), OpCodes.Ldind_U2);
            ldindOpCodeTypeMap.Add(typeof(Int32), OpCodes.Ldind_I4);
            ldindOpCodeTypeMap.Add(typeof(UInt32), OpCodes.Ldind_U4);
            ldindOpCodeTypeMap.Add(typeof(Int64), OpCodes.Ldind_I8);
            ldindOpCodeTypeMap.Add(typeof(UInt64), OpCodes.Ldind_I8);
            ldindOpCodeTypeMap.Add(typeof(Char), OpCodes.Ldind_U2);
            ldindOpCodeTypeMap.Add(typeof(Double), OpCodes.Ldind_R8);
            ldindOpCodeTypeMap.Add(typeof(Single), OpCodes.Ldind_R4);
            Dictionary <Type, OpCode> stindOpCodeTypeMap = new Dictionary <Type, OpCode>();

            stindOpCodeTypeMap.Add(typeof(Boolean), OpCodes.Stind_I1);
            stindOpCodeTypeMap.Add(typeof(Byte), OpCodes.Stind_I1);
            stindOpCodeTypeMap.Add(typeof(SByte), OpCodes.Stind_I1);
            stindOpCodeTypeMap.Add(typeof(Int16), OpCodes.Stind_I2);
            stindOpCodeTypeMap.Add(typeof(UInt16), OpCodes.Stind_I2);
            stindOpCodeTypeMap.Add(typeof(Int32), OpCodes.Stind_I4);
            stindOpCodeTypeMap.Add(typeof(UInt32), OpCodes.Stind_I4);
            stindOpCodeTypeMap.Add(typeof(Int64), OpCodes.Stind_I8);
            stindOpCodeTypeMap.Add(typeof(UInt64), OpCodes.Stind_I8);
            stindOpCodeTypeMap.Add(typeof(Char), OpCodes.Stind_I2);
            stindOpCodeTypeMap.Add(typeof(Double), OpCodes.Stind_R8);
            stindOpCodeTypeMap.Add(typeof(Single), OpCodes.Stind_R4);

            //construct the method builders from the method infos defined in the interface
            List <MethodInfo> methods = GetAllMethods(allInterfaces);

            foreach (MethodInfo methodInfo in methods)
            {
                MethodBuilder methodBuilder = ConstructMethod(channelType, methodInfo, typeBuilder, ldindOpCodeTypeMap, stindOpCodeTypeMap);
                typeBuilder.DefineMethodOverride(methodBuilder, methodInfo);
            }

            //create proxy builder
            var result = new ProxyBuilder
            {
                ProxyName       = proxyName,
                InterfaceType   = interfaceType,
                CtorType        = ctorArgType,
                AssemblyBuilder = assemblyBuilder,
                ModuleBuilder   = moduleBuilder,
                TypeBuilder     = typeBuilder
            };

            return(result);
        }
Example #39
0
		// internal - get called by the class loader

		// Called when
		// - class inheritance
		// - method overrides
		private unsafe static bool InheritanceDemand (AppDomain ad, Assembly a, RuntimeDeclSecurityActions *actions)
		{
			try {
				PermissionSet ps = null;
				bool result = true;
				if (actions->cas.size > 0) {
					ps = Decode (actions->cas.blob, actions->cas.size);
					result = (SecurityManager.CheckPermissionSet (a, ps, false) == null);
					if (result) {
						// also check appdomain
						result = (SecurityManager.CheckPermissionSet (ad, ps) == null);
					}
				}
				if (actions->noncas.size > 0) {
					ps = Decode (actions->noncas.blob, actions->noncas.size);
					result = (SecurityManager.CheckPermissionSet (a, ps, true) == null);
					if (result) {
						// also check appdomain
						result = (SecurityManager.CheckPermissionSet (ad, ps) == null);
					}
				}
				return result;
			}
			catch (SecurityException) {
				return false;
			}
		}
Example #40
0
        static void TestCAS(string connectString1, string connectString2)
        {
            // Create permission set for sandbox AppDomain.
            // This example only allows execution.
            PermissionSet permissions = new PermissionSet(PermissionState.None);

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

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

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

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

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

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

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

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

            permissions.AddPermission(sqlPermission);

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

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

            // Try a different connection string. This should fail.
            try {
                secondHelper.TestConnectionOpen(connectString2);
                Console.WriteLine("Connection opened, unexpected.");
            }
            catch (System.Security.SecurityException ex) {
                Console.WriteLine("Failed, as expected: {0}", ex.Message);
            }
        }
Example #41
0
        /// <summary>
        /// Construct an application domain for running a test package
        /// </summary>
        /// <param name="package">The TestPackage to be run</param>
        public AppDomain CreateDomain(TestPackage package)
        {
            AppDomainSetup setup = new AppDomainSetup();

            //For paralell tests, we need to use distinct application name
            setup.ApplicationName = "Tests" + "_" + Environment.TickCount;

            FileInfo testFile = package.FullName != null && package.FullName != string.Empty
                ? new FileInfo(package.FullName)
                : null;

            string appBase    = package.BasePath;
            string configFile = package.ConfigurationFile;
            string binPath    = package.PrivateBinPath;

            if (testFile != null)
            {
                if (appBase == null || appBase == string.Empty)
                {
                    appBase = testFile.DirectoryName;
                }

                if (configFile == null || configFile == string.Empty)
                {
                    configFile = Services.ProjectService.CanLoadProject(testFile.Name)
                        ? Path.GetFileNameWithoutExtension(testFile.Name) + ".config"
                        : testFile.Name + ".config";
                }
            }
            else if (appBase == null || appBase == string.Empty)
            {
                appBase = GetCommonAppBase(package.Assemblies);
            }

            char lastChar = appBase[appBase.Length - 1];

            if (lastChar != Path.DirectorySeparatorChar && lastChar != Path.AltDirectorySeparatorChar)
            {
                appBase += Path.DirectorySeparatorChar;
            }

            setup.ApplicationBase = appBase;
            // TODO: Check whether Mono still needs full path to config file...
            setup.ConfigurationFile = appBase != null && configFile != null
                ? Path.Combine(appBase, configFile)
                : configFile;

            if (package.AutoBinPath)
            {
                binPath = GetPrivateBinPath(appBase, package.Assemblies);
            }

            setup.PrivateBinPath = binPath;

            if (package.GetSetting("ShadowCopyFiles", true))
            {
                setup.ShadowCopyFiles       = "true";
                setup.ShadowCopyDirectories = appBase;
                setup.CachePath             = GetCachePath();
            }
            else
            {
                setup.ShadowCopyFiles = "false";
            }

            string domainName = "test-domain-" + package.Name;
            // Setup the Evidence
            Evidence evidence = new Evidence(AppDomain.CurrentDomain.Evidence);

            if (evidence.Count == 0)
            {
                Zone zone = new Zone(SecurityZone.MyComputer);
                evidence.AddHost(zone);
                Assembly assembly = Assembly.GetExecutingAssembly();
                Url      url      = new Url(assembly.CodeBase);
                evidence.AddHost(url);
                Hash hash = new Hash(assembly);
                evidence.AddHost(hash);
            }

            log.Info("Creating AppDomain " + domainName);

            AppDomain runnerDomain;

            // TODO: Try to eliminate this test. Currently, running on
            // Linux with the permission set specified causes an
            // unexplained crash when unloading the domain.
#if CLR_2_0 || CLR_4_0
            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                PermissionSet permissionSet = new PermissionSet(PermissionState.Unrestricted);
                runnerDomain = AppDomain.CreateDomain(domainName, evidence, setup, permissionSet, null);
            }
            else
#endif
            runnerDomain = AppDomain.CreateDomain(domainName, evidence, setup);

            // Set PrincipalPolicy for the domain if called for in the settings
            if (Services.UserSettings.GetSetting("Options.TestLoader.SetPrincipalPolicy", false))
            {
                runnerDomain.SetPrincipalPolicy((PrincipalPolicy)Services.UserSettings.GetSetting(
                                                    "Options.TestLoader.PrincipalPolicy", PrincipalPolicy.UnauthenticatedPrincipal));
            }

            // HACK: Only pass down our AddinRegistry one level so that tests of NUnit
            // itself start without any addins defined.
            if (!IsTestDomain(AppDomain.CurrentDomain))
            {
                runnerDomain.SetData("AddinRegistry", Services.AddinRegistry);
            }

            // Inject DomainInitializer into the remote domain - there are other
            // approaches, but this works for all CLR versions.
            DomainInitializer initializer = DomainInitializer.CreateInstance(runnerDomain);

            // HACK: Under nunit-console, direct use of the enum fails
            int traceLevel = IsTestDomain(AppDomain.CurrentDomain)
                ? (int)InternalTraceLevel.Off : (int)InternalTrace.Level;

            initializer.InitializeDomain(traceLevel);

            return(runnerDomain);
        }
Example #42
0
 internal RuntimeData(RuntimeAssemblyManager manager, AppDomain appDomain)
 {
     Manager   = manager;
     AppDomain = appDomain;
 }
Example #43
0
 public PluginContainer(AppDomain domain, TPlugin plugin, TModel model)
 {
     Domain = domain;
     Plugin = plugin;
     Model  = model;
 }
Example #44
0
        /// <summary>
        /// Init the repository from a given path
        /// </summary>
        public void Init(string path)
        {
            RepositoryPath = path;
            RepositoryServer.ViewsFolder          = ViewsFolder;
            RepositoryServer.TableTemplatesFolder = TableTemplatesFolder;

            CheckFolders();
            //Data sources
            if (Sources.Count == 0)
            {
                foreach (var file in Directory.GetFiles(SourcesFolder, "*." + SealConfigurationFileExtension))
                {
                    try
                    {
                        var source = MetaSource.LoadFromFile(file, this);
                        Sources.Add(source);
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message);
                    }
                }
            }

            if (Devices.Count == 0)
            {
                //Devices, add a default folder device, then the other devices
                Devices.Add(OutputFolderDevice.Create());
                foreach (var file in Directory.GetFiles(DevicesEmailFolder, "*." + SealConfigurationFileExtension))
                {
                    try
                    {
                        Devices.Add(OutputEmailDevice.LoadFromFile(file, true));
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message);
                    }
                }
                foreach (var file in Directory.GetFiles(DevicesFileServerFolder, "*." + SealConfigurationFileExtension))
                {
                    try
                    {
                        Devices.Add(OutputFileServerDevice.LoadFromFile(file, true));
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message);
                    }
                }
            }

            if (!_assembliesLoaded)
            {
                //Load extra assemblies defined in Repository
                var assemblies = Directory.GetFiles(AssembliesFolder, "*.dll");
                foreach (var assembly in assemblies)
                {
                    try
                    {
                        Assembly.LoadFrom(assembly);
                    }
                    catch (Exception Exception)
                    {
                        Debug.WriteLine(Exception.Message);
                    }
                }

                //Add this assembly resolve necessary when executing Razor scripts
                AppDomain currentDomain = AppDomain.CurrentDomain;
                currentDomain.AssemblyResolve += new ResolveEventHandler(AssemblyResolve);

                _assembliesLoaded = true;
            }
        }
Example #45
0
 /// <summary>
 /// Returns true if this is a clickonce deployed app.
 /// </summary>
 internal static bool IsClickOnceDeployed(AppDomain appDomain)
 {
     // Never ClickOnce app in CoreFX
     return(false);
 }
        /// <summary>
        /// Method initiates the startup of the application.
        /// The MainWindow entity is retrieved from the services provider and rendered to the user
        /// </summary>
        /// <param name="sender">The caller of the method</param>
        /// <param name="e">Any startup arguments provided</param>
        private void OnStartup(object sender, StartupEventArgs e)
        {
            // global exception handler for unhandled exceptions
            AppDomain domain = AppDomain.CurrentDomain;

            domain.UnhandledException += DomainOnUnhandledException;

            string env = null;

            for (int i = 0; i < e.Args.Length; i++)
            {
                if (e.Args[i].Equals("-config"))
                {
                    _enviromentTag = e.Args[i + 1];
                    switch (e.Args[i + 1])
                    {
                    case "Development":
                        env = "appsettings.Development.json";
                        break;

                    case "Live":
                        env = "appsettings.json";
                        break;

                    default:
                        env = null;
                        break;
                    }
                }
                else if (e.Args[i].Equals("-clear"))
                {
                    clearList.Clear      = true;
                    clearList.ClearValue = int.Parse(e.Args[i + 1]);
                }
            }

            // add in the app settings file
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Environment.CurrentDirectory)
                          .AddJsonFile(env, optional: false, reloadOnChange: false);

            _configuration = builder.Build();

            ServiceCollection serviceCollection = new ServiceCollection();

            // Add NLog
            serviceCollection.AddLogging(loggingProvider =>
            {
                // configure Logging with NLog
                loggingProvider.ClearProviders();
                loggingProvider.SetMinimumLevel(LogLevel.Debug);
                loggingProvider.AddConfiguration(_configuration.GetSection("Logging"));
                loggingProvider.AddNLog(_configuration);
            });

            // configure all classes that need to be injected
            ConfigureServices(serviceCollection);
            ConfigureViews(serviceCollection);
            ConfigureViewModels(serviceCollection);


            ConfigDatabase(serviceCollection); // Database

            _serviceProvider = serviceCollection.BuildServiceProvider();

            Services = serviceCollection;

            MigrateDatabase();
            SeedDatabase();

            MainWindow mainWindow = _serviceProvider.GetService <MainWindow>();

            mainWindow.Show();
        }
Example #47
0
 public Event.ExecutionOrigin ExecutionOriginHere()
 {
     return(new Event.ExecutionOrigin(process.MainModule.ModuleName, (uint)process.Id, (uint)AppDomain.GetCurrentThreadId()));
 }
Example #48
0
        private void SetupExceptionHandling()
        {
            AppDomain currentDomain = AppDomain.CurrentDomain;

            currentDomain.UnhandledException += CurrentDomain_UnhandledException;
        }
Example #49
0
        public void LoadAssemblies()
        {
            if (ad != null)
            {
                System.Console.Error.WriteLine("Unloading domain");
                AppDomain.Unload(ad);
            }

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

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

                    System.Console.Error.WriteLine("Loading: " + a);
                    h.Load(a);
                }
                catch (Exception e)
                {
                    reportError(e);
                }
            }
        }
Example #50
0
        void EnableAlternativeAssemblyResolvers()
        {
            AppDomain currentDomain = AppDomain.CurrentDomain;

            currentDomain.AssemblyResolve += CurrentDomainOnAssemblyResolve;
        }
	public UnloadThread (AppDomain domain) {
		this.domain = domain;
	}
Example #52
0
        public void Dispose()
        {
            AppDomain currentDomain = AppDomain.CurrentDomain;

            currentDomain.AssemblyResolve -= CurrentDomainOnAssemblyResolve;
        }
    /// <summary>
    /// Handles unloads for assemblyLoad and domainUnload events
    /// </summary>
    /// <param name="ad">The appdomain to potentially unload</param>
    /// <param name="eReasonForUnload">reason for unload</param>
    public void UnloadOnEvent(AppDomain ad, eReasonForUnload reason)
    {
        int percent = 0;
        switch (reason)
        {
            case eReasonForUnload.AssemblyLoad:
                percent = curTestSet.ULAssemblyLoadPercent;
                break;
            case eReasonForUnload.AppDomainUnload:
                percent = curTestSet.ULAppDomainUnloadPercent;
                break;
            case eReasonForUnload.Replay:
                percent = 100;
                break;
        }
        if (randNum.Next(100) < percent)
        {
            for (int i = 0; i < curTestSet.Tests.Length; i++)
            {
                lock (curTestSet.Tests[i])
                {
                    if ((curTestSet.Tests[i].AppDomain != null) && (curTestSet.Tests[i].AppDomain.FriendlyName == ad.FriendlyName))
                    {
                        //update testsRanCount to reflect missing tests
                        this.testsRanCount += curTestSet.Tests[i].ConcurrentCopies * curTestSet.MaximumLoops - curTestSet.Tests[i].RunCount;

                        //print unload message to log
                        //WriteToLog(String.Format("UNLOAD {0} AppDomain Unloaded: {1}{2}", DateTime.Now, curTestSet.Tests[i].RefOrID, Environment.NewLine));

                        if (reason == eReasonForUnload.AssemblyLoad)
                        {
                            //The test isn't going to load, so don't count it
                            Interlocked.Decrement(ref LoadingCount);
                        }
                        Console.WriteLine("\nReliabilityFramework: Unload on{0}-{1}-{2}", reason.ToString(), curTestSet.Tests[i].RefOrID, System.DateTime.Now);

                        // unload domain
                        AppDomainUnloadDelegate adu = new AppDomainUnloadDelegate(AppDomain.Unload);
                        adu.BeginInvoke(curTestSet.Tests[i].AppDomain, null, null);
                        curTestSet.Tests[i].AppDomain = null;
                        curTestSet.Tests[i].ConcurrentCopies = 0;
                    }
                }
            }
        }
    }
Example #54
0
 public void Unload(AppDomain domain)
 {
     new DomainUnloader(domain).Unload();
 }
Example #55
0
        /// <summary>
        /// Releases all resources used by the facade.
        /// </summary>
        /// <param name="disposing">
        /// <c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.
        /// </param>
        protected virtual void Dispose(bool disposing)
        {
            if (disposing && _appDomain != null)
            {
                AppDomain.Unload(_appDomain);
                _appDomain = null;
            }

            if (_configurationFile != null)
            {
                File.Delete(_configurationFile);
            }
        }
Example #56
0
 public DomainUnloader(AppDomain domain)
 {
     this.domain = domain;
 }
Example #57
0
		internal static IPermission CheckPermissionSet (AppDomain ad, PermissionSet ps)
		{
			if ((ps == null) || ps.IsEmpty ())
				return null;

			PermissionSet granted = ad.GrantedPermissionSet;
			if (granted == null)
				return null;
			if (granted.IsUnrestricted ())
				return null;
			if (ps.IsUnrestricted ())
				return new SecurityPermission (SecurityPermissionFlag.NoFlags);

			foreach (IPermission p in ps) {
				if (p is CodeAccessPermission) {
					CodeAccessPermission grant = (CodeAccessPermission) granted.GetPermission (p.GetType ());
					if (grant == null) {
						if (!granted.IsUnrestricted () || !(p is IUnrestrictedPermission)) {
							if (!p.IsSubsetOf (null))
								return p;
						}
					} else if (!p.IsSubsetOf (grant)) {
						return p;
					}
				} else {
					// but non-CAS will throw on failure...
					try {
						p.Demand ();
					}
					catch (SecurityException) {
						// ... so we catch
						return p;
					}
				}
			}
			return null;
		}
Example #58
0
 private bool IsTestDomain(AppDomain domain)
 {
     return(domain.FriendlyName.StartsWith("test-domain-"));
 }
Example #59
0
        // Arguments: Codebase, flags, zone, srcurl
        // If the flags indicate zone then a zone must be provided.
        // If the flags indicate a site then a srcurl must be provided, codebase must be a filepath
        public int Execute(string codebase, Int32 flags, Int32 evidenceZone, string evidenceSrcUrl, string stringArg)
        {
            string file = codebase;

            if ((file.Length == 0) || (file[0] == '\0'))
            {
                throw new ArgumentException("Invalid codebase");
            }

            Console.WriteLine("Codebase- {0}", file);

            // Find the appbase of the executable. For now we assume the
            // form to be http://blah/... with forward slashes. This
            // need to be update.
            // Note: aso works with '\' as in file paths
            string appbase           = null;
            string ConfigurationFile = null;
            int    k = file.LastIndexOf('/');

            if (k <= 0)
            {
                k = file.LastIndexOf('\\');
                if (k == 0)
                {
                    appbase           = file;
                    ConfigurationFile = file;
                }
            }

            if (k != 0)
            {
                // if k is still < 0 at this point, appbase should be an empty string
                appbase = file.Substring(0, k + 1);
                if (k + 1 < file.Length)
                {
                    ConfigurationFile = file.Substring(k + 1);
                }
            }

            // Check 1: disallow non-fully qualified path/codebase
            if ((appbase.Length == 0) || (appbase[0] == '.'))
            {
                throw new ArgumentException("Codebase must be fully qualified");
            }

            // BUGBUG: should appbase be the source of the code, not local?
            Console.WriteLine("AppBase- {0}", appbase);

            // Build up the configuration File name
            if (ConfigurationFile != null)
            {
                StringBuilder bld = new StringBuilder();
                bld.Append(ConfigurationFile);
                bld.Append(".config");
                ConfigurationFile = bld.ToString();
            }

            Console.WriteLine("Config- {0}", ConfigurationFile);

            // Get the flags
            // 0x1 we have Zone
            // 0x2 we have a unique id.
            int dwFlag = flags;

            Evidence documentSecurity = null;

            // Check 2: disallow called with no evidence
            if (dwFlag == SECURITY_NONE)
            {
                // BUGBUG?: disallow executing with no evidence
                throw new ArgumentException("Flag set at no evidence");
            }

            if ((dwFlag & SECURITY_SITE) != 0 ||
                (dwFlag & SECURITY_ZONE) != 0)
            {
                documentSecurity = new Evidence();
            }

            // BUGBUG: check other invalid cases for dwFlag

            if ((dwFlag & SECURITY_ZONE) != 0)
            {
                int zone = evidenceZone;
                documentSecurity.AddHost(new Zone((System.Security.SecurityZone)zone));

                Console.WriteLine("Evidence Zone- {0}", zone);
            }
            if ((dwFlag & SECURITY_SITE) != 0)
            {
                if (file.Length < 7 || String.Compare(file.Substring(0, 7), "file://", true) != 0)
                {
                    documentSecurity.AddHost(System.Security.Policy.Site.CreateFromUrl(evidenceSrcUrl));

                    Console.WriteLine("Evidence SiteFromUrl- {0}", evidenceSrcUrl);

                    // if srcUrl is given, assume file/appbase is a local file path
                    StringBuilder bld = new StringBuilder();
                    bld.Append("file://");
                    bld.Append(appbase);
                    documentSecurity.AddHost(new ApplicationDirectory(bld.ToString()));

                    Console.WriteLine("Evidence AppDir- {0}", bld);
                }

                // URLs may be matched exactly or by a wildcard in the final position,
                // for example: http://www.fourthcoffee.com/process/*
                StringBuilder bld2 = new StringBuilder();
                if (evidenceSrcUrl[evidenceSrcUrl.Length - 1] == '/')
                {
                    bld2.Append(evidenceSrcUrl);
                }
                else
                {
                    int j = evidenceSrcUrl.LastIndexOf('/');
                    if (j > 0)
                    {
                        if (j > 7)  // evidenceSrcUrl == "http://a/file.exe"
                        {
                            bld2.Append(evidenceSrcUrl.Substring(0, j + 1));
                        }
                        else
                        {
                            // evidenceSrcUrl == "http://foo.com" -> but why?
                            bld2.Append(evidenceSrcUrl);
                            bld2.Append('/');
                        }
                    }
                    else
                    {
                        throw new ArgumentException("Invalid Url format");
                    }
                }
                bld2.Append('*');

                documentSecurity.AddHost(new Url(bld2.ToString()));

                Console.WriteLine("Evidence Url- {0}", bld2);
            }

            // other evidence: Hash, Publisher, StrongName

            // Set domain name to site name if possible
            string friendlyName = null;

            if ((dwFlag & SECURITY_SITE) != 0)
            {
                friendlyName = GetSiteName(evidenceSrcUrl);
            }
            else
            {
                friendlyName = GetSiteName(file);
            }
            Console.WriteLine("AppDomain friendlyName- {0}", friendlyName);

            // set up arguments
            // only allow 1 for now
            string[] args;
            if (stringArg != null)
            {
                args    = new string[1];
                args[0] = stringArg;
            }
            else
            {
                args = new string[0];
            }

            AppDomainSetup properties = new AppDomainSetup();

            properties.ApplicationBase = appbase;
            properties.PrivateBinPath  = "bin";
            if (ConfigurationFile != null)
            {
                properties.ConfigurationFile = ConfigurationFile;
            }

            AppDomain proxy = AppDomain.CreateDomain(friendlyName, documentSecurity, properties);

            if (proxy != null)
            {
                AssemblyName asmname = Assembly.GetExecutingAssembly().GetName();
                Console.WriteLine("AsmExecute name- {0}", asmname);

                try
                {
                    // Use remoting. Otherwise asm will be loaded both in current and the new AppDomain
                    // ... as explained by URT dev
                    // asmexec.dll must be found on path (CorPath?) or in the GAC for this to work.
                    ObjectHandle handle = proxy.CreateInstance(asmname.FullName, "FusionCLRHost.AsmExecute");
                    if (handle != null)
                    {
                        AsmExecute execproxy = (AsmExecute)handle.Unwrap();
                        int        retVal    = -1;

                        Console.WriteLine("\n========");

                        if (execproxy != null)
                        {
                            retVal = execproxy.ExecuteAsAssembly(file, documentSecurity, args);
                        }

                        Console.WriteLine("\n========");

                        return(retVal);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("AsmExecute CreateInstance(AsmExecute) failed: {0}", e.Message);
                    throw e;
                }
            }
            else
            {
                Console.WriteLine("AsmExecute CreateDomain failed");
            }

            // BUGBUG: throw Exception?
            return(-1);
        }
Example #60
0
 public void CreateDomainNonNetfx()
 {
     AssertExtensions.Throws <ArgumentNullException>("friendlyName", () => { AppDomain.CreateDomain(null); });
     Assert.Throws <PlatformNotSupportedException>(() => { AppDomain.CreateDomain("test"); });
 }