|
using System;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Web;
using System.Web.Caching;
using System.Xml;
namespace Localization{
/// <summary>
/// ResourceManager class used to access localized content in XML files
/// </summary>
public sealed class ResourceManager{
private ResourceManager(){}
/// <summary>
/// Retrieves the RFC 1766 name of the current culture
/// </summary>
/// <remarks>
/// This would more likely belong in an utility/global class, but for simplicities sake, I've put it here
/// </remarks>
public static string CurrentCultureName {
get { return System.Threading.Thread.CurrentThread.CurrentCulture.Name;}
}
/// <summary>
/// Wrapper to GetString() to get a colon
/// </summary>
public static string Colon {
get { return GetString("colon"); }
}
/// <summary>
/// Returns
/// </summary>
/// <param name="key" type="string">
/// <para>
/// The name of the resource we want
/// </para>
/// </param>
/// <remarks>
/// When in DEBUG mode, an ApplicationException will be thrown if the key isn't found
/// </remarks>
public static string GetString( string key) {
Hashtable messages = GetResource();
if (messages[key] == null){
messages[key] = string.Empty;
#if DEBUG
throw new ApplicationException("Resource value not found for key: " + key);
#endif
}
return (string)messages[key];
}
private static Hashtable GetResource() {
string currentCulture = CurrentCultureName;
string defaultCulture = LocalizationConfiguration.GetConfig().DefaultCultureName;
string cacheKey = "Localization:" + defaultCulture + ':' + currentCulture;
if (HttpRuntime.Cache[cacheKey] == null){
Hashtable resource = new Hashtable();
LoadResource(resource, defaultCulture, cacheKey);
if (defaultCulture != currentCulture){
try{
LoadResource(resource, currentCulture, cacheKey);
} catch (FileNotFoundException){}
}
}
return (Hashtable)HttpRuntime.Cache[cacheKey];
}
private static void LoadResource(Hashtable resource, string culture, string cacheKey) {
string file = LocalizationConfiguration.GetConfig().LanguageFilePath + '\\' + culture + "\\Resource.xml";
XmlDocument xml = new XmlDocument();
xml.Load(file);
foreach (XmlNode n in xml.SelectSingleNode("Resource")) {
if (n.NodeType != XmlNodeType.Comment){
resource[n.Attributes["name"].Value] = n.InnerText;
}
}
HttpRuntime.Cache.Insert(cacheKey, resource, new CacheDependency(file), DateTime.MaxValue, TimeSpan.Zero);
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.