using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Windows.Markup; namespace Developpez.Dotnet.Windows { internal class AssemblyManager { public static Assembly GetEntryAssembly() { Assembly asm = Assembly.GetEntryAssembly(); // Mode design if (asm == null) { // En mode design, Assembly.GetEntryAssembly ne fonctionne pas // On cherche donc un assembly avec un point d'entrée qui contient // une classe héritée de System.Windows.Application asm = ( from a in AppDomain.CurrentDomain.GetAssemblies() where a.EntryPoint != null && a.GetTypes().Any(t => t.IsSubclassOf(typeof(System.Windows.Application))) select a ).FirstOrDefault(); } return asm; } public static Uri GetRootUri(IUriContext uriContext) { string authority = uriContext.BaseUri.GetLeftPart(UriPartial.Authority); if (uriContext.BaseUri.Segments.Length > 1) { string path = uriContext.BaseUri.Segments[0] + uriContext.BaseUri.Segments[1]; return new Uri(authority + path); } else return null; } private static Dictionary _assembliesByUri = new Dictionary(); public static Assembly GetAssembly(IUriContext uriContext) { Uri baseUri = GetRootUri(uriContext); Assembly assembly = null; if (_assembliesByUri.TryGetValue(baseUri, out assembly)) { return assembly; } else { if (baseUri.Authority == "application:,,," && baseUri.Segments.Length > 1) { string seg1 = baseUri.Segments[1]; int idx = seg1.IndexOf(";component"); if (idx >= 0) { string assemblySpec = seg1.Substring(0, idx); string[] assemblyParts = assemblySpec.Split(';'); string uriAsmName = assemblyParts[0]; string uriAsmVersion = null; string uriAsmPubKeyToken = null; if (assemblyParts.Length > 1) uriAsmVersion = assemblyParts[1]; if (assemblyParts.Length > 2) uriAsmPubKeyToken = assemblyParts[2]; System.Reflection.Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (System.Reflection.Assembly asm in assemblies) { System.Reflection.AssemblyName asmName = asm.GetName(); string pubKeyToken =asmName.GetPublicKeyToken().ToHexString(); if (asmName.Name == uriAsmName && (uriAsmVersion == null || asmName.Version.ToString() == uriAsmVersion) && (uriAsmPubKeyToken == null || pubKeyToken == uriAsmPubKeyToken)) { _assembliesByUri.Add(baseUri, asm); return asm; } } } } } return null; } } }