//Create a SandBox to load Assemblies with "Full Trust"
        public static ServiceBridge Sandbox(string assemblyFilename, string configPath, ResolveEventHandler handler)
        {
            var trustedLoadGrantSet = new PermissionSet(PermissionState.Unrestricted);
            var trustedLoadSetup = new AppDomainSetup();
            trustedLoadSetup.ApplicationBase = Path.GetDirectoryName(assemblyFilename);
            trustedLoadSetup.PrivateBinPath = Path.GetDirectoryName(assemblyFilename);
            //trustedLoadSetup.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
            trustedLoadSetup.ConfigurationFile = configPath;

            AppDomain.CurrentDomain.AssemblyResolve += handler;
            AppDomain appDomain = AppDomain.CreateDomain("ServiceBridge SandBox", null, trustedLoadSetup, trustedLoadGrantSet);
            appDomain.SetData("DataDirectory", configPath.Replace("Web.config", "App_Data"));

            ServiceBridge loader = appDomain.CreateInstanceAndUnwrap(
                typeof(ServiceBridge).Assembly.GetName().FullName,
                typeof(ServiceBridge).FullName,
                false,
                BindingFlags.Default,
                null,
                new object[] { assemblyFilename },
                CultureInfo.InvariantCulture,
                null) as ServiceBridge;

            return loader;
        }
 public void Dispose()
 {
     if (_assemblyResolver != null) {
         AppDomain.CurrentDomain.AssemblyResolve -= _assemblyResolver;
         _assemblyResolver = null;
     }
 }
Exemple #3
0
        private static void add_assembly_resolver()
        {
            _handler = (sender, args) =>
            {
                var requestedAssembly = new AssemblyName(args.Name);
                if (requestedAssembly.get_public_key_token().is_equal_to(ApplicationParameters.OfficialChocolateyPublicKey)
                    && !requestedAssembly.Name.is_equal_to("chocolatey.licensed")
                    && !requestedAssembly.Name.EndsWith(".resources", StringComparison.OrdinalIgnoreCase))
                {
                    return typeof(ConsoleApplication).Assembly;
                }

                try
                {
                    if (requestedAssembly.get_public_key_token().is_equal_to(ApplicationParameters.OfficialChocolateyPublicKey)
                        && requestedAssembly.Name.is_equal_to("chocolatey.licensed"))
                    {
                        return Assembly.LoadFile(ApplicationParameters.LicensedAssemblyLocation).UnderlyingType;
                    }
                }
                catch (Exception ex)
                {
                    "chocolatey".Log().Warn("Unable to load chocolatey.licensed assembly. {0}".format_with(ex.Message));
                }

                return null;
            };

            AppDomain.CurrentDomain.AssemblyResolve += _handler;
        }
        /// <summary>
        /// Installs an AssemblyResolve handler in the current AppDomain. This class can be created in any AppDomain, 
        /// so it's possible to create an AppDomain, create an instance of this class in it and use this method to install
        /// an event handler in that AppDomain. Since the event handler instance is stored internally, this method
        /// should only be called once before a corresponding call to RemoveHandler (not that it would make sense to do 
        /// anything else).
        /// </summary>
        /// <owner>lukaszg</owner>
        internal void InstallHandler()
        {
            Debug.Assert(eventHandler == null, "The TaskEngineAssemblyResolver.InstallHandler method should only be called once!");

            eventHandler = new ResolveEventHandler(ResolveAssembly);
            AppDomain.CurrentDomain.AssemblyResolve += eventHandler;
        }
        //===================================================================
        // Initialization performed on startup of the Python runtime. Here we
        // scan all of the currently loaded assemblies to determine exported
        // names, and register to be notified of new assembly loads.
        //===================================================================

        internal static void Initialize()
        {
            namespaces = new
                Dictionary<string, Dictionary<Assembly, string>>(32);
            probed = new Dictionary<string, int>(32);
            //generics = new Dictionary<string, Dictionary<string, string>>();
            assemblies = new List<Assembly>(16);
            pypath = new List<string>(16);

            AppDomain domain = AppDomain.CurrentDomain;

            lhandler = new AssemblyLoadEventHandler(AssemblyLoadHandler);
            domain.AssemblyLoad += lhandler;

            rhandler = new ResolveEventHandler(ResolveHandler);
            domain.AssemblyResolve += rhandler;

            Assembly[] items = domain.GetAssemblies();
            foreach (var a in items)
            {
                try
                {
                    ScanAssembly(a);
                    assemblies.Add(a);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(string.Format("Error scanning assembly {0}. {1}", a, ex));
                }
            }
        }
 internal void Dispose()
 {
     if (this.assemblyResolver != null)
     {
         AppDomain.CurrentDomain.AssemblyResolve -= this.assemblyResolver;
     }
     this.assemblyResolver = null;
 }
        public static Assembly BuildAndLoad(string[] sourcePaths, string[] referencePaths, string[] defines)
        {
            var assemblyName = Path.GetRandomFileName();
            var parseOption = new CSharpParseOptions(LanguageVersion.CSharp6, DocumentationMode.Parse, SourceCodeKind.Regular, defines);
            var syntaxTrees = sourcePaths.Select(file => CSharpSyntaxTree.ParseText(File.ReadAllText(file), parseOption, file)).ToArray();
            var references = referencePaths.Select(file => MetadataReference.CreateFromFile(file)).ToArray();
            var referenceMaps = referencePaths.Select(file => Assembly.LoadFile(file))
                                              .ToDictionary(a => a.FullName, a => a);

            var compilation = CSharpCompilation.Create(
                assemblyName,
                syntaxTrees: syntaxTrees,
                references: references,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (var ms = new MemoryStream())
            {
                var result = compilation.Emit(ms);

                if (!result.Success)
                {
                    var failures = result.Diagnostics.Where(diagnostic =>
                        diagnostic.IsWarningAsError ||
                        diagnostic.Severity == DiagnosticSeverity.Error);

                    foreach (var diagnostic in failures)
                    {
                        var line = diagnostic.Location.GetLineSpan();
                        Console.Error.WriteLine("{0}({1}): {2} {3}",
                            line.Path,
                            line.StartLinePosition.Line + 1,
                            diagnostic.Id,
                            diagnostic.GetMessage());
                    }
                    return null;
                }
                else
                {
                    ms.Seek(0, SeekOrigin.Begin);

                    // To load referenced assemblies, set customized resolved during using this assembly.

                    var currentDomain = AppDomain.CurrentDomain;
                    var resolveHandler = new ResolveEventHandler((sender, args) =>
                    {
                        Assembly assembly;
                        return referenceMaps.TryGetValue(args.Name, out assembly) ? assembly : null;
                    });

                    if (_lastResolveHandler != null)
                        currentDomain.AssemblyResolve -= _lastResolveHandler;
                    currentDomain.AssemblyResolve += resolveHandler;
                    _lastResolveHandler = resolveHandler;

                    return Assembly.Load(ms.ToArray());
                }
            }
        }
 internal void Init(TempAssembly tempAssembly)
 {
     this.tempAssembly = tempAssembly;
     if ((tempAssembly != null) && tempAssembly.NeedAssembyResolve)
     {
         this.threadCode = Thread.CurrentThread.GetHashCode();
         this.assemblyResolver = new ResolveEventHandler(this.OnAssemblyResolve);
         AppDomain.CurrentDomain.AssemblyResolve += this.assemblyResolver;
     }
 }
 internal void Init(TempAssembly tempAssembly) {
     this.tempAssembly = tempAssembly;
     // only hook the assembly resolver if we have something to help us do the resolution
     if (tempAssembly != null && tempAssembly.NeedAssembyResolve) {
         // we save the threadcode to make sure we don't handle any resolve events for any other threads
         threadCode = Thread.CurrentThread.GetHashCode();
         assemblyResolver = new ResolveEventHandler(OnAssemblyResolve);
         AppDomain.CurrentDomain.AssemblyResolve += assemblyResolver;
     }
 }
Exemple #10
0
 public static void Test_SetAssemblyEvent_01()
 {
     Test_UnsetAssemblyEvent_01();
     _tr.WriteLine("Test_SetAssemblyEvent_01");
     ResolveEventHandler resolveEventHandler = new ResolveEventHandler(CurrentDomain_AssemblyResolve);
     AssemblyLoadEventHandler assemblyLoadEventHandler = new AssemblyLoadEventHandler(CurrentDomain_AssemblyLoad);
     _rs.Data.Add("ResolveEventHandler", resolveEventHandler);
     _rs.Data.Add("AssemblyLoadEventHandler", assemblyLoadEventHandler);
     AppDomain.CurrentDomain.AssemblyResolve += resolveEventHandler;
     AppDomain.CurrentDomain.AssemblyLoad += assemblyLoadEventHandler;
 }
Exemple #11
0
        internal PackedHelper(string appId, string referencesId, bool logging) {
            _appId = appId;
            _referencesId = referencesId;
            _logging = logging;
            _temporaryDirectory = Path.Combine(Path.GetTempPath(), appId + "_libs");
            Directory.CreateDirectory(_temporaryDirectory);

            Log(null);
            Handler = HandlerImpl;

            _references = new ResourceManager(referencesId, Assembly.GetExecutingAssembly());
        }
        public TypeLoader(AppDomain appDomain, IEnumerable<Assembly> assemblies)
        {
            Contract.Requires(appDomain != null);
            Contract.Requires(assemblies != null);

            _appDomain = appDomain;
            _assemblies = assemblies;
            _constructors = new ConcurrentDictionary<Type, Func<ITemplate>>();
            _resolveEventHandler = (s, e) => ResolveAssembly(e.Name);

            _appDomain.AssemblyResolve += _resolveEventHandler;
        }
 void RemoveAssemblyResolve()
 {
     if (_resolveEventHandler != null)
     {
         AppDomain.CurrentDomain.AssemblyResolve -= _resolveEventHandler;
         _resolveEventHandler = null;
     }
     if (_resolveDirs != null)
     {
         _resolveDirs.Clear();
         _resolveDirs = null;
     }
 }
Exemple #14
0
        private static void add_assembly_resolver()
        {
            _handler = (sender, args) =>
            {
                var requestedAssembly = new AssemblyName(args.Name);
                if (requestedAssembly.get_public_key_token().is_equal_to(ApplicationParameters.OfficialChocolateyPublicKey)
                    && !requestedAssembly.Name.is_equal_to("chocolatey.licensed")
                    && !requestedAssembly.Name.EndsWith(".resources", StringComparison.OrdinalIgnoreCase))
                {
                    return typeof(ConsoleApplication).Assembly;
                }

                return null;
            };

            AppDomain.CurrentDomain.AssemblyResolve += _handler;
        }
Exemple #15
0
        internal PackedHelper(string appId, string referencesId, string logFilename) {
            _logFilename = logFilename;
            _temporaryDirectory = Path.Combine(Path.GetTempPath(), appId + "_libs");
            Directory.CreateDirectory(_temporaryDirectory);
            SetDllDirectory(_temporaryDirectory);

            Log(null);
            Handler = HandlerImpl;
            
#if DEBUG
            _references = null;
#else
            _references = new ResourceManager(referencesId, Assembly.GetExecutingAssembly());
#endif

            if (logFilename != null) {
                SetUnhandledExceptionHandler();
            }
        }
Exemple #16
0
		public void Add(ProjectItem item, EventModel model, IEnumerable<IEventScript> scripts, ResolveEventHandler resolver)
		{
			if (item == null)
				throw new ArgumentNullException("item");

			var entry = new Entry(item, model, scripts, resolver);

			var project = item.ContainingProject;
	
			Dictionary<ProjectItem, Entry> items;
			if (!_entries.TryGetValue(project, out items))
			{
				// Add project entry
				items = new Dictionary<ProjectItem, Entry>();
				_entries.Add(project, items);
			}

			items.Add(item, entry);
		}
        static Plugin()
        {
            ResolveEventHandler OnRhinoCommonResolve = null;

            AppDomain.CurrentDomain.AssemblyResolve += OnRhinoCommonResolve = (sender, args) =>
            {
                const string rhino_common_assembly_name = "RhinoCommon";
                var          assembly_name = new AssemblyName(args.Name).Name;

                if (assembly_name != rhino_common_assembly_name)
                {
                    return(null);
                }

                AppDomain.CurrentDomain.AssemblyResolve -= OnRhinoCommonResolve;

                var rhino_system_dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Rhino WIP", "System");
                return(Assembly.LoadFrom(Path.Combine(rhino_system_dir, rhino_common_assembly_name + ".dll")));
            };
        }
Exemple #18
0
        public static void InstallHarmonyResolver()
        {
            UnityEngine.Debug.Log($"[CitiesHarmony] InstallHarmonyResolver() called ...");
            var mCSResolver =
                typeof(BuildConfig)
                .GetMethod("CurrentDomain_AssemblyResolve", BindingFlags.NonPublic | BindingFlags.Static);
            ResolveEventHandler dCSResolver =
                (ResolveEventHandler)Delegate.CreateDelegate(typeof(ResolveEventHandler), mCSResolver);

            AppDomain.CurrentDomain.AssemblyResolve -= dCSResolver;
            AppDomain.CurrentDomain.TypeResolve     -= dCSResolver;
            AppDomain.CurrentDomain.AssemblyResolve -= ResolveHarmony;
            AppDomain.CurrentDomain.TypeResolve     -= ResolveHarmony;
            AppDomain.CurrentDomain.AssemblyResolve += ResolveHarmony;
            AppDomain.CurrentDomain.TypeResolve     += ResolveHarmony;
            AppDomain.CurrentDomain.AssemblyResolve += dCSResolver;
            AppDomain.CurrentDomain.TypeResolve     += dCSResolver;

            UnityEngine.Debug.Log($"[CitiesHarmony] InstallHarmonyResolver() successfull!");
        }
Exemple #19
0
        public ToolingConnectorForm(string id, string label)
        {
            var currentDomain          = AppDomain.CurrentDomain;
            var assemblyresolveHandler = new ResolveEventHandler(ResolveToolingUiStylesHandler);

            currentDomain.AssemblyResolve += assemblyresolveHandler;

            InitializeComponent();

            currentDomain.AssemblyResolve -= assemblyresolveHandler;

            ConnectionLabel = label ?? "Unnamed Connection";
            ConnectionId    = id;
            //// Should be used for testing only.
            //ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) =>
            //{
            //    MessageBox.Show("CertError");
            //    return true;
            //};
        }
Exemple #20
0
        public static void Init(string path, ResolveEventHandler handler)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            var files = Directory.GetFiles(path, "*.dll", SearchOption.AllDirectories);

            foreach (var file in files)
            {
                var addin = AddinLoader.Load(file);
                if (addin != null && !_map.ContainsKey(addin.Name))
                {
                    _map.Add(addin.Name, addin);
                }
            }

            AppDomain.CurrentDomain.AssemblyResolve += handler;
        }
        /// <summary>
        /// The sandbox.
        /// </summary>
        /// <param name="domain">
        /// The domain.
        /// </param>
        /// <param name="assemblyFilenames">
        /// The assembly filenames.
        /// </param>
        /// <param name="handler">
        /// The handler.
        /// </param>
        /// <returns>
        /// The <see cref="PluginSandBoxLoader"/>.
        /// </returns>
        public static PluginSandBoxLoader Sandbox(
            AppDomain domain,
            string[] assemblyFilenames,
            ResolveEventHandler handler)
        {
            //AppDomain.CurrentDomain.AssemblyResolve += handler;

            var loader =
                domain.CreateInstanceAndUnwrap(
                    typeof(PluginSandBoxLoader).Assembly.GetName().FullName,
                    typeof(PluginSandBoxLoader).FullName,
                    false,
                    BindingFlags.Default,
                    null,
                    new object[] { assemblyFilenames },
                    CultureInfo.InvariantCulture,
                    null) as PluginSandBoxLoader;

            return loader;
        }
            internal AssemblyName[] GetReferencedAssemblyNames(string path, string dll)
            {
                AssemblyName[] assemblyNames = new AssemblyName[] { };

                DirectoryInfo       directory           = new DirectoryInfo(path);
                ResolveEventHandler resolveEventHandler =
                    (s, e) =>
                {
                    return(OnReflectionOnlyResolve(
                               e, directory));
                };

                AppDomain.CurrentDomain.AssemblyResolve += resolveEventHandler;

                assemblyNames = Assembly.LoadFrom(dll).GetReferencedAssemblies();

                AppDomain.CurrentDomain.AssemblyResolve -= resolveEventHandler;

                return(assemblyNames);
            }
            internal PluginTypeInfo[] GetTypes(string path, string dll)
            {
                PluginTypeInfo[] types = new PluginTypeInfo[] { };

                DirectoryInfo       directory           = new DirectoryInfo(path);
                ResolveEventHandler resolveEventHandler =
                    (s, e) =>
                {
                    return(OnReflectionOnlyResolve(
                               e, directory));
                };

                AppDomain.CurrentDomain.AssemblyResolve += resolveEventHandler;

                types = Assembly.LoadFrom(dll).GetTypes().Where(t => IsDefinedAttributeData <ReflectorTypeAttribute>(t)).Select(t => new PluginTypeInfo(t)).ToArray();

                AppDomain.CurrentDomain.AssemblyResolve -= resolveEventHandler;

                return(types);
            }
Exemple #24
0
        public void AssemblyResolve_RequestingAssembly()
        {
            RemoteInvoke(() =>
            {
                Assembly a = Assembly.LoadFile(Path.Combine(Environment.CurrentDirectory, "TestAppOutsideOfTPA", "TestAppOutsideOfTPA.exe"));

                ResolveEventHandler handler = (sender, e) =>
                {
                    Assert.Equal(e.RequestingAssembly, a);
                    return(Assembly.LoadFile(Path.Combine(Environment.CurrentDirectory, "AssemblyResolveTests", "AssemblyResolveTests.dll")));
                };

                AppDomain.CurrentDomain.AssemblyResolve += handler;
                Type ptype = a.GetType("Program");
                MethodInfo myMethodInfo = ptype.GetMethod("foo");
                object ret = myMethodInfo.Invoke(null, null);
                Assert.NotNull(ret);
                return(SuccessExitCode);
            }).Dispose();
        }
Exemple #25
0
        private static void RedirectAssembly(string shortName, Version targetVersion, string publicKeyToken)
        {
            ResolveEventHandler handler = null;

            handler = (sender, args) =>
            {
                var requestedAssembly = new AssemblyName(args.Name);
                if (requestedAssembly.Name != shortName)
                {
                    return(null);
                }
                var targetPublicKeyToken = new AssemblyName("x, PublicKeyToken=" + publicKeyToken).GetPublicKeyToken();
                requestedAssembly.SetPublicKeyToken(targetPublicKeyToken);
                requestedAssembly.Version                = targetVersion;
                requestedAssembly.CultureInfo            = CultureInfo.InvariantCulture;
                AppDomain.CurrentDomain.AssemblyResolve -= handler;
                return(Assembly.Load(requestedAssembly));
            };
            AppDomain.CurrentDomain.AssemblyResolve += handler;
        }
        public TResult Reflect <TResult>(Func <Assembly, TResult> func)
        {
            DirectoryInfo       directory           = new FileInfo(_assemblyPath).Directory;
            ResolveEventHandler resolveEventHandler =
                (s, e) =>
            {
                return(OnReflectionOnlyResolve(
                           e, directory));
            };

            AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += resolveEventHandler;

            var assembly = AppDomain.CurrentDomain.ReflectionOnlyGetAssemblies().FirstOrDefault(a => string.Compare(a.Location, _assemblyPath, StringComparison.Ordinal) == 0);

            var result = func(assembly);

            AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= resolveEventHandler;

            return(result);
        }
        private static void RedirectAssembly(BindingRedirect bindingRedirect)
        {
            ResolveEventHandler handler = null;

            handler = (sender, args) =>
            {
                var requestedAssembly = new AssemblyName(args.Name);
                if (requestedAssembly.Name != bindingRedirect.ShortName)
                {
                    return(null);
                }
                var targetPublicKeyToken = new AssemblyName("x, PublicKeyToken=" + bindingRedirect.PublicKeyToken).GetPublicKeyToken();
                requestedAssembly.SetPublicKeyToken(targetPublicKeyToken);
                requestedAssembly.Version                = new Version(bindingRedirect.RedirectToVersion);
                requestedAssembly.CultureInfo            = CultureInfo.InvariantCulture;
                AppDomain.CurrentDomain.AssemblyResolve -= handler;
                return(Assembly.Load(requestedAssembly));
            };
            AppDomain.CurrentDomain.AssemblyResolve += handler;
        }
Exemple #28
0
    unsafe static int Main(char *appBase, int argc, char **argv)
    {
        var applicationBase = new string(appBase);

        ResolveEventHandler handler = (sender, args) =>
        {
            var name = new AssemblyName(args.Name).Name;
            return(ResolveAssembly(applicationBase, name));
        };

        try
        {
            AppDomain.CurrentDomain.AssemblyResolve += handler;

            Assembly.Load(new AssemblyName("Stubs, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"));

            Assembly.Load(new AssemblyName("Microsoft.Net.Runtime.Interfaces, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"));

            var assembly = Assembly.Load(new AssemblyName("klr.host"));

            AppDomain.CurrentDomain.AssemblyResolve -= handler;

            //Pack arguments
            var arguments = new string[argc];
            for (var i = 0; i < arguments.Length; i++)
            {
                arguments[i] = new string(argv[i]);
            }

            var bootstrapperType = assembly.GetType("Bootstrapper");
            var mainMethod       = bootstrapperType.GetTypeInfo().GetDeclaredMethod("Main");
            var bootstrapper     = Activator.CreateInstance(bootstrapperType);
            var result           = mainMethod.Invoke(bootstrapper, new object[] { argc, arguments });
            return((int)result);
        }
        catch (Exception ex)
        {
            Console.Error.WriteLine(String.Join(Environment.NewLine, GetExceptions(ex)));
            return(1);
        }
    }
Exemple #29
0
        public void LoadAssembly(string assemblyPath)
        {
            try
            {
                _assemblyPath = assemblyPath;

                if (Uri.TryCreate(assemblyPath, UriKind.RelativeOrAbsolute, out var uri))
                {
                    if (uri.Scheme != Uri.UriSchemeFile)
                    {
                        throw new Exception(string.Format("Unsupported protocol in URI {0}", assemblyPath));
                    }
                    assemblyPath = uri.LocalPath;
                }

                ResolveEventHandler x = (s, args) =>
                {
                    // Console.WriteLine("X1 {1} {0}", args.RequestingAssembly, args.Name);
                    Assembly assembly = Assembly.LoadFrom(args.Name);
                    // if (assembly != null)
                    return(assembly);
                };
                //                AssemblyLoadEventHandler y = (sender, args) =>
                //                {
                //                    Console.WriteLine("X2 {0}", args.LoadedAssembly);
                //                };
                AppDomain.CurrentDomain.AssemblyResolve += x;
                //AppDomain.CurrentDomain.AssemblyLoad += y;

                // Console.WriteLine("Loading {0} B" , assemblyPath);
                _wrappedAssembly = Assembly.LoadFile(assemblyPath);
                //Console.WriteLine("Loading {0} E", assemblyPath);
                var ass = AppDomain.CurrentDomain.GetAssemblies();
                //Console.WriteLine("Current domain contains {0} assemblies", ass.Length);
                AppDomain.CurrentDomain.AssemblyResolve -= x;
            }
            catch (FileNotFoundException)
            {
                // Continue loading assemblies even if an assembly can not be loaded in the new AppDomain.
            }
        }
Exemple #30
0
            internal List <ModelTypeInfo> GetModelTypeInfo(string path)
            {
                var types = new List <ModelTypeInfo>();

                var directory = new DirectoryInfo(path);
                ResolveEventHandler resolveEventHandler =
                    (s, e) => OnReflectionOnlyResolve(
                        e, directory);

                AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve
                    += resolveEventHandler;

                Assembly reflectionOnlyAssembly =
                    AppDomain.CurrentDomain.
                    ReflectionOnlyGetAssemblies().First();

                foreach (Type type in reflectionOnlyAssembly.GetTypes())
                {
                    var modelType = ModelType.Other;
                    if (type.InheritsFrom(typeof(ITrackable)))
                    {
                        modelType = ModelType.Trackable;
                    }
                    else if (type.InheritsFrom(typeof(DbContext)))
                    {
                        modelType = ModelType.DbContext;
                    }
                    types.Add(new ModelTypeInfo
                    {
                        Namespace   = type.Namespace,
                        Name        = type.Name,
                        ModelType   = modelType,
                        DisplayName = string.Format("{0} ({1})",
                                                    type.Name, type.Namespace)
                    });
                }

                AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve
                    -= resolveEventHandler;
                return(types);
            }
Exemple #31
0
        /// <summary>
        /// Deallocates the specified application domain.
        /// </summary>
        /// <param name="appDomainId">The ID of the application domain to consider.</param>
        /// <param name="ownerId">The ID of the owner.</param>
        public bool Deallocate(string appDomainId, string ownerId = null)
        {
            if (appDomainId == null)
            {
                return(false);
            }

            _resourceAllocations.RemoveAll(p =>
                                           ((p.AllocatedResourceId != null) && (string.Equals(p.AllocatedResourceId, appDomainId, StringComparison.OrdinalIgnoreCase))) &
                                           (((p.OwnerId == ownerId) & (ownerId == null)) || ((p.OwnerId != null) && (string.Equals(p.OwnerId, ownerId, StringComparison.OrdinalIgnoreCase)))));

            if (!_resourceAllocations.Any(p => (p.AllocatedResourceId != null) && (string.Equals(p.AllocatedResourceId, appDomainId, StringComparison.OrdinalIgnoreCase))))
            {
                // we retrieve the application domain
                AppDomain appDomain = _appDomains.FirstOrDefault(p => p.FriendlyName.KeyEquals(appDomainId));
                if ((appDomain != null) && (appDomain != AppDomain.CurrentDomain))
                {
                    // we remove the resolve event handler from the main domain
                    ResolveEventHandler aResolveEventHandler = (ResolveEventHandler)_resolveEventHandlerHashTable[appDomainId];
                    if (aResolveEventHandler != null)
                    {
                        AppDomain.CurrentDomain.AssemblyResolve -= aResolveEventHandler;
                        _resolveEventHandlerHashTable.Remove(appDomainId);
                    }

                    // we remove the application domain from list
                    _appDomains.Remove(appDomain);
                    AppDomain.Unload(appDomain);

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

                    //appDomain = null;
                }

                return(true);
            }

            return(false);
        }
Exemple #32
0
        public void AssemblyResolveInvalidAssemblyName()
        {
            RemoteExecutor.Invoke(() => {
                bool AssemblyResolveFlag    = false;
                ResolveEventHandler handler = (sender, args) =>
                {
                    Assert.Same(AppDomain.CurrentDomain, sender);
                    Assert.NotNull(args);
                    Assert.NotNull(args.Name);
                    Assert.NotNull(args.RequestingAssembly);
                    AssemblyResolveFlag = true;
                    return(null);
                };

                AppDomain.CurrentDomain.AssemblyResolve += handler;

                Type t = Type.GetType("AssemblyResolveTestApp.Class1, InvalidAssemblyName", throwOnError: false);
                Assert.Null(t);
                Assert.True(AssemblyResolveFlag);
            }).Dispose();
        }
            internal ModuleInfo[] GetModuleInfos(string path)
            {
                DirectoryInfo directory = new DirectoryInfo(path);

                ResolveEventHandler resolveEventHandler =
                    delegate(object sender, ResolveEventArgs args) { return(OnReflectionOnlyResolve(args, directory)); };

                AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += resolveEventHandler;

                Assembly moduleReflectionOnlyAssembly =
                    AppDomain.CurrentDomain.ReflectionOnlyGetAssemblies().First(
                        asm => asm.FullName == typeof(IModule).Assembly.FullName);
                Type IModuleType = moduleReflectionOnlyAssembly.GetType(typeof(IModule).FullName);

                IEnumerable <ModuleInfo> modules = GetNotAllreadyLoadedModuleInfos(directory, IModuleType);

                var array = modules.ToArray();

                AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= resolveEventHandler;
                return(array);
            }
Exemple #34
0
	//===================================================================
	// Initialization performed on startup of the Python runtime.
	//===================================================================

	internal static void Initialize() {
	    pypath = new StringCollection();
	    namespaces = new Hashtable();
	    assemblies = new ArrayList();
	    probed = new Hashtable();

	    AppDomain domain = AppDomain.CurrentDomain;

	    lh = new AssemblyLoadEventHandler(AssemblyLoadHandler);
	    domain.AssemblyLoad += lh;

	    rh = new ResolveEventHandler(ResolveHandler);	
	    domain.AssemblyResolve += rh;

	    Assembly[] items = domain.GetAssemblies();
	    for (int i = 0; i < items.Length; i++) {
		Assembly a = items[i];
		assemblies.Add(a);
		ScanAssembly(a);
	    }
	}
        private static RuntimeAssembly InvokeResolveEvent(ResolveEventHandler eventHandler, RuntimeAssembly assembly, string name)
        {
            if (eventHandler == null)
            {
                return(null);
            }

            var args = new ResolveEventArgs(name, assembly);

            foreach (ResolveEventHandler handler in eventHandler.GetInvocationList())
            {
                Assembly        asm = handler(null /* AppDomain */, args);
                RuntimeAssembly ret = GetRuntimeAssembly(asm);
                if (ret != null)
                {
                    return(ret);
                }
            }

            return(null);
        }
Exemple #36
0
        /// <summary>
        /// Load type using <see cref="Type.GetType(string)"/>, and if fails,
        /// attempt to load same type from an assembly by assembly name,
        /// without specifying assembly version or any other part of the signature
        /// </summary>
        /// <param name="typeName">
        /// The assembly-qualified name of the type to get.
        /// See System.Type.AssemblyQualifiedName.
        /// If the type is in the currently executing assembly or in Mscorlib.dll, it
        /// is sufficient to supply the type name qualified by its namespace.
        /// </param>
        public static Type GetTypeFromAnyAssemblyVersion(string typeName)
        {
            // If we were unable to resolve type object
            //    - possibly because of the version change
            // Try to load using just the assembly name,
            // without any version/culture/public key info
            ResolveEventHandler assemblyResolve = OnAssemblyResolve;

            try
            {
                // Attach our custom assembly name resolver, attempt to resolve again, and detach it
                AppDomain.CurrentDomain.AssemblyResolve += assemblyResolve;
                _isGetTypeRunningOnThisThread            = true;
                return(Type.GetType(typeName));
            }
            finally
            {
                _isGetTypeRunningOnThisThread            = false;
                AppDomain.CurrentDomain.AssemblyResolve -= assemblyResolve;
            }
        }
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    if (_assemblyEventResolver != null)
                    {
                        AppDomain.CurrentDomain.AssemblyResolve -= _assemblyEventResolver;
                        _assemblyEventResolver = null;
                    }

                    if (this._container == null)
                    {
                        this._container.Dispose();
                        this._container = null;
                    }
                }
                disposedValue = true;
            }
        }
        public void Plugin_Dispose_Test()
        {
            // Arrange
            _MockPluginDependencyResolver.Setup(m => m.RemoveDependencyResolver());
            var  plugin    = CreatePlugin(true);
            bool wasCalled = false;
            ResolveEventHandler handler = (object sender, ResolveEventArgs args) =>
            {
                wasCalled = true;
                return(Assembly.GetExecutingAssembly());
            };

            _MockPluginDependencyResolver.Setup(m => m.Dispose());

            // Act
            plugin.Dispose();

            // Assert
            Assert.IsFalse(wasCalled, "The removed handle should not be called.");
            _MockRepository.VerifyAll();
        }
        void SetupAssemblyResolve(ResolveEventHandler resolveEventHandler)
        {
            if (resolveEventHandler == null)
            {
                _resolveEventHandler = new ResolveEventHandler(DefaultResolveEventHandler);
            }
            else
            {
                _resolveEventHandler = resolveEventHandler;
            }
            _resolveDirs = new List<string>();
            AppDomain.CurrentDomain.AssemblyResolve += _resolveEventHandler;


            string reflector = Config.Reflector;
            if (!String.IsNullOrEmpty(reflector) && File.Exists(reflector))
            {
                AddAssemblyResolveDir(Path.GetDirectoryName(reflector));
            }
            
        }
Exemple #40
0
        /// <summary>
        /// Tries to get the <see cref="Type"/> from the given <paramref name="settingsTypeName"/>.
        /// </summary>
        /// <param name="settingsTypeName">Assembly qualified type name.</param>
        /// <returns></returns>
        public static Type GetSettingsType(string settingsTypeName)
        {
            ResolveEventHandler customAssemblyResolver = CustomAssemblyResolver;

            try
            {
                if (customAssemblyResolver != null)
                {
                    AppDomain.CurrentDomain.AssemblyResolve += customAssemblyResolver;
                }

                return(Type.GetType(settingsTypeName));
            }
            finally
            {
                if (customAssemblyResolver != null)
                {
                    AppDomain.CurrentDomain.AssemblyResolve -= customAssemblyResolver;
                }
            }
        }
Exemple #41
0
        internal PackedHelper(string appId, string referencesId, string logFilename)
        {
            _logFilename        = logFilename;
            _temporaryDirectory = Path.Combine(Path.GetTempPath(), appId + "_libs");
            Directory.CreateDirectory(_temporaryDirectory);
            SetDllDirectory(_temporaryDirectory);

            Log(null);
            Handler = HandlerImpl;

#if DEBUG
            _references = null;
#else
            _references = new ResourceManager(referencesId, Assembly.GetExecutingAssembly());
#endif

            if (logFilename != null)
            {
                SetUnhandledExceptionHandler();
            }
        }
        public GacAssemblyResolver()
        {
            m_oAssemblyResolveHandler = GacAssemblyResolveHandler;

            IDataCache cache = CacheFactory.LocalCache;

            lock (m_locker)
            {
                object value;
                if (cache.TryGetCacheItem(m_cacheItemName, out value) == false)
                {
                    m_assemblyNameToFileMap = new Dictionary <string, string>();

                    cache.PutCacheItem(m_cacheItemName, m_assemblyNameToFileMap, true);
                }
                else
                {
                    m_assemblyNameToFileMap = (Dictionary <string, string>)value;
                }
            }
        }
Exemple #43
0
        static Test1()
        {
            ResolveEventHandler OnRhinoCommonResolve = null;

            AppDomain.CurrentDomain.AssemblyResolve += OnRhinoCommonResolve = (sender, args) =>
            {
                const string rhinoCommonAssemblyName = "RhinoCommon";
                var          assemblyName            = new AssemblyName(args.Name).Name;

                if (assemblyName != rhinoCommonAssemblyName)
                {
                    return(null);
                }

                AppDomain.CurrentDomain.AssemblyResolve -= OnRhinoCommonResolve;

                string rhinoSystemDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Rhino WIP", "System");
                //string rhinoSystemDir = @"C:\Users\EErtugrul\Desktop\Rhino WIP\System";
                return(Assembly.LoadFrom(Path.Combine(rhinoSystemDir, rhinoCommonAssemblyName + ".dll")));
            };
        }
        void SetupAssemblyResolve(ResolveEventHandler resolveEventHandler)
        {
            if (resolveEventHandler == null)
            {
                _resolveEventHandler = new ResolveEventHandler(DefaultResolveEventHandler);
            }
            else
            {
                _resolveEventHandler = resolveEventHandler;
            }
            _resolveDirs = new List <string>();
            AppDomain.CurrentDomain.AssemblyResolve += _resolveEventHandler;


            string reflector = Config.Reflector;

            if (!String.IsNullOrEmpty(reflector) && File.Exists(reflector))
            {
                AddAssemblyResolveDir(Path.GetDirectoryName(reflector));
            }
        }
        public TResult ReflectInstance <TResult>(Func <Assembly, Assembly[], TResult> func)
        {
            DirectoryInfo       directory           = new FileInfo(_assemblyPath).Directory;
            ResolveEventHandler resolveEventHandler =
                (s, e) =>
            {
                return(OnReflectionOnlyResolve(
                           e, directory));
            };

            AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += resolveEventHandler;

            var assembly = AppDomain.CurrentDomain.ReflectionOnlyGetAssemblies().FirstOrDefault
                               (a => new Uri(a.CodeBase).LocalPath.CompareTo(_assemblyPath) == 0);

            var result = func(assembly, AppDomain.CurrentDomain.GetAssemblies());

            AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= resolveEventHandler;

            return(result);
        }
            public void DoOnTypes(AssemblyName assemblyName, string path, AssemblyLoaderClient client, bool publicTypesOnly)
            {
                ResolveEventHandler resolve =
                    delegate(object sender, ResolveEventArgs args)
                {
                    var an = Path.Combine(path, args.Name.Split(',')[0] + ".dll");
                    return(System.IO.File.Exists(an) ? Assembly.LoadFile(an) : null);
                };

                AppDomain.CurrentDomain.AssemblyResolve += resolve;
                Assembly assembly = Assembly.Load(assemblyName);

                foreach (Type type in assembly.GetTypes())
                {
                    if (type.IsAbstract)
                    {
                        continue;
                    }
                    if (type.IsNestedPrivate)
                    {
                        continue;
                    }
                    if (publicTypesOnly && !type.IsVisible)
                    {
                        continue;
                    }
                    if (!typeof(System.ComponentModel.IComponent).IsAssignableFrom(type))
                    {
                        continue;
                    }
                    ToolboxItem item = CreateToolboxItem(type, assembly.GetName());
                    if (item == null)
                    {
                        continue;
                    }
                    client.DoOnToolboxItemForType(type.Namespace, item,
                                                  (byte[])TypeDescriptor.GetConverter(item.Bitmap).ConvertTo(item.Bitmap, typeof(byte[])));
                }
                AppDomain.CurrentDomain.AssemblyResolve -= resolve;
            }
Exemple #47
0
    public void Execute()
    {
        ResolveEventHandler assemblyResolve = CurrentDomain_AssemblyResolve;

        try
        {
            AppDomain.CurrentDomain.AssemblyResolve += assemblyResolve;
            SplitUpReferences();
            assemblyResolver = new AssemblyResolver(Logger, SplitReferences);
            ReadModule();
            var weavingInfoClassName = GetWeavingInfoClassName();
            if (ModuleDefinition.Types.Any(x => x.Name == weavingInfoClassName))
            {
                Logger.LogWarning($"The assembly has already been processed by Fody. Weaving aborted. Path: {AssemblyFilePath} ");
                return;
            }
            TypeCache = new TypeCache(assemblyResolver.Resolve);
            InitialiseWeavers();
            ValidatePackageReferenceSettings(weaverInstances, Logger);
            TypeCache.BuildAssembliesToScan(weaverInstances.Select(x => x.Instance));
            InitialiseTypeSystem();
            ExecuteWeavers();
            AddWeavingInfo();
            FindStrongNameKey();
            WriteModule();
            ModuleDefinition?.Dispose();
            ExecuteAfterWeavers();
            DisposeWeavers();
        }
        catch (Exception exception)
        {
            Logger.LogException(exception);
        }
        finally
        {
            AppDomain.CurrentDomain.AssemblyResolve -= assemblyResolve;
            ModuleDefinition?.Dispose();
            assemblyResolver?.Dispose();
        }
    }
Exemple #48
0
        public void AssemblyResolve_FirstChanceException()
        {
            RemoteExecutor.Invoke(() => {
                Assembly assembly = typeof(AppDomainTests).Assembly;

                Exception firstChanceExceptionThrown = null;

                EventHandler <System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs> firstChanceHandler = (source, args) =>
                {
                    firstChanceExceptionThrown = args.Exception;
                };

                AppDomain.CurrentDomain.FirstChanceException += firstChanceHandler;

                ResolveEventHandler assemblyResolveHandler = (sender, e) =>
                {
                    Assert.Equal(assembly, e.RequestingAssembly);
                    Assert.Null(firstChanceExceptionThrown);
                    return(null);
                };

                AppDomain.CurrentDomain.AssemblyResolve += assemblyResolveHandler;

                Func <System.Runtime.Loader.AssemblyLoadContext, AssemblyName, Assembly> resolvingHandler = (context, name) =>
                {
                    return(null);
                };

                // The issue resolved by coreclr#24450, was only reproduced when there was a Resolving handler present
                System.Runtime.Loader.AssemblyLoadContext.Default.Resolving += resolvingHandler;

                assembly.GetType("System.Tests.AGenericClass`1[[Bogus, BogusAssembly]]", false);
                Assert.Null(firstChanceExceptionThrown);

                Exception thrown = Assert.Throws <FileNotFoundException>(() => assembly.GetType("System.Tests.AGenericClass`1[[Bogus, AnotherBogusAssembly]]", true));
                Assert.Same(firstChanceExceptionThrown, thrown);

                return(RemoteExecutor.SuccessExitCode);
            }).Dispose();
        }
        /// <summary>
        /// constructor
        /// </summary>
        private Container()
        {
            // Suppress CA2000 since we want the object to persist until the end of the process
#pragma warning disable CA2000 // Dispose objects before losing scope
            // An aggregate catalog that combines multiple catalogs
            var catalog = new AggregateCatalog();

            // Adds all the parts found in the folder whether Microsoft.AcccessiblityInsights.Extentions.dll
            // later we will need to make it configurable.
            var dirCatalog = new DirectoryCatalog(Path.GetDirectoryName(typeof(Container).Assembly.Location), ExtensionSearchPattern);
            catalog.Catalogs.Add(dirCatalog);

            // Dynamically search for assemblies when it fails to resolve
            _extensionPaths        = GetExtensionPaths();
            _assemblyEventResolver = new ResolveEventHandler(CurrentDomain_AssemblyResolve);
            AppDomain.CurrentDomain.AssemblyResolve += _assemblyEventResolver;

            // Adds all the parts found in .\Extensions directory
            foreach (string path in _extensionPaths)
            {
                catalog.Catalogs.Add(new DirectoryCatalog(path, ExtensionSearchPattern));
            }

            //Create the CompositionContainer with the parts in the catalog
            _container = new CompositionContainer(catalog);

            //Fill the imports of this object
            try
            {
                _container.ComposeParts(this);
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch
            {
                // Fail silently, since the code is designed to run without extensions
                // and our Telemetry extension will always be null at this point
            }
#pragma warning restore CA1031 // Do not catch general exception types
#pragma warning restore CA2000 // Dispose objects before losing scope
        }
Exemple #50
0
		public Entry(ProjectItem item, EventModel model, IEnumerable<IEventScript> scripts, ResolveEventHandler resolver)
		{
			if (item == null)
				throw new ArgumentNullException("item");
			if (model == null)
				throw new ArgumentNullException("model");
			if (scripts == null)
				throw new ArgumentNullException("scripts");
			if (resolver == null)
				throw new ArgumentNullException("resolver");

			if (!scripts.Any())
				throw new ArgumentException("Scripts should not be 0.", "scripts");

			ProjectItem = item;
			EventModel = model;

			//Assembly = scripts.First().GetType().Assembly;						// Dont require the Assembly to be passed ?
			
			_scripts.AddRange(scripts);	
			Resolver = resolver;
		}
        public override Type BindToType(string assemblyName, string typeName)
        {
            ResolveEventHandler handler = new ResolveEventHandler(CurrentDomain_AssemblyResolve);
            AppDomain.CurrentDomain.AssemblyResolve += handler;

            Type returnedType;
            try
            {
                AssemblyName asmName = new AssemblyName(assemblyName);
                var assembly = Assembly.Load(asmName);
                returnedType = assembly.GetType(typeName);
            }
            catch
            {
                returnedType = null;
            }
            finally
            {
                AppDomain.CurrentDomain.AssemblyResolve -= handler;
            }

            return returnedType;
        }
        public void BeginResolving(params string[] searchPaths)
        {
            _resolveEventHandler = (sender, args) =>
            {
                var assemblySimpleName = GetSimpleName(args.Name);
                foreach (var searchPath in searchPaths)
                {
                    var assemblyPath = Path.Combine(searchPath, assemblySimpleName + ".dll");
                    try
                    {
                        return Assembly.LoadFrom(assemblyPath);
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }

                return null;
            };

            AppDomain.CurrentDomain.AssemblyResolve += _resolveEventHandler;
        }
        //===================================================================
        // Initialization performed on startup of the Python runtime. Here we
        // scan all of the currently loaded assemblies to determine exported
        // names, and register to be notified of new assembly loads.
        //===================================================================

        internal static void Initialize() {
            namespaces = new 
                         Dictionary<string, Dictionary<Assembly, string>>(32);
            probed = new Dictionary<string, int>(32);
            //generics = new Dictionary<string, Dictionary<string, string>>();
            assemblies = new List<Assembly>(16);
            pypath = new List<string>(16);

            AppDomain domain = AppDomain.CurrentDomain;

            lhandler = new AssemblyLoadEventHandler(AssemblyLoadHandler);
            domain.AssemblyLoad += lhandler;

            rhandler = new ResolveEventHandler(ResolveHandler);        
            domain.AssemblyResolve += rhandler;

            Assembly[] items = domain.GetAssemblies();
            for (int i = 0; i < items.Length; i++) {
                Assembly a = items[i];
                assemblies.Add(a);
                ScanAssembly(a);
            }
        }
 // this method must be called at the end of serialization
 internal void Dispose() {
     if (assemblyResolver != null)
         AppDomain.CurrentDomain.AssemblyResolve -= assemblyResolver;
     assemblyResolver = null;
 }
 public ProtectModuleHelper()
 {
     m_executingAssembly = Assembly.GetExecutingAssembly().Location;
     m_resolveEventHandler = new ResolveEventHandler(CurrentDomain_AssemblyResolve);
 }
 private void SetupAssemblyResolver()
 {
     ResolveEventHandler handler = new ResolveEventHandler(this.OnAssemblyResolve);
     AppDomain.CurrentDomain.AssemblyResolve += handler;
 }
 private Tuple<AppDomain, Action> CreateNewAppDomain(string friendlyName)
 {
     AppDomainSetup domainSetup = new AppDomainSetup();
     domainSetup.ApplicationName = friendlyName;
     domainSetup.ApplicationBase = Environment.CurrentDirectory;
     var assemblyResolveEventHandler = new ResolveEventHandler(CurrentDomain_AssemblyResolve);
     AppDomain.CurrentDomain.AssemblyResolve += assemblyResolveEventHandler;
     Action destructor = () => AppDomain.CurrentDomain.AssemblyResolve -= assemblyResolveEventHandler;
     var newAppDomain = AppDomain.CreateDomain(friendlyName, null, domainSetup);
     return Tuple.Create(newAppDomain, destructor);
 }
 [System.Security.SecurityCritical] // auto-generated
 #endif
 private RuntimeAssembly TryToResolveAssembly(RuntimeAssembly assembly, String assemblyFullName,
                                              ResolveEventHandler eventHandler,
                                              bool fInspectionOnly)
 {
     Delegate[] delegates = eventHandler.GetInvocationList();
     int len = delegates.Length;
     // Attempt all assembly resolve handlers before bailing out.
     // This by design can produce a number of loaded assemblies unused for the pending bind.
     for (int i = 0; i < len; i++) {
         RuntimeAssembly rtAssembly = null;
         // ---- handler exceptions to allow other handlers to proceed
         try {
             Assembly candidateAssembly =
                 ((ResolveEventHandler) delegates[i])(this,
                                                      new ResolveEventArgs(assemblyFullName, assembly));
             rtAssembly = GetRuntimeAssembly(candidateAssembly);
         }
         catch (Exception) {
             continue;
         }
         // Only accept assemblies that match the request
         if (rtAssembly != null)
         {
             if (nVerifyResolvedAssembly(assemblyFullName,
                                         rtAssembly,
                                         fInspectionOnly))
                 return rtAssembly;
         }
     }
     return null;
 }
		}

		protected void RemoveAssemblyResolver(ResolveEventHandler handler)
		{