コード例 #1
0
        /// <summary>
        /// Looks up in the cached <see cref="ResourceManager"/> list for the searched <see cref="ResourceManager"/>.
        /// </summary>
        /// <param name="resourceAssembly">The resource assembly.</param>
        /// <param name="resourceDictionary">The dictionary to look up.</param>
        /// <returns>
        /// The found <see cref="ResourceManager"/>
        /// </returns>
        /// <exception cref="System.InvalidOperationException">
        /// If the ResourceManagers cannot be looked up
        /// </exception>
        /// <exception cref="System.ArgumentException">
        /// If the searched <see cref="ResourceManager"/> wasn't found
        /// </exception>
        protected ResourceManager GetResourceManager(string resourceAssembly, string resourceDictionary)
        {
            Assembly        assembly = null;
            ResourceManager resManager;
            string          foundResource          = null;
            string          resManagerNameToSearch = "." + resourceDictionary + ResourceFileExtension;

            var resManKey = resourceAssembly + resManagerNameToSearch;

#if !SILVERLIGHT
            // Here comes our great hack for full VS2012+ design time support with multiple languages.
            // We check only every second to reduce overhead in the designer.
            var now = DateTime.Now;

            if (AppDomain.CurrentDomain.FriendlyName.Contains("XDesProc") && ((now - lastUpdateCheck).TotalSeconds >= 1.0))
            {
                // This block is only handled during design time.
                lastUpdateCheck = now;

                // Get the directory of the executing assembly (some strange path in the middle of nowhere on the disk and attach "\tmp", e.g.:
                // %userprofile%\AppData\Local\Microsoft\VisualStudio\12.0\Designer\ShadowCache\erys4uqz.oq1\l24nfewi.r0y\tmp\
                var assemblyDir = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "tmp");

                // Find the VS process that shows our design.
                foreach (var process in Process.GetProcesses())
                {
                    if (!process.ProcessName.Contains(".vshost"))
                    {
                        continue;
                    }

                    // Get the executable path (all paths are cached now in order to reduce WMI load.
                    var dir = Path.GetDirectoryName(GetExecutablePath(process.Id));

                    if (string.IsNullOrEmpty(dir))
                    {
                        continue;
                    }

                    // Get all files matching our resource assembly.
                    var files = Directory.GetFiles(dir, resourceAssembly + ".*", SearchOption.AllDirectories);

                    if (files.Length > 0)
                    {
                        // Get more files.
                        files = Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories).Where(f => IsFileOfInterest(f, dir)).ToArray();

                        // Remove the resource manager from the dictionary.
                        TryRemove(resManKey);

                        // Copy all newer or missing files.
                        foreach (var f in files)
                        {
                            try
                            {
                                var dst = Path.Combine(assemblyDir, f.Replace(dir + "\\", ""));

                                if (!File.Exists(dst) || (Directory.GetLastWriteTime(dst) < Directory.GetLastWriteTime(f)))
                                {
                                    var dstDir = Path.GetDirectoryName(dst);
                                    if (String.IsNullOrEmpty(dstDir))
                                    {
                                        continue;
                                    }
                                    if (!Directory.Exists(dstDir))
                                    {
                                        Directory.CreateDirectory(dstDir);
                                    }

                                    File.Copy(f, dst, true);
                                }
                            }
                            // ReSharper disable once EmptyGeneralCatchClause
                            catch { }
                        }

                        // Prepare and load (new) assembly.
                        var file = Path.Combine(assemblyDir, resourceAssembly + ".exe");
                        if (!File.Exists(file))
                        {
                            file = Path.Combine(assemblyDir, resourceAssembly + ".dll");
                        }

                        assembly = Assembly.LoadFrom(file);

                        // Must break here - otherwise, we might have caught another instance of VS.
                        break;
                    }
                }
            }
#endif

            if (!TryGetValue(resManKey, out resManager))
            {
                // If the assembly cannot be loaded, throw an exception
                if (assembly == null)
                {
                    try
                    {
                        // go through every assembly loaded in the app domain
                        var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
                        foreach (var assemblyInAppDomain in loadedAssemblies)
                        {
                            // get the assembly name object
                            AssemblyName assemblyName = new AssemblyName(assemblyInAppDomain.FullName);

                            // check if the name of the assembly is the seached one
                            if (assemblyName.Name == resourceAssembly)
                            {
                                // assigne the assembly
                                assembly = assemblyInAppDomain;

                                // stop the search here
                                break;
                            }
                        }

                        // check if the assembly is still null
                        if (assembly == null)
                        {
                            // assign the loaded assembly
#if SILVERLIGHT
                            var name = new AssemblyName(resourceAssembly);
                            assembly = Assembly.Load(name.FullName);
#else
                            assembly = Assembly.Load(new AssemblyName(resourceAssembly));
#endif
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(string.Format("The Assembly '{0}' cannot be loaded.", resourceAssembly), ex);
                    }
                }

                // get all available resourcenames
                string[] availableResources = assembly.GetManifestResourceNames();

                // get all available types (and ignore unloadable types, e.g. because of unsatisfied dependencies)
                IEnumerable <Type> availableTypes;
                try
                {
                    availableTypes = assembly.GetTypes();
                }
                catch (ReflectionTypeLoadException e)
                {
                    availableTypes = e.Types.Where(t => t != null);
                }

                // The proposed approach of Andras (http://wpflocalizeextension.codeplex.com/discussions/66098?ProjectName=wpflocalizeextension)
                Func <Type, string> tryGetNamespace = delegate(Type type)
                {
                    // Ignore unloadable types
                    try
                    {
                        return(type.Namespace);
                    }
                    catch (Exception)
                    {
                        return(null);
                    }
                };
                var possiblePrefixes = availableTypes.Select(tryGetNamespace).Where(n => n != null).Distinct().ToList();

                foreach (string availableResource in availableResources)
                {
                    if (availableResource.EndsWith(resManagerNameToSearch) && possiblePrefixes.Any(p => availableResource.StartsWith(p + ".")))
                    {
                        // take the first occurrence and break
                        foundResource = availableResource;
                        break;
                    }
                }

                // NOTE: Inverted this IF (nesting is bad, I know) so we just create a new ResourceManager.  -gen3ric
                if (foundResource != null)
                {
                    // remove ".resources" from the end
                    foundResource = foundResource.Substring(0, foundResource.Length - ResourceFileExtension.Length);

                    // First try the simple retrieval
                    Type resourceManagerType;
                    try
                    {
                        resourceManagerType = assembly.GetType(foundResource);
                    }
                    catch (Exception)
                    {
                        resourceManagerType = null;
                    }

                    // If simple doesn't work, check all of the types without using dot notation
                    if (resourceManagerType == null)
                    {
                        var dictTypeName = resourceDictionary.Replace('.', '_');

                        Func <Type, bool> matchesDictTypeName = delegate(Type type)
                        {
                            // Ignore unloadable types
                            try
                            {
                                return(type.Name == dictTypeName);
                            }
                            catch (Exception)
                            {
                                return(false);
                            }
                        };
                        resourceManagerType = availableTypes.FirstOrDefault(matchesDictTypeName);
                    }

                    resManager = GetResourceManagerFromType(resourceManagerType);
                }
                else
                {
                    resManager = new ResourceManager(resManagerNameToSearch, assembly);
                }

                // if no one was found, exception
                if (resManager == null)
                {
                    throw new ArgumentException(string.Format("No resource manager for dictionary '{0}' in assembly '{1}' found! ({1}.{0})", resourceDictionary, resourceAssembly));
                }

                // Add the ResourceManager to the cachelist
                Add(resManKey, resManager);

                try
                {
#if SILVERLIGHT
                    var cultures = CultureInfoHelper.GetCultures();

                    foreach (var c in cultures)
                    {
                        var dir = c.Name + "/";

                        foreach (var p in Deployment.Current.Parts)
                        {
                            if (p.Source.StartsWith(dir))
                            {
                                AddCulture(c);
                                break;
                            }
                        }
                    }
#else
                    var assemblyLocation = Path.GetDirectoryName(assembly.Location);

                    // Get the list of all cultures.
                    var cultures = CultureInfo.GetCultures(CultureTypes.AllCultures);

                    foreach (var c in cultures)
                    {
                        var rs = resManager.GetResourceSet(c, true, false);
                        if (rs != null)
                        {
                            AddCulture(c);
                        }
                    }
#endif
                }
                catch
                {
                    // This may lead to problems with Silverlight
                }
            }

            // return the found ResourceManager
            return(resManager);
        }
コード例 #2
0
        /// <summary>
        /// Looks up in the cached <see cref="ResourceManager"/> list for the searched <see cref="ResourceManager"/>.
        /// </summary>
        /// <param name="resourceAssembly">The resource assembly (e.g.: <c>BaseLocalizeExtension</c>). NULL = Name of the executing assembly</param>
        /// <param name="resourceDictionary">The dictionary to look up (e.g.: ResHelp, Resources, ...). NULL = Name of the default resource file (Resources)</param>
        /// <returns>
        /// The found <see cref="ResourceManager"/>
        /// </returns>
        /// <exception cref="System.InvalidOperationException">
        /// If the ResourceManagers cannot be looked up
        /// </exception>
        /// <exception cref="System.ArgumentException">
        /// If the searched <see cref="ResourceManager"/> wasn't found
        /// </exception>
        protected ResourceManager GetResourceManager(string resourceAssembly, string resourceDictionary)
        {
            PropertyInfo    propInfo;
            MethodInfo      methodInfo;
            Assembly        assembly = null;
            ResourceManager resManager;
            string          foundResource          = null;
            string          resManagerNameToSearch = "." + resourceDictionary + ResourceFileExtension;

            string[] availableResources;
            var      keyManKey = resourceAssembly + resManagerNameToSearch;

            if (!TryGetValue(keyManKey, out resManager))
            {
                // if the assembly cannot be loaded, throw an exception
                try
                {
                    // go through every assembly loaded in the app domain
                    foreach (Assembly assemblyInAppDomain in AppDomain.CurrentDomain.GetAssemblies())
                    {
                        // check if the name pf the assembly is not null
                        if (assemblyInAppDomain.FullName != null)
                        {
                            // get the assembly name object
                            AssemblyName assemblyName = new AssemblyName(assemblyInAppDomain.FullName);

                            // check if the name of the assembly is the seached one
                            if (assemblyName.Name == resourceAssembly)
                            {
                                // assigne the assembly
                                assembly = assemblyInAppDomain;

                                // stop the search here
                                break;
                            }
                        }
                    }

                    // check if the assembly is still null
                    if (assembly == null)
                    {
                        // assign the loaded assembly
#if SILVERLIGHT
                        var name = new AssemblyName(resourceAssembly);
                        assembly = Assembly.Load(name.FullName);
#else
                        assembly = Assembly.Load(new AssemblyName(resourceAssembly));
#endif
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(string.Format("The Assembly '{0}' cannot be loaded.", resourceAssembly), ex);
                }

                // get all available resourcenames
                availableResources = assembly.GetManifestResourceNames();

                // The proposed approach of Andras (http://wpflocalizeextension.codeplex.com/discussions/66098?ProjectName=wpflocalizeextension)
                var possiblePrefixes = new List <string>(assembly.GetTypes().Select((t) => t.Namespace).Distinct());

                for (int i = 0; i < availableResources.Length; i++)
                {
                    if (availableResources[i].EndsWith(resManagerNameToSearch))
                    {
                        var matches = possiblePrefixes.Where((p) => availableResources[i].StartsWith(p + "."));
                        if (matches.Count() != 0)
                        {
                            // take the first occurrence and break
                            foundResource = availableResources[i];
                            break;
                        }
                    }
                }

                // if no one was found, exception
                if (foundResource == null)
                {
                    throw new ArgumentException(
                              string.Format(
                                  "No resource manager for dictionary '{0}' in assembly '{1}' found! ({1}.{0})",
                                  resourceDictionary,
                                  resourceAssembly));
                }

                // remove ".resources" from the end
                foundResource = foundResource.Substring(0, foundResource.Length - ResourceFileExtension.Length);

                //// Resources.{foundResource}.ResourceManager.GetObject()
                //// ^^ prop-info      ^^ method get

                try
                {
                    // get the propertyinfo from resManager over the type from foundResource
                    var resourceManagerType = assembly.GetType(foundResource);

                    // check if the resource manager was found.
                    // if not, assume that the assembly was build with VisualBasic.
                    // in this case try to manipulate the resource identifier.
                    if (resourceManagerType == null)
                    {
#if SILVERLIGHT
                        var assemblyName = resourceAssembly;
#else
                        var assemblyName = assembly.GetName().Name;
#endif
                        resourceManagerType = assembly.GetType(foundResource.Replace(assemblyName, assemblyName + ".My.Resources"));
                    }

                    propInfo = resourceManagerType.GetProperty(ResourceManagerName, ResourceBindingFlags);

                    // get the GET-method from the methodinfo
                    methodInfo = propInfo.GetGetMethod(true);

                    // get the static ResourceManager property
                    object resManObject = methodInfo.Invoke(null, null);

                    // cast it to a ResourceManager for better working with
                    resManager = (ResourceManager)resManObject;
                }
                catch (Exception ex)
                {
                    // this error has to get thrown because this has to work
                    throw new InvalidOperationException("Cannot resolve the ResourceManager!", ex);
                }

                // Add the ResourceManager to the cachelist
                Add(keyManKey, resManager);

                try
                {
#if SILVERLIGHT
                    var cultures = CultureInfoHelper.GetCultures();

                    foreach (var c in cultures)
                    {
                        var dir = c.Name + "/";

                        foreach (var p in Deployment.Current.Parts)
                        {
                            if (p.Source.StartsWith(dir))
                            {
                                AddCulture(c);
                                break;
                            }
                        }
                    }
#else
                    var assemblyLocation = Path.GetDirectoryName(assembly.Location);

                    // Get all directories named like a specific culture.
                    var dirs = Directory.GetDirectories(assemblyLocation, "??-??").ToList();
                    // Get all directories named like a culture.
                    dirs.AddRange(Directory.GetDirectories(assemblyLocation, "??"));

                    // Get the list of all cultures.
                    var cultures = CultureInfo.GetCultures(CultureTypes.AllCultures);

                    foreach (var c in cultures)
                    {
                        var dir = Path.Combine(assemblyLocation, c.Name);
                        if (Directory.Exists(dir) &&
                            Directory.GetFiles(dir, "*.resources.dll").Length > 0)
                        {
                            AddCulture(c);
                        }
                    }
#endif
                }
                catch
                {
                    // This may lead to problems with Silverlight
                }
            }

            // return the found ResourceManager
            return(resManager);
        }
        /// <summary>
        /// Looks up in the cached <see cref="ResourceManager"/> list for the searched <see cref="ResourceManager"/>.
        /// </summary>
        /// <param name="resourceAssembly">The resource assembly.</param>
        /// <param name="resourceDictionary">The dictionary to look up.</param>
        /// <returns>
        /// The found <see cref="ResourceManager"/>
        /// </returns>
        /// <exception cref="System.InvalidOperationException">
        /// If the ResourceManagers cannot be looked up
        /// </exception>
        /// <exception cref="System.ArgumentException">
        /// If the searched <see cref="ResourceManager"/> wasn't found
        /// </exception>
        protected ResourceManager GetResourceManager(string resourceAssembly, string resourceDictionary)
        {
            PropertyInfo    propInfo;
            MethodInfo      methodInfo;
            Assembly        assembly = null;
            ResourceManager resManager;
            string          foundResource          = null;
            string          resManagerNameToSearch = "." + resourceDictionary + ResourceFileExtension;

            string[] availableResources;

            //var resManKey = designPath + resourceAssembly + resManagerNameToSearch;
            var resManKey = resourceAssembly + resManagerNameToSearch;

#if !SILVERLIGHT
            if (AppDomain.CurrentDomain.FriendlyName.Contains("XDesProc"))
            {
                var assemblyDir = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "tmp");

                foreach (var process in Process.GetProcesses())
                {
                    if (!process.ProcessName.Contains(".vshost"))
                    {
                        continue;
                    }

                    var dir   = Path.GetDirectoryName(process.Modules[0].FileName);
                    var files = Directory.GetFiles(dir, resourceAssembly + ".*", SearchOption.AllDirectories);
                    var dirs  = Directory.GetDirectories(dir);

                    if (files.Length > 0)
                    {
                        files = Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories);
                        bool updateManager = false;

                        foreach (var f in files)
                        {
                            var dst = Path.Combine(assemblyDir, f.Replace(dir + "\\", ""));

                            if (!File.Exists(dst) || (Directory.GetLastWriteTime(dst) < Directory.GetLastWriteTime(f)))
                            {
                                updateManager = true;
                                break;
                            }
                        }

                        if (updateManager)
                        {
                            TryRemove(resManKey);

                            if (shadowCacheAppDomain != null)
                            {
                                AppDomain.Unload(shadowCacheAppDomain);
                                shadowCacheAppDomain = null;

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

                            foreach (var f in files)
                            {
                                var dst = Path.Combine(assemblyDir, f.Replace(dir + "\\", ""));

                                var dstDir = Path.GetDirectoryName(dst);
                                if (!Directory.Exists(dstDir))
                                {
                                    Directory.CreateDirectory(dstDir);
                                }
                                File.Copy(f, dst, true);
                            }
                        }

                        var file = Path.Combine(assemblyDir, resourceAssembly + ".exe");
                        if (!File.Exists(file))
                        {
                            file = Path.Combine(assemblyDir, resourceAssembly + ".dll");
                        }

                        //if (shadowCacheAppDomain == null)
                        //{
                        //    shadowCacheAppDomain = AppDomain.CreateDomain("LocalizationDomain");
                        //    AppDomain.CurrentDomain.AssemblyResolve += (s, e) =>
                        //    {
                        //        return Assembly.LoadFrom(file);
                        //    };
                        //}

                        //var name = new AssemblyName { CodeBase = file };
                        //assembly = shadowCacheAppDomain.Load(resourceAssembly);

                        assembly = Assembly.LoadFrom(file);
                        break;
                    }

                    break;
                }
            }
#endif

            if (!TryGetValue(resManKey, out resManager))
            {
                // If the assembly cannot be loaded, throw an exception
                if (assembly == null)
                {
                    try
                    {
                        // go through every assembly loaded in the app domain
                        var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
                        foreach (var assemblyInAppDomain in loadedAssemblies)
                        {
                            // check if the name pf the assembly is not null
                            if (assemblyInAppDomain.FullName != null)
                            {
                                // get the assembly name object
                                AssemblyName assemblyName = new AssemblyName(assemblyInAppDomain.FullName);

                                // check if the name of the assembly is the seached one
                                if (assemblyName.Name == resourceAssembly)
                                {
                                    // assigne the assembly
                                    assembly = assemblyInAppDomain;

                                    // stop the search here
                                    break;
                                }
                            }
                        }

                        // check if the assembly is still null
                        if (assembly == null)
                        {
                            // assign the loaded assembly
#if SILVERLIGHT
                            var name = new AssemblyName(resourceAssembly);
                            assembly = Assembly.Load(name.FullName);
#else
                            assembly = Assembly.Load(new AssemblyName(resourceAssembly));
#endif
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(string.Format("The Assembly '{0}' cannot be loaded.", resourceAssembly), ex);
                    }
                }

                // get all available resourcenames
                availableResources = assembly.GetManifestResourceNames();

                // The proposed approach of Andras (http://wpflocalizeextension.codeplex.com/discussions/66098?ProjectName=wpflocalizeextension)
                var possiblePrefixes = new List <string>(assembly.GetTypes().Select((t) => t.Namespace).Distinct());

                for (int i = 0; i < availableResources.Length; i++)
                {
                    if (availableResources[i].EndsWith(resManagerNameToSearch))
                    {
                        var matches = possiblePrefixes.Where((p) => availableResources[i].StartsWith(p + "."));
                        if (matches.Count() != 0)
                        {
                            // take the first occurrence and break
                            foundResource = availableResources[i];
                            break;
                        }
                    }
                }

                // NOTE: Inverted this IF (nesting is bad, I know) so we just create a new ResourceManager.  -gen3ric
                if (foundResource != null)
                {
                    // remove ".resources" from the end
                    foundResource = foundResource.Substring(0, foundResource.Length - ResourceFileExtension.Length);

                    var dictTypeName = resourceDictionary.Replace('.', '_');

                    foreach (var type in assembly.GetTypes())
                    {
                        if (type.Name == dictTypeName)
                        {
                            try
                            {
                                propInfo = type.GetProperty(ResourceManagerName, ResourceBindingFlags);

                                // get the GET-method from the methodinfo
                                methodInfo = propInfo.GetGetMethod(true);

                                // cast it to a ResourceManager for better working with
                                resManager = (ResourceManager)methodInfo.Invoke(null, null);
                                break;
                            }
                            catch
                            {
                            }
                        }
                    }
                }
                else
                {
                    resManager = new ResourceManager(resManagerNameToSearch, assembly);
                }

                // if no one was found, exception
                if (resManager == null)
                {
                    throw new ArgumentException(string.Format("No resource manager for dictionary '{0}' in assembly '{1}' found! ({1}.{0})", resourceDictionary, resourceAssembly));
                }

                // Add the ResourceManager to the cachelist
                Add(resManKey, resManager);

                try
                {
#if SILVERLIGHT
                    var cultures = CultureInfoHelper.GetCultures();

                    foreach (var c in cultures)
                    {
                        var dir = c.Name + "/";

                        foreach (var p in Deployment.Current.Parts)
                        {
                            if (p.Source.StartsWith(dir))
                            {
                                AddCulture(c);
                                break;
                            }
                        }
                    }
#else
                    var assemblyLocation = Path.GetDirectoryName(assembly.Location);

                    // Get the list of all cultures.
                    var cultures = CultureInfo.GetCultures(CultureTypes.AllCultures);

                    foreach (var c in cultures)
                    {
                        var dir = Path.Combine(assemblyLocation, c.Name);
                        if (Directory.Exists(dir) && Directory.GetFiles(dir, "*.resources.dll").Length > 0)
                        {
                            AddCulture(c);
                        }
                    }
#endif
                }
                catch
                {
                    // This may lead to problems with Silverlight
                }
            }

            // return the found ResourceManager
            return(resManager);
        }
コード例 #4
0
        /// <summary>
        /// Looks up in the cached <see cref="ResourceManager"/> list for the searched <see cref="ResourceManager"/>.
        /// </summary>
        /// <param name="resourceAssembly">The resource assembly.</param>
        /// <param name="resourceDictionary">The dictionary to look up.</param>
        /// <returns>
        /// The found <see cref="ResourceManager"/>
        /// </returns>
        /// <exception cref="System.InvalidOperationException">
        /// If the ResourceManagers cannot be looked up
        /// </exception>
        /// <exception cref="System.ArgumentException">
        /// If the searched <see cref="ResourceManager"/> wasn't found
        /// </exception>
        protected ResourceManager GetResourceManager(string resourceAssembly, string resourceDictionary)
        {
            Assembly        assembly = null;
            ResourceManager resManager;
            string          foundResource          = null;
            string          resManagerNameToSearch = "." + resourceDictionary + ResourceFileExtension;


            var resManKey = resourceAssembly + resManagerNameToSearch;

#if !SILVERLIGHT
            if (AppDomain.CurrentDomain.FriendlyName.Contains("XDesProc"))
            {
                var assemblyDir = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "tmp");

                foreach (var process in Process.GetProcesses())
                {
                    if (!process.ProcessName.Contains(".vshost"))
                    {
                        continue;
                    }

                    var dir = Path.GetDirectoryName(GetExecutablePath(process.Id));

                    if (string.IsNullOrEmpty(dir))
                    {
                        continue;
                    }

                    var files = Directory.GetFiles(dir, resourceAssembly + ".*", SearchOption.AllDirectories);

                    if (files.Length > 0)
                    {
                        files = Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories).Where(f => IsFileOfInterest(f, dir)).ToArray();
                        bool updateManager = false;

                        foreach (var f in files)
                        {
                            var dst = Path.Combine(assemblyDir, f.Replace(dir + "\\", ""));

                            if (!File.Exists(dst) || (Directory.GetLastWriteTime(dst) < Directory.GetLastWriteTime(f)))
                            {
                                updateManager = true;
                                break;
                            }
                        }

                        if (updateManager)
                        {
                            TryRemove(resManKey);

                            if (shadowCacheAppDomain != null)
                            {
                                AppDomain.Unload(shadowCacheAppDomain);
                                shadowCacheAppDomain = null;

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

                            foreach (var f in files)
                            {
                                try
                                {
                                    var dst = Path.Combine(assemblyDir, f.Replace(dir + "\\", ""));

                                    var dstDir = Path.GetDirectoryName(dst);
                                    if (String.IsNullOrEmpty(dstDir))
                                    {
                                        continue;
                                    }
                                    if (!Directory.Exists(dstDir))
                                    {
                                        Directory.CreateDirectory(dstDir);
                                    }

                                    File.Copy(f, dst, true);
                                }
                                // ReSharper disable once EmptyGeneralCatchClause
                                catch { }
                            }
                        }

                        var file = Path.Combine(assemblyDir, resourceAssembly + ".exe");
                        if (!File.Exists(file))
                        {
                            file = Path.Combine(assemblyDir, resourceAssembly + ".dll");
                        }

                        assembly = Assembly.LoadFrom(file);
                    }

                    break;
                }
            }
#endif

            if (!TryGetValue(resManKey, out resManager))
            {
                // If the assembly cannot be loaded, throw an exception
                if (assembly == null)
                {
                    try
                    {
                        // go through every assembly loaded in the app domain
                        var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
                        foreach (var assemblyInAppDomain in loadedAssemblies)
                        {
                            // get the assembly name object
                            AssemblyName assemblyName = new AssemblyName(assemblyInAppDomain.FullName);

                            // check if the name of the assembly is the seached one
                            if (assemblyName.Name == resourceAssembly)
                            {
                                // assigne the assembly
                                assembly = assemblyInAppDomain;

                                // stop the search here
                                break;
                            }
                        }

                        // check if the assembly is still null
                        if (assembly == null)
                        {
                            // assign the loaded assembly
#if SILVERLIGHT
                            var name = new AssemblyName(resourceAssembly);
                            assembly = Assembly.Load(name.FullName);
#else
                            assembly = Assembly.Load(new AssemblyName(resourceAssembly));
#endif
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(string.Format("The Assembly '{0}' cannot be loaded.", resourceAssembly), ex);
                    }
                }

                // get all available resourcenames
                string[] availableResources = assembly.GetManifestResourceNames();

                // get all available types (and ignore unloadable types, e.g. because of unsatisfied dependencies)
                IEnumerable <Type> availableTypes;
                try
                {
                    availableTypes = assembly.GetTypes();
                }
                catch (ReflectionTypeLoadException e)
                {
                    availableTypes = e.Types.Where(t => t != null);
                }

                // The proposed approach of Andras (http://wpflocalizeextension.codeplex.com/discussions/66098?ProjectName=wpflocalizeextension)
                Func <Type, string> tryGetNamespace = delegate(Type type)
                {
                    // Ignore unloadable types
                    try
                    {
                        return(type.Namespace);
                    }
                    catch (Exception)
                    {
                        return(null);
                    }
                };
                var possiblePrefixes = availableTypes.Select(tryGetNamespace).Where(n => n != null).Distinct().ToList();

                foreach (string availableResource in availableResources)
                {
                    if (availableResource.EndsWith(resManagerNameToSearch) && possiblePrefixes.Any(p => availableResource.StartsWith(p + ".")))
                    {
                        // take the first occurrence and break
                        foundResource = availableResource;
                        break;
                    }
                }

                // NOTE: Inverted this IF (nesting is bad, I know) so we just create a new ResourceManager.  -gen3ric
                if (foundResource != null)
                {
                    // remove ".resources" from the end
                    foundResource = foundResource.Substring(0, foundResource.Length - ResourceFileExtension.Length);

                    // First try the simple retrieval
                    Type resourceManagerType;
                    try
                    {
                        resourceManagerType = assembly.GetType(foundResource);
                    }
                    catch (Exception)
                    {
                        resourceManagerType = null;
                    }

                    // If simple doesn't work, check all of the types without using dot notation
                    if (resourceManagerType == null)
                    {
                        var dictTypeName = resourceDictionary.Replace('.', '_');

                        Func <Type, bool> matchesDictTypeName = delegate(Type type)
                        {
                            // Ignore unloadable types
                            try
                            {
                                return(type.Name == dictTypeName);
                            }
                            catch (Exception)
                            {
                                return(false);
                            }
                        };
                        resourceManagerType = availableTypes.FirstOrDefault(matchesDictTypeName);
                    }

                    resManager = GetResourceManagerFromType(resourceManagerType);
                }
                else
                {
                    resManager = new ResourceManager(resManagerNameToSearch, assembly);
                }

                // if no one was found, exception
                if (resManager == null)
                {
                    throw new ArgumentException(string.Format("No resource manager for dictionary '{0}' in assembly '{1}' found! ({1}.{0})", resourceDictionary, resourceAssembly));
                }

                // Add the ResourceManager to the cachelist
                Add(resManKey, resManager);

                try
                {
#if SILVERLIGHT
                    var cultures = CultureInfoHelper.GetCultures();

                    foreach (var c in cultures)
                    {
                        var dir = c.Name + "/";

                        foreach (var p in Deployment.Current.Parts)
                        {
                            if (p.Source.StartsWith(dir))
                            {
                                AddCulture(c);
                                break;
                            }
                        }
                    }
#else
                    var assemblyLocation = Path.GetDirectoryName(assembly.Location);

                    // Get the list of all cultures.
                    var cultures = CultureInfo.GetCultures(CultureTypes.AllCultures);

                    foreach (var c in cultures)
                    {
                        var rs = resManager.GetResourceSet(c, true, false);
                        if (rs != null)
                        {
                            AddCulture(c);
                        }
                    }
#endif
                }
                catch
                {
                    // This may lead to problems with Silverlight
                }
            }

            // return the found ResourceManager
            return(resManager);
        }