/// <summary> /// Populates the needed enumeration Dictionaries for translating en-US strings by /// transversing the en-US resource file and finding the appropriate EnumSets. /// </summary> /// <remarks> /// This method should be faster than using the enumSets/{id}/members api endpoint. /// This method has a potential for value mismatch if the local enumeration values differ /// from the server. This will cause the translation functionality to fail since no matching /// enumeration key will be found in dictionaries. /// </remarks> private static void SetEnumerationDictionaries() { // First time setup, there are about 349 values in the command set, 800 in the objectType set CommandEnumerations = new Dictionary <string, string>(); ObjectTypeEnumerations = new List <Dictionary <string, string> >(); var ObjectTypeEnumerations1 = new Dictionary <string, string>(); var ObjectTypeEnumerations2 = new Dictionary <string, string>(); ResourceSet ResourcesEnUS = Resource.GetResourceSet(CultureEnUS, true, true); IDictionaryEnumerator ide = ResourcesEnUS.GetEnumerator(); while (ide.MoveNext()) { if (ide.Key.ToString().Contains("commandIdEnumSet.")) { CommandEnumerations.Add(ide.Value.ToString(), ide.Key.ToString()); } else if (ide.Key.ToString().Contains("objectTypeEnumSet.")) { try { ObjectTypeEnumerations1.Add(ide.Value.ToString(), ide.Key.ToString()); } catch { ObjectTypeEnumerations2.Add(ide.Value.ToString(), ide.Key.ToString()); } } } ObjectTypeEnumerations.Add(ObjectTypeEnumerations1); ObjectTypeEnumerations.Add(ObjectTypeEnumerations2); }
///<summary> /// In case you want to use Saber's implemented language file, but use ith with your own resource file, you can use this property to set it. /// In case you've set the Language property to a custom built class, setting this property will reset it to the default Saber class. ///</summary> public static void SetCustomResource(ResourceManager resourceManager) { if (resourceManager == null) return; var newKeys = new Collection<string>(); var newResourceSet = resourceManager.GetResourceSet(CultureInfo.CurrentCulture, true, true).GetEnumerator(); while (newResourceSet.MoveNext()) newKeys.Add(newResourceSet.Key.ToString()); var resourceType = typeof(SaberRes); var properties = resourceType.GetProperties(BindingFlags.Static | (resourceType.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic)); var foundAllKeys = properties.Select(x => x.Name) .Intersect(newKeys) .Count() == (properties.Length - 2); if (!foundAllKeys) return; var resourceManagerField = resourceType.GetField("resourceMan", BindingFlags.Static | BindingFlags.NonPublic); if (resourceManagerField == null) return; resourceManagerField.SetValue(null, resourceManager); ResetLanguageInstance(); }
public void Resources_HasEquivalents() { IEnumerable<CultureInfo> languages = new[] { new CultureInfo("en-GB"), new CultureInfo("lt-LT") }; IEnumerable<Type> resourceTypes = Assembly .Load("MvcTemplate.Resources") .GetTypes() .Where(type => type.Namespace.StartsWith("MvcTemplate.Resources.")); foreach (Type type in resourceTypes) { ResourceManager manager = new ResourceManager(type); IEnumerable<String> resourceKeys = new String[0]; foreach (ResourceSet set in languages.Select(language => manager.GetResourceSet(language, true, true))) { resourceKeys = resourceKeys.Union(set.Cast<DictionaryEntry>().Select(resource => resource.Key.ToString())); resourceKeys = resourceKeys.Distinct(); } foreach (CultureInfo language in languages) { ResourceSet set = manager.GetResourceSet(language, true, true); foreach (String key in resourceKeys) Assert.True((set.GetObject(key) ?? "").ToString() != "", String.Format("{0}, does not have translation for '{1}' in {2} language.", type.FullName, key, language.EnglishName)); } } }
static void Main(string[] args) { Console.WriteLine("Extracts resources from .net .resources files or assemblies containing *.g.resources files, dumps them in the working directory."); if (args.Count() != 1) { Console.WriteLine("Usage: first argument should be a .resource file or an assembly."); return; } ResourceManager manager = null; //try{ try{ Assembly assembly = Assembly.LoadFile(args[0]); manager = new ResourceManager(assembly.GetName().Name + ".g", assembly); }catch(BadImageFormatException e){ // Ok, not an assembly. } if (manager == null){ manager = ResourceManager.CreateFileBasedResourceManager(Path.GetFileNameWithoutExtension(args[0]), Path.GetDirectoryName(args[0]), null); } //GetResourceSet() will return null unless I do a bogus fetch of a resource. I probably need to RTFM more. try{ Object hello = manager.GetObject("buttwars"); } catch (Exception) { } ResourceSet resourceset = manager.GetResourceSet(CultureInfo.InvariantCulture, false, false); foreach (DictionaryEntry resource in resourceset){ Console.WriteLine(resource.Key); if (resource.Value is UnmanagedMemoryStream) { UnmanagedMemoryStream stream = (UnmanagedMemoryStream)resource.Value; String path = (String)resource.Key; String directory = Path.GetDirectoryName(path); if(path == null) { Console.WriteLine("null?"); } if (directory != null && directory.Length != 0) { Directory.CreateDirectory(directory); } FileStream outputstream = File.Create(path); stream.CopyTo(outputstream); outputstream.Close(); } } Console.WriteLine(manager.ToString()); /*}catch(Exception e){ Console.Error.WriteLine(e.ToString()); }*/ }
public static Func<string, string> CreateResourceStringGetter( [NotNull] Assembly assembly, string baseName, CultureInfo culture) { if (assembly == null) throw new ArgumentNullException("assembly"); if (baseName != null) { var rm = new ResourceManager(baseName, assembly); var resSets = new List<ResourceSet>(); var curCulture = culture ?? CultureInfo.CurrentUICulture; do { resSets.Add(rm.GetResourceSet(curCulture, true, true)); if (curCulture.Parent == null || curCulture == curCulture.Parent) break; curCulture = curCulture.Parent; } while (true); return name => resSets .Select(rs => rs.GetString(name ?? "")) .FirstOrDefault(s => s != null); } return name => { throw new ApplicationException( "Запрошена ресурсная строка '{0}', но не указан ресурсный файл.".FormatStr(name)); }; }
public static void LoadResources(string strCulture) { try { System.Reflection.Assembly targetAsmbly = System.Reflection.Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + "PACT.Globalization.dll"); System.Reflection.Assembly satAsmbly = targetAsmbly.GetSatelliteAssembly(new CultureInfo(strCulture)); string[] resources = satAsmbly.GetManifestResourceNames(); string strName = ""; string strValue = ""; UIResources.Clear(); foreach (string resource in resources) { string baseName = resource.Substring(0, resource.LastIndexOf('.')); ResourceManager resourceManager = new ResourceManager(baseName, satAsmbly); ResourceSet resourceSet = resourceManager.GetResourceSet(CultureInfo.CurrentCulture, true, true); IDictionaryEnumerator enumerator = resourceSet.GetEnumerator(); while (enumerator.MoveNext()) { strName = enumerator.Key.ToString(); strValue = enumerator.Value.ToString(); UIResources.Add(strName, strValue); } } } catch (Exception ex) { throw new Exception(ex.Message); } }
public LocalizationExtenderProvider(ISite serviceProvider, IComponent baseComponent) { this.serviceProvider = serviceProvider; this.baseComponent = baseComponent; if (serviceProvider != null) { IExtenderProviderService service = (IExtenderProviderService) serviceProvider.GetService(typeof(IExtenderProviderService)); if (service != null) { service.AddExtenderProvider(this); } } this.language = CultureInfo.InvariantCulture; ResourceManager manager = new ResourceManager(baseComponent.GetType()); if (manager != null) { ResourceSet set = manager.GetResourceSet(this.language, true, false); if (set != null) { object obj2 = set.GetObject("$this.Localizable"); if (obj2 is bool) { this.defaultLocalizable = (bool) obj2; this.localizable = this.defaultLocalizable; } } } }
public IEnumerable<Language> GetAllLanguages() { if(!mCachedLanguageList.Any()) { // Based on http://stackoverflow.com/a/11047894/2579010 var allCultures = CultureInfo.GetCultures(CultureTypes.AllCultures); var resourceManager = new ResourceManager(typeof(Auctioneer.Resources.Shared.Layout)); foreach(var culture in allCultures) { var resourcesForThisCulture = resourceManager.GetResourceSet(culture, createIfNotExists: true, tryParents: false); if(resourcesForThisCulture != null) { var language = new Language { LangCode = !culture.Equals(CultureInfo.InvariantCulture) ? culture.TwoLetterISOLanguageName : "en", DisplayName = !culture.Equals(CultureInfo.InvariantCulture) ? culture.DisplayName : "English" }; mCachedLanguageList.Add(language); } } } return mCachedLanguageList; }
public static IEnumerable<CultureInfo> GetImplementedCultures(ResourceManager rm) { var cultures = CultureInfo.GetCultures(CultureTypes.AllCultures) .Where(i => rm.GetResourceSet(i, true, false) != null); return cultures; }
/// <summary> /// Retrieve string resource according to the string name. /// </summary> /// <param name="resourceKey">string name</param> /// <returns>the value of <c>name</c> if successful, /// <c>name</c>, otherwise. /// </returns> public string GetString(string resourceKey) { string resourceValue = ""; try { resourceValue = resourceManager.GetString(resourceKey); if (resourceValue == null) { // if the resource not exist, retrieve the default value ResourceSet resourceSet = resourceManager.GetResourceSet(new CultureInfo("en"), true, false); resourceValue = resourceSet.GetString(resourceKey); } } catch (System.Exception) { resourceValue = resourceKey; } finally { if (resourceValue == null || resourceValue == "") { resourceValue = resourceKey; } } return(resourceValue); }
// btnGetResourceList private void btnGetResourceList_onClick(object sender, RoutedEventArgs e) { Assembly assembly = Assembly.GetAssembly(this.GetType()); string resourceName = assembly.GetName().Name + ".g"; System.Resources.ResourceManager rm = new System.Resources.ResourceManager(resourceName, assembly); using (ResourceSet set = rm.GetResourceSet(System.Globalization.CultureInfo.CurrentCulture, true, true)) { StringBuilder sb = new StringBuilder(); foreach (DictionaryEntry res in set) { String str = res.Key.ToString() + "\n\r"; sb.Append(str); } Uri uri = null; if (bUriRelative == true) { uri = new Uri("/Images/Pic2.png", UriKind.Relative); } else { uri = new Uri("pack://application:,,,/Images/Pic0.png"); } bUriRelative = !bUriRelative; sb.Append(uri.ToString()); img.Source = new BitmapImage(uri); Sound.Play(); MessageBox.Show(sb.ToString(), resourceName); } }
public SwatchesProvider() { var assembly = Assembly.GetExecutingAssembly(); var resourcesName = assembly.GetName().Name + ".g"; var manager = new ResourceManager(resourcesName, assembly); var resourceSet = manager.GetResourceSet(CultureInfo.CurrentUICulture, true, true); var dictionaryEntries = resourceSet.OfType<DictionaryEntry>().ToList(); var assemblyName = assembly.GetName().Name; var regex = new Regex(@"^themes\/materialdesigncolor\.(?<name>[a-z]+)\.(?<type>primary|accent)\.baml$"); Swatches = dictionaryEntries .Select(x => new { key = x.Key.ToString(), match = regex.Match(x.Key.ToString()) }) .Where(x => x.match.Success && x.match.Groups["name"].Value != "black") .GroupBy(x => x.match.Groups["name"].Value) .Select(x => CreateSwatch ( x.Key, Read(assemblyName, x.SingleOrDefault(y => y.match.Groups["type"].Value == "primary")?.key), Read(assemblyName, x.SingleOrDefault(y => y.match.Groups["type"].Value == "accent")?.key) )) .ToList(); }
public void load_images() { List<string> resource_paths = new List<string>(); var assembly = Assembly.GetExecutingAssembly(); var buffer = new ResourceManager(assembly.GetName().Name + ".g", assembly); try { var list = buffer.GetResourceSet(CultureInfo.CurrentCulture, true, true); foreach (DictionaryEntry item in list) { resource_paths.Add((string)item.Key); } } finally { buffer.ReleaseAllResources(); } all_images = new List<photo>(); foreach (string current_path in resource_paths) { if (current_path.Contains(".jpg")) { BitmapImage another_image = new BitmapImage(new Uri(@"/" + current_path, UriKind.Relative)); all_images.Add(new photo(another_image)); } } faces_combo_box.ItemsSource = all_images; faces_combo_box.SelectedItem = faces_combo_box.Items[0]; }
public static IHtmlString IncludeResources(this HtmlHelper html) { var currentCulture = Thread.CurrentThread.CurrentUICulture; var sw = new StringWriter(); sw.WriteLine("<script>"); Assembly executingAssembly = Assembly.GetExecutingAssembly(); foreach (string resourceName in executingAssembly.GetManifestResourceNames()) { var resourceKey = resourceName.Replace(".resources", ""); var resourceManager = new ResourceManager(resourceKey, executingAssembly); var shortenedResourceName = resourceKey.Replace("OnBoard.Views.Module.", ""); var set = resourceManager.GetResourceSet(currentCulture, true, true); IDictionaryEnumerator id = set.GetEnumerator(); while (id.MoveNext()) { sw.WriteLine("resources.setResource('{0}.{1}','{2}');", shortenedResourceName, id.Key, id.Value.ToString().Replace("'", "\\'")); } } sw.WriteLine("</script>"); return new HtmlString(sw.ToString()); }
public void Resources_HasAllTranslations() { IEnumerable<Language> languages = GlobalizationProviderFactory.CreateProvider().Languages; IEnumerable<Type> resourceTypes = Assembly .Load("MvcTemplate.Resources") .GetTypes() .Where(type => type.Namespace.StartsWith("MvcTemplate.Resources.")); foreach (Type type in resourceTypes) { ResourceManager manager = new ResourceManager(type); IEnumerable<String> resourceKeys = new String[0]; foreach (Language language in languages) { ResourceSet set = manager.GetResourceSet(language.Culture, true, true); resourceKeys = resourceKeys.Union(set.Cast<DictionaryEntry>().Select(resource => resource.Key.ToString())); resourceKeys = resourceKeys.Distinct(); } foreach (Language language in languages) { ResourceSet set = manager.GetResourceSet(language.Culture, true, true); foreach (String key in resourceKeys) Assert.True(!String.IsNullOrEmpty(set.GetString(key)), String.Format("{0}, does not have translation for '{1}' in {2} language.", type.FullName, key, language.Culture.EnglishName)); } } }
public ActionResult GetResourcesJavaScript(string resxFileName) { ResourceManager resourceManager = null; switch (resxFileName.ToLower()) { case "globalsresource": { resourceManager = new ResourceManager("ControleFinanceiro.CORE.Resources.GlobalsResource", typeof(GlobalsResource).Assembly); break; } case "labelsresource": { resourceManager = new ResourceManager("ControleFinanceiro.CORE.Resources.LabelsResource", typeof(LabelsResource).Assembly); break; } case "messagesresource": { resourceManager = new ResourceManager("ControleFinanceiro.CORE.Resources.MessagesResource", typeof(MessagesResource).Assembly); break; } } if(resourceManager != null) { var resourceSet = resourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true); var resourceDictionary = resourceSet.Cast<DictionaryEntry>() .ToDictionary(entry => entry.Key.ToString(), entry => entry.Value.ToString()); var json = Serializer.Serialize(resourceDictionary); var javaScript = string.Format("window.Resources = window.Resources || {{}}; window.Resources.{0} = {1};", resxFileName, json); return JavaScript(javaScript); } return JavaScript(""); }
public ResxTranslationProvider(ResourceManager resourceManager) { _resourceManager = resourceManager; _languages = CultureInfo.GetCultures(CultureTypes.AllCultures) .Where(x => x.TwoLetterISOLanguageName != "iv" && _resourceManager.GetResourceSet(x, true, false) != null) .ToList(); }
static void ReadHtmlFiles(ResourceManager resourceManager) { var rs = resourceManager.GetResourceSet(CultureInfo.CurrentCulture, true, true); var it = rs.GetEnumerator(); while (it.MoveNext()) TestHtml(it.Value.ToString(), it.Key.ToString()); }
private static IEnumerable<string> AllResourcesIn(ResourceManager manager) { var resSet = manager.GetResourceSet( CultureInfo.CurrentCulture, true, true); return resSet.Cast<DictionaryEntry>() .Select(x => x.Key) .Cast<string>(); }
public OptionsForm() { InitializeComponent(); lbl_version.Text = string.Format( Language.FrmOptions_By_Soroush_Falahati_v, Assembly.GetEntryAssembly().GetName().Version.ToString(2)); cb_lang.Items.Add( new ComboBoxItem("Windows Default - " + Thread.CurrentThread.CurrentCulture.DisplayName) { Tag = string.Empty }); cb_lang.SelectedIndex = 0; var resourceManager = new ResourceManager(typeof (NVidiaLocalization)); foreach (var culture in CultureInfo.GetCultures(CultureTypes.AllCultures)) { try { if (!string.IsNullOrWhiteSpace(culture.Name)) { var rs = resourceManager.GetResourceSet(culture, true, false); if (rs != null) { cb_lang.Items.Add(new ComboBoxItem(culture.DisplayName) {Tag = culture.Name}); rs.Close(); rs.Dispose(); } } } catch { // ignored } } if (!string.IsNullOrWhiteSpace(Settings.Default.ControlPanelLanguage)) { var selectedLanguage = cb_lang.SelectedItem = cb_lang.Items.Cast<ComboBoxItem>() .FirstOrDefault( item => Settings.Default.ControlPanelLanguage.Equals(item.Tag as string, StringComparison.CurrentCultureIgnoreCase)); if (selectedLanguage == null) { selectedLanguage = new ComboBoxItem(Settings.Default.ControlPanelLanguage) { Tag = Settings.Default.ControlPanelLanguage }; cb_lang.Items.Add(selectedLanguage); } cb_lang.SelectedItem = selectedLanguage; } cb_lang.SelectedIndexChanged += LanguageIndexChanged; RefreshButtons(); }
public static IEnumerable<CultureInfo> GetAvailableTranslations(ResourceManager rm) { var cultures = CultureInfo.GetCultures(CultureTypes.AllCultures); foreach (var culture in cultures) { ResourceSet rs = rm.GetResourceSet(culture, true, false); if (rs == null || culture.LCID == CultureInfo.InvariantCulture.LCID || culture.Parent.LCID != CultureInfo.InvariantCulture.LCID) continue; yield return culture; } }
private static IEnumerable<CultureInfo> GetCulturesFromResourceFile(Type resourceFile) { var rm = new ResourceManager(resourceFile); var cultures = CultureInfo.GetCultures(CultureTypes.AllCultures) .Where(c => { if (c.IsSameCultureAs(CultureInfo.InvariantCulture)) { return false; } return rm.GetResourceSet(c, createIfNotExists: true, tryParents: false) != null; }).ToList(); return cultures; }
public static void Initialize() { rm = new ResourceManager("Nada.Globalization.Translations", typeof(GlobalizationUtil).Assembly); keys = new List<string>(); initializedCulture = CultureInfo.CurrentCulture; ResourceSet set = rm.GetResourceSet(CultureInfo.CurrentCulture, true, true); foreach (DictionaryEntry o in set) { keys.Add((string)o.Key); } }
/// <summary> /// Creates dictionary with key value pairs from resources in resourceManager. /// </summary> /// <param name="culture">The culture.</param> /// <param name="resourceManager">The resource manager.</param> /// <returns>Dictionary with all resource keys and values</returns> private static Dictionary<string, string> CreateDictionaryFromResourceSet(CultureInfo culture, ResourceManager resourceManager) { var result = new Dictionary<string, string>(); var resources = resourceManager.GetResourceSet(culture, true, true).GetEnumerator(); while (resources.MoveNext()) { if (resources.Key is string && resources.Value is string) { result.Add((string)resources.Key, (string)resources.Value); } } return result; }
private static string TransformResx(string fileName, CultureInfo culture) { fileName = fileName.Replace(".resx", string.Empty).Trim(); var rm = new ResourceManager("CGN.Paralegal.UI.App.resources." + fileName, Assembly.GetExecutingAssembly()); var resourceSet = rm.GetResourceSet(culture, true, true); const string Output = "var {0}Resources = {{ {1} }}; \r\n\r\n"; //note: double curly braces are escaped... var sb = new StringBuilder(); foreach (DictionaryEntry entry in resourceSet) { sb.Append(entry.Key + ":\"" + entry.Value + "\",\r\n"); } return string.Format(CultureInfo.InvariantCulture, Output, fileName, sb.Remove(sb.Length - 3, 3)); }
static void Main(string[] args) { if (args == null || args.Length == 0) { return;//args = new string[] { @"C:\Users\samuel grahame\Source\Repos\ClassicForms.Showcase3\ClassicForms.Showcase3.UI\bin\Debug\ClassicForms.Showcase3.UI.dll" }; } var assmbly = Assembly.LoadFile(args.FirstOrDefault().Trim()); var startingPath = ""; if (args.Length == 2) { startingPath = args[1]; } if (!System.IO.Directory.Exists(startingPath + "Resources")) { System.IO.Directory.CreateDirectory(startingPath + "Resources"); } try { var fullName = assmbly.GetName().Name + ".Properties.Resources"; var globalResourceManager = new System.Resources.ResourceManager(fullName, assmbly); CreateBin(startingPath, globalResourceManager.GetResourceSet(CultureInfo.CurrentCulture, true, true), fullName); } catch (Exception) { } var types = assmbly.GetTypes().Where(o => o.BaseType == typeof(Form)); if (types == null) { return; } foreach (var item in types) { try { var rm = new ResourceManager(item); CreateBin(startingPath, rm.GetResourceSet(CultureInfo.CurrentCulture, true, true), item.FullName); } catch (Exception) { } } }
private void winter2_Click(object sender, RoutedEventArgs e) { Assembly assembly = Assembly.GetAssembly(this.GetType()); string resourceName = assembly.GetName().Name + ".g"; ResourceManager rm = new ResourceManager(resourceName, assembly); using(ResourceSet set = rm.GetResourceSet(CultureInfo.CurrentCulture, true, true)) { UnmanagedMemoryStream s; s = (UnmanagedMemoryStream) set.GetObject("images/winter.png", true); } }
private static void LoadCultures() { var resourceManager = new ResourceManager(typeof(Properties.Resources)); var cultures = CultureInfo.GetCultures(CultureTypes.AllCultures); var supportedCultures = new List<CultureInfo>(cultures.Length - 1); for (var i = cultures.Length - 1; i >= 0; i--) { var culture = cultures[i]; if (Equals(culture, Utilities.InvariantCulture)) continue; if (resourceManager.GetResourceSet(culture, true, false) != null) { supportedCultures.Add(culture); } } supportedCultures = supportedCultures.OrderBy(x => x.ThreeLetterWindowsLanguageName).ToList(); supportedCultures.Insert(0, Utilities.InvariantCulture); SupportedLanguageCultures = supportedCultures; var supportedStrings = new string[supportedCultures.Count]; for (var i = supportedCultures.Count - 1; i > 0; i--) { var culture = supportedCultures[i]; var nativeName = culture.NativeName.UppercaseFirst(); var displayName = culture.EnglishName.UppercaseFirst(); var bracketIndex = nativeName.IndexOf('('); if (bracketIndex >= 0) { nativeName = nativeName.Substring(0, bracketIndex - 1); } bracketIndex = displayName.IndexOf('('); if (bracketIndex >= 0) { displayName = displayName.Substring(0, bracketIndex - 1); } var stringFormat = nativeName != displayName ? "{0} {1} ({2})" : "{0} {1}"; supportedStrings[i] = string.Format( Utilities.InvariantCulture, stringFormat, culture.ThreeLetterWindowsLanguageName, nativeName, displayName ); } SupportedLanguageStrings = supportedStrings; if (SupportedLanguagesLoaded != null) SupportedLanguagesLoaded(null, EventArgs.Empty); }
public static Dictionary <string, string> ConvertActorLabelType() { Dictionary <string, string> labelTypes = new Dictionary <string, string>(); System.Resources.ResourceManager resourceManager = new System.Resources.ResourceManager(typeof(Resources.ActorLabelType)); ResourceSet resourceSet = resourceManager.GetResourceSet(CultureInfo.CurrentCulture, true, true); IDictionaryEnumerator id = resourceSet.GetEnumerator(); while (id.MoveNext()) { labelTypes.Add(id.Key.ToString(), id.Value.ToString()); } resourceSet.Close(); return(labelTypes); }
static ResourceManager LoadLanguage(CultureInfo culture, ref ResourceSet rs) { Current = culture; if (rs != null) { rs.Dispose(); rs = null; } try { ResourceManager rManager = new ResourceManager("XPloit.Res.Res", typeof(Lang).Assembly) { IgnoreCase = true }; rs = rManager.GetResourceSet(culture, true, true); return rManager; } catch { } return null; }
public void Init() { string resourceName = Assembly.GetExecutingAssembly().GetName().Name + ".g"; var rm = new ResourceManager(resourceName, Assembly.GetExecutingAssembly()); using (ResourceSet set = rm.GetResourceSet(CultureInfo.CurrentCulture, true, true)) { using (UnmanagedMemoryStream sri = (UnmanagedMemoryStream)set.GetObject("config/Tools.config", true)) { using (StreamReader streamReader = new StreamReader(sri)) { string xmlDoc = streamReader.ReadToEnd(); m_Config = XmlUtility.DeserializeFromXml<ToolsConfig>(xmlDoc, null); } } } }
// Получение всех ресурсов. private void buttonGetAllResources_Click(object sender, RoutedEventArgs e) { Assembly assembly = Assembly.GetAssembly(this.GetType()); string resourceName = assembly.GetName().Name + ".g"; // Позволяет получить доступ к ресурсу (на основе культуры) на этапе выполнения. ResourceManager rm = new ResourceManager(resourceName, assembly); using (ResourceSet set = rm.GetResourceSet(CultureInfo.CurrentCulture, true, true)) { string result = string.Empty; foreach (DictionaryEntry item in set) { result += item.Key.ToString() + Environment.NewLine; } MessageBox.Show(result); } }
public static IEnumerable<CultureInfo> GetAvailableTranslations(ResourceManager rm) { var cultures = CultureInfo.GetCultures(CultureTypes.AllCultures); foreach (var culture in cultures) { // This is the source language, which is only returned below in some versions of the .NET framework if (culture.Name == "en") { yield return culture; continue; } ResourceSet rs = rm.GetResourceSet(culture, true, false); if (rs == null || culture.LCID == CultureInfo.InvariantCulture.LCID || culture.Parent.LCID != CultureInfo.InvariantCulture.LCID) continue; yield return culture; } }
public override byte[] GetContent(Assembly assembly) { var result = new Dictionary<string, string>(); var resourceManager = new ResourceManager(baseName, assembly); using (var resourceSet = resourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true)) { foreach (DictionaryEntry entry in resourceSet) { var key = entry.Key.ToString(); result.Add(key, resourceManager.GetString(key)); } } var json = result.ToJson(); return Encoding.UTF8.GetBytes(json); }
/// <summary> /// Opens the resource with the requested URI. /// </summary> /// <param name="uri">The URI.</param> /// <returns>A stream containing the resource contents.</returns> /// <exception cref="FileNotFoundException"> /// The resource was not found. /// </exception> public Stream Open(Uri uri) { var assembly = Assembly.GetEntryAssembly(); var resourceName = assembly.GetName().Name + ".g"; var manager = new ResourceManager(resourceName, assembly); using (var resourceSet = manager.GetResourceSet(CultureInfo.CurrentCulture, true, true)) { var stream = (Stream)resourceSet.GetObject(uri.ToString(), true); if (stream == null) { throw new FileNotFoundException($"The requested asset could not be found: {uri}"); } return stream; } }