public bool ExportJavaScriptResources(string path, string baseVarname = "resources") { var man = DbResourceDataManager.CreateDbResourceDataManager(); var resourceSets = man.GetAllResourceSets(ResourceListingTypes.GlobalResourcesOnly); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } foreach (var resSet in resourceSets) { var locales = man.GetAllLocaleIds(resSet); foreach (var locale in locales) { var resourceSet = man.GetResourceSetNormalizedForLocaleId(locale, resSet); string js = SerializeResourceDictionary(resourceSet, baseVarname + "." + resSet, locale); var filePath = Path.Combine(path, SafeVarName(resSet)) + (string.IsNullOrEmpty(locale) ? "" : "." + locale) + ".js"; File.WriteAllText(filePath, js); } } return(true); }
/// <summary> /// API Controller that handles API service requests from the /// Localization Admin form. /// </summary> /// <param name="host"></param> /// <param name="config"></param> public LocalizationAdministrationController(IWebHostEnvironment host, DbResourceConfiguration config) { Host = host; Config = config; DbIRes = new DbResInstance(config); Manager = DbResourceDataManager.CreateDbResourceDataManager(config.DbResourceDataManagerType); }
public void GetDbResourcesTest() { DbResourceDataManager manager = new DbResourceDataManager(); Dictionary <string, object> items = manager.GetResourceSetNormalizedForLocaleId("de-de", "resources"); WriteResourceDictionary(items, "DB Resources"); }
/// <summary> /// Creates strongly typed classes from all global resources in the current application /// from the active DbResourceManager. One class is created which contains each of the /// resource classes. Classnames are not necessarily named with /// /// Uses the default DbResourceConfiguration.Current settings for connecting /// to the database. /// </summary> /// <param name="Namespace">Optional namespace for the generated file</param> /// <param name="FileName">Output class file. .cs or .vb determines code language</param> /// <returns>Generated class as a string</returns> public string CreateClassFromAllDatabaseResources(string Namespace, string FileName, IEnumerable <string> resourceSets = null) { var man = DbResourceDataManager.CreateDbResourceDataManager(); var resources = man.GetAllResourceSets(ResourceListingTypes.GlobalResourcesOnly); if (resourceSets != null) { if (resourceSets != null) { resources = resources.Where(rs => resourceSets.Any(rs1 => rs1 == rs)) .ToList(); } } StringBuilder sbClasses = new StringBuilder(); foreach (var resourceSet in resources) { string Class = CreateClassFromDatabaseResource(resourceSet, Namespace, resourceSet, null); sbClasses.Append(Class); } string Output = CreateNameSpaceWrapper(Namespace, IsVb, sbClasses.ToString(), true); File.WriteAllText(FileName, Output); return(Output); }
/// <summary> /// The main method to retrieve a specific resource key. The provider /// internally handles resource fallback based on the ResourceSet implementation. /// </summary> /// <param name="resourceKey"></param> /// <param name="culture"></param> /// <returns></returns> object IResourceProvider.GetObject(string resourceKey, CultureInfo culture) { object value = ResourceManager.GetObject(resourceKey, culture); // If the value is still null and we're at the invariant culture // let's add a marker that the value is missing // this also allows the pre-compiler to work and never return null if (value == null && (culture == null || culture == CultureInfo.InvariantCulture)) { // No entry there value = resourceKey; if (DbResourceConfiguration.Current.AddMissingResources) { lock (_SyncLock) { value = ResourceManager.GetObject(resourceKey, culture); if (value == null) { // Add invariant resource DbResourceDataManager data = new DbResourceDataManager(); if (!data.ResourceExists(resourceKey, "", _className)) { data.AddResource(resourceKey, resourceKey, "", _className, null); } value = resourceKey; } } } } return(value); }
public JsonResult SaveResource(string path, string key, string culture, string data) { try { var c = String.IsNullOrEmpty(culture) ? CultureInfo.InvariantCulture : CultureInfo.GetCultureInfo(culture); culture = c.TwoLetterISOLanguageName; c = new CultureInfo(culture); // remove unwanted para elements if (data.StartsWith("<p>") && data.EndsWith("</p>")) { data = data.Substring(3, data.Length - 7); } DbResourceDataManager.UpdateOrAdd(key, data, c, path); // UNDO Stack q; if (Session[String.Format("Undo_{0}_{1}_{2}", path, key, culture)] == null) { q = new Stack(); q.Push(data); } else { q = (Stack)Session[String.Format("Undo_{0}_{1}_{2}", path, key, culture)]; q.Push(data); } Session[String.Format("Undo_{0}_{1}_{2}", path, key, culture)] = q; return(Json(new { msg = "OK (" + culture + ")", data })); // 0 (added) or 1 (updated) } catch (Exception ex) { return(Json(new { msg = ex.Message, data })); // 0 (added) or 1 (updated) } }
public Dictionary <string, string> GetResourcesForId(string resourceID, string resourceSet) { var manager = DbResourceDataManager.CreateDbResourceDataManager(); var resourceStrings = manager.GetResourceStrings(resourceID, resourceSet); return(resourceStrings); }
/// <summary> /// Creates strongly typed classes from all global resources in the current application /// from the active DbResourceManager. One class is created which contains each of the /// resource classes. Classnames are not necessarily named with /// /// Uses the default DbResourceConfiguration.Current settings for connecting /// to the database. /// </summary> /// <param name="ns">Optional namespace for the generated file</param> /// <param name="fileName">Output class file. .cs or .vb determines code language</param> /// <returns>Generated class as a string</returns> public string CreateResxDesignerClassesFromAllDatabaseResources(string ns, string outputPath, IEnumerable <string> resourceSets = null) { var man = DbResourceDataManager.CreateDbResourceDataManager(); var resources = man.GetAllResourceSets(ResourceListingTypes.GlobalResourcesOnly); if (resourceSets != null) { if (resourceSets != null) { resources = resources.Where(rs => resourceSets.Any(rs1 => rs1 == rs)) .ToList(); } } string classCode = null; StringBuilder sbClasses = new StringBuilder(); foreach (var resourceSet in resources) { classCode = CreateResxDesignerClassFromResourceSet(resourceSet, ns, resourceSet, null); StringBuilder sb = new StringBuilder(classCode); classCode = CreateResxDesignerNameSpaceWrapper(ns, IsVb, sb.ToString()); string outputFile = Path.Combine(outputPath, resourceSet + ".designer." + (IsVb ? "vb" : "cs")); File.WriteAllText(outputFile, classCode); } return(classCode); }
/// <summary> /// Generates the Database resources for a given form /// </summary> /// <param name="ParentControl"></param> /// <param name="ResourcePrefix"></param> public void AddResourceToResourceFile(Control ParentControl, string ResourcePrefix, string ResourceSet) { if (ResourcePrefix == null) { ResourcePrefix = "Resource1"; } if (ResourceSet == null) { ResourceSet = this.Context.Request.ApplicationPath + this.Parent.TemplateControl.AppRelativeVirtualPath.Replace("~", ""); } var Data = DbResourceDataManager.CreateDbResourceDataManager(); List <LocalizableProperty> ResourceList = this.GetAllLocalizableControls(ParentControl); foreach (LocalizableProperty Resource in ResourceList) { string ResourceKey = Resource.ControlId + ResourcePrefix + "." + Resource.Property; if (!Data.ResourceExists(ResourceKey, "", ResourceSet)) { Data.AddResource(ResourceKey, Resource.Value, "", ResourceSet, null); } } }
/// <summary> /// Writes all resources out to the resource store. Optional flag that /// allows deleting all resources for a given culture and basename first /// so that you get 'clean set' of resource with no orphaned values. /// </summary> /// <param name="DeleteAllRowsFirst"></param> public void Generate(bool DeleteAllRowsFirst) { // DEPENDENCY HERE var data = DbResourceDataManager.CreateDbResourceDataManager(); data.GenerateResources(resourceList, cultureInfo.Name, baseName, DeleteAllRowsFirst); }
/// <summary> /// Writes all resources out to the resource store. Optional flag that /// allows deleting all resources for a given culture and basename first /// so that you get 'clean set' of resource with no orphaned values. /// </summary> /// <param name="DeleteAllRowsFirst"></param> public void Generate(bool DeleteAllRowsFirst) { // DEPENDENCY HERE DbResourceDataManager Data = new DbResourceDataManager(); Data.GenerateResources(resourceList, this.cultureInfo.Name, this.baseName, DeleteAllRowsFirst); }
public void GetDbResourcesTest() { DbResourceDataManager manager = new DbResourceDataManager(); Dictionary<string,object> items = manager.GetResourceSetNormalizedForLocaleId("de-de", "resources"); WriteResourceDictionary(items, "DB Resources"); }
public void GetDbResourcesTest() { // create manager based on configuration var manager = DbResourceDataManager.CreateDbResourceDataManager(configuration); Dictionary <string, object> items = manager.GetResourceSetNormalizedForLocaleId("de-de", "Resources"); WriteResourceDictionary(items, "DB Resources"); }
private void Load() { // RAS Modified: Read the full page path ie. /internationalization/test.aspx string resourceSet = GetFullPagePath(); // Load IDictionary data using the DataManager (same code as provider) var manager = DbResourceDataManager.CreateDbResourceDataManager(); _reader = manager.GetResourceSet("", resourceSet); }
private static void AddResourceToStore(string key, object value, string resourceSet, IServiceProvider serviceProvider) { // Use custom data manager to write the values into the database var manager = DbResourceDataManager.CreateDbResourceDataManager(); if (manager.UpdateOrAddResource(key, value, "", resourceSet, null) == -1) { throw new InvalidOperationException("Resource update error: " + manager.ErrorMessage); } }
public bool UploadResource() { if (Request.Form.Files.Count < 1) { return(false); } var file = Request.Form.Files[0]; var resourceId = Request.Form["ResourceId"]; var resourceSet = Request.Form["ResourceSet"]; var localeId = Request.Form["LocaleId"]; if (string.IsNullOrEmpty(resourceId) || string.IsNullOrEmpty(resourceSet)) { throw new ApplicationException("Resourceset or ResourceId are not provided for upload."); } var item = Manager.GetResourceItem(resourceId, resourceSet, localeId); if (item == null) { item = new ResourceItem() { ResourceId = resourceId, ResourceSet = resourceSet, LocaleId = localeId, ValueType = (int)ValueTypes.Binary }; } using (var fs = file.OpenReadStream()) using (var ms = new MemoryStream()) { fs.CopyTo(ms); ms.Flush(); if (DbResourceDataManager.SetFileDataOnResourceItem(item, ms.ToArray(), file.FileName) == null) { return(false); } int res = Manager.UpdateOrAddResource(item); if (res < 0) { return(false); } } return(true); }
/// <summary> /// Writes a resource either creating or updating an existing resource /// </summary> /// <param name="resourceId">Resource Id to write. Resource Ids can be any string up to 1024 bytes in length</param> /// <param name="value">Value to set the resource to</param> /// <param name="lang">Language as ieetf code: en-US, de-DE etc. /// Value can be left blank for Invariant/Default culture to set. /// </param> /// <param name="resourceSet">The resourceSet to store the resource on. /// If no resource set name is provided a default empty resource set is used.</param> /// <returns>true or false</returns> public static bool WriteResource(string resourceId, string value = null, string lang = null, string resourceSet = null) { if (lang == null) lang = string.Empty; if (resourceSet == null) resourceSet = string.Empty; if (value == null) value = resourceId; var db = DbResourceDataManager.CreateDbResourceDataManager(); return db.UpdateOrAddResource(resourceId, value, lang, resourceSet, null) > -1; }
/// <summary> /// 2020.08.28 paulus: /// 預設 ResouceSet = "General", ResourceId = "logon" /// Invariant = en, plus other supported locales /// </summary> /// <returns>Dictionary = locale id, locale native name</locale></returns> public static Dictionary <string, string> GetLocaleList() { Dictionary <string, string> result = new Dictionary <string, string>(); var mgr = DbResourceDataManager.CreateDbResourceDataManager(); var list = mgr.GetResourceStrings("logon", "General", true); foreach (var item in list) { var localeId = (item.Key == String.Empty) ? "en" : item.Key; var cultureInfo = new CultureInfo(localeId); result.Add(localeId, cultureInfo.NativeName); } return(result); }
public ContentResult ResourceSummary(string view) { var cc = new CultureInfo(CurrentCulture); var cp = new CultureInfo(CurrentCulture).Parent; var ci = CultureInfo.InvariantCulture; var resourceCulture = DbResourceDataManager.GetResourceSet(cc, view); var resourceNeutral = DbResourceDataManager.GetResourceSet(cp, view); var resourceInvariant = DbResourceDataManager.GetResourceSet(ci, view); return(Content(String.Format(@"<ul><li>{3} = {0}</li><li>{4} = {1}</li><li>{5} = {2}</li>", resourceCulture.Count, resourceNeutral.Count, resourceInvariant.Count, cc.TwoLetterISOLanguageName, cp.TwoLetterISOLanguageName, "INV"))); }
protected void btnFileUpload_Click(object sender, EventArgs e) { #if OnlineDemo this.ErrorDisplay.ShowError(WebUtils.LRes("FeatureDisabled")); return; #endif if (!FileUpload.HasFile) { return; } //FileInfo fi = new FileInfo(this.FileUpload.FileName); string Extension = Path.GetExtension(FileUpload.FileName).TrimStart('.'); // fi.Extension.TrimStart('.'); string Filter = ",bmp,ico,gif,jpg,png,css,js,txt,wav,mp3,"; if (Filter.IndexOf("," + Extension + ",") == -1) { ErrorDisplay.ShowError(WebUtils.LRes("InvalidFileUploaded")); return; } string FilePath = Server.MapPath(FileUpload.FileName); File.WriteAllBytes(FilePath, FileUpload.FileBytes); string ResourceId = txtNewResourceId.Text; // *** Try to add the file DbResourceDataManager Data = new DbResourceDataManager(); if (Data.UpdateOrAdd(ResourceId, FilePath, txtNewLanguage.Text, ResourceSet, null, true) == -1) { ErrorDisplay.ShowError(WebUtils.LRes("ResourceUpdateFailed") + "<br/>" + Data.ErrorMessage); } else { ErrorDisplay.ShowMessage(WebUtils.LRes("ResourceUpdated")); } File.Delete(FilePath); lstResourceIds.Items.Add(ResourceId); lstResourceIds.SelectedValue = ResourceId; }
/// <summary> /// Writes a resource either creating or updating an existing resource /// </summary> /// <param name="resourceId">Resource Id to write. Resource Ids can be any string up to 1024 bytes in length</param> /// <param name="value">Value to set the resource to</param> /// <param name="lang">Language as ieetf code: en-US, de-DE etc. /// Value can be left blank for Invariant/Default culture to set. /// </param> /// <param name="resourceSet">The resourceSet to store the resource on. /// If no resource set name is provided a default empty resource set is used.</param> /// <returns>true or false</returns> public static bool WriteResource(string resourceId, string value = null, string lang = null, string resourceSet = null) { if (lang == null) { lang = string.Empty; } if (resourceSet == null) { resourceSet = string.Empty; } if (value == null) { value = resourceId; } var db = new DbResourceDataManager(); return(db.UpdateOrAdd(resourceId, value, lang, resourceSet, null) > -1); }
/// <summary> /// Manages caching of the Resource Sets. Once loaded the values are loaded from the /// cache only. /// </summary> /// <param name="cultureName"></param> /// <returns></returns> private IDictionary GetResourceCache(string cultureName) { if (cultureName == null) { cultureName = ""; } if (_resourceCache == null) { _resourceCache = new ListDictionary(); } IDictionary Resources = _resourceCache[cultureName] as IDictionary; if (Resources == null) { // DEPENDENCY HERE (#1): Using DbResourceDataManager to retrieve resources // Use datamanager to retrieve the resource keys from the database DbResourceDataManager Data = new DbResourceDataManager(); lock (_SyncLock) { if (Resources == null) { if (_resourceCache.Contains(cultureName)) { Resources = _resourceCache[cultureName] as IDictionary; } else { Resources = Data.GetResourceSet(cultureName as string, _ResourceSetName); } _resourceCache[cultureName] = Resources; } } } return(Resources); }
/// <summary> /// Creates strongly typed classes from all global resources in the current application /// from the active DbResourceManager. One class is created which contains each of the /// resource classes. Classnames are not necessarily named with /// /// Uses the default DbResourceConfiguration.Current settings for connecting /// to the database. /// </summary> /// <param name="Namespace">Optional namespace for the generated file</param> /// <param name="FileName">Output class file. .cs or .vb determines code language</param> /// <returns>Generated class as a string</returns> public string CreateClassFromAllDatabaseResources(string Namespace, string FileName) { bool IsVb = IsFileVb(FileName); var man = DbResourceDataManager.CreateDbResourceDataManager(); var resources = man.GetAllResourceSets(ResourceListingTypes.GlobalResourcesOnly); StringBuilder sbClasses = new StringBuilder(); foreach (var resourceSet in resources) { string Class = CreateClassFromDatabaseResource(resourceSet, Namespace, resourceSet, null); sbClasses.Append(Class); } string Output = CreateNameSpaceWrapper(Namespace, IsVb, sbClasses.ToString()); File.WriteAllText(FileName, Output); return(Output); }
/// <summary> /// Creates strongly typed classes from all global resources in the current application /// from the active DbResourceManager. One class is created which contains each of the /// resource classes. Classnames are not necessarily named with /// /// Uses the default DbResourceConfiguration.Current settings for connecting /// to the database. /// </summary> /// <param name="Namespace">Optional namespace for the generated file</param> /// <param name="FileName">Output class file. .cs or .vb determines code language</param> /// <returns>Generated class as a string</returns> public string CreateClassFromAllDatabaseResources(string Namespace, string FileName) { bool IsVb = IsFileVb(FileName); DbResourceDataManager man = new DbResourceDataManager(); DataTable Resources = man.GetAllResourceSets(ResourceListingTypes.GlobalResourcesOnly); StringBuilder sbClasses = new StringBuilder(); foreach (DataRow row in Resources.Rows) { string ResourceSet = row["resourceset"] as string; string Class = CreateClassFromDatabaseResource(ResourceSet, null, ResourceSet, null); sbClasses.Append(Class); } string Output = CreateNameSpaceWrapper(Namespace, IsVb, sbClasses.ToString()); File.WriteAllText(FileName, Output); return(Output); }
/// <summary> /// This is the worker method responsible for actually retrieving resources from the resource /// store. This method goes out queries the database by asking for a specific ResourceSet and /// Culture and it returns a Hashtable (as IEnumerable) to use as a ResourceSet. /// /// The ResourceSet manages access to resources via IEnumerable access which is ultimately used /// to return resources to the front end. /// /// Resources are read once and cached into an internal Items field. A ResourceReader instance /// is specific to a ResourceSet and Culture combination so there should never be a need to /// reload this data, except when explicitly clearing the reader/resourceset (in which case /// Items can be set to null via ClearResources()). /// </summary> /// <returns>An IDictionaryEnumerator of the resources for this reader</returns> public IDictionaryEnumerator GetEnumerator() { if (Items != null) { return(Items.GetEnumerator()); } lock (_SyncLock) { // Check again to ensure we still don't have items if (Items != null) { return(Items.GetEnumerator()); } // DEPENDENCY HERE // Here's the only place we really access the database and return // a specific ResourceSet for a given ResourceSet Id and Culture DbResourceDataManager Manager = new DbResourceDataManager(); Items = Manager.GetResourceSet(cultureInfo.Name, baseNameField); return(Items.GetEnumerator()); } }
/// <summary> /// Add a new resource to the base resource set /// </summary> /// <param name="name"></param> /// <param name="value"></param> public void AddMissingResource(string name, string value, CultureInfo culture = null) { var manager = DbResourceDataManager.CreateDbResourceDataManager(); string cultureName = string.Empty; if (culture != null) { cultureName = culture.IetfLanguageTag; } lock (AddSyncLock) { // double check if culture neutral version exists string item = manager.GetResourceObject(name, ResourceSetName, cultureName) as string; if (item != null) { return; } manager.AddResource(name, value, cultureName, ResourceSetName, null); } }
/// <summary> /// This is the worker method responsible for actually retrieving resources from the resource /// store. This method goes out queries the database by asking for a specific ResourceSet and /// Culture and it returns a Hashtable (as IEnumerable) to use as a ResourceSet. /// /// The ResourceSet manages access to resources via IEnumerable access which is ultimately used /// to return resources to the front end. /// /// Resources are read once and cached into an internal Items field. A ResourceReader instance /// is specific to a ResourceSet and Culture combination so there should never be a need to /// reload this data, except when explicitly clearing the reader/resourceset (in which case /// Items can be set to null via ClearResources()). /// </summary> /// <returns>An IDictionaryEnumerator of the resources for this reader</returns> public IDictionaryEnumerator GetEnumerator() { if (Items != null) { return(Items.GetEnumerator()); } lock (_SyncLock) { // Check again to ensure we still don't have items if (Items != null) { return(Items.GetEnumerator()); } // PLACEHOLDER: DEPENDENCY HERE // Here's the only place we really access the database and return // a specific ResourceSet for a given ResourceSet Id and Culture DbResourceDataManager manager = DbResourceDataManager.CreateDbResourceDataManager(configuration: Configuration); Items = manager.GetResourceSet(cultureInfo.Name, resourceSetName); return(Items.GetEnumerator()); } }
/// <summary> /// Deletes a resource entry /// </summary> /// <param name="resourceId">The resource to delete</param> /// <param name="lang">The language Id - Be careful: If empty or null deletes matching keys for all languages</param> /// <param name="resourceSet">The resource set to apply</param> /// <returns>true or false</returns> public bool DeleteResource(string resourceId, string resourceSet = null, string lang = null) { var db = DbResourceDataManager.CreateDbResourceDataManager(); return(db.DeleteResource(resourceId, resourceSet: resourceSet, cultureName: lang)); }
/// <summary> /// Imports an individual ResX Resource file into the database /// </summary> /// <param name="FileName">Full path to the the ResX file</param> /// <param name="ResourceSetName">Name of the file or for local resources the app relative path plus filename (admin/default.aspx or default.aspx)</param> /// <param name="LocaleId">Locale Id of the file to import. Use "" for Invariant</param> /// <returns></returns> public bool ImportResourceFile(string FileName, string ResourceSetName, string LocaleId) { string FilePath = Path.GetDirectoryName(FileName) + "\\"; var Data = DbResourceDataManager.CreateDbResourceDataManager(); XmlDocument dom = new XmlDocument(); try { dom.Load(FileName); } catch (Exception ex) { ErrorMessage = ex.Message; return(false); } XmlNodeList nodes = dom.DocumentElement.SelectNodes("data"); foreach (XmlNode Node in nodes) { string Value; // = Node.ChildNodes[0].InnerText; XmlNodeList valueNodes = Node.SelectNodes("value"); if (valueNodes.Count == 1) { Value = valueNodes[0].InnerText; } else { Value = Node.InnerText; } string Name = Node.Attributes["name"].Value; string Type = null; if (Node.Attributes["type"] != null) { Type = Node.Attributes["type"].Value; } string Comment = null; XmlNode commentNode = Node.SelectSingleNode("comment"); if (commentNode != null) { Comment = commentNode.InnerText; } if (string.IsNullOrEmpty(Type)) { if (Data.UpdateOrAddResource(Name, Value, LocaleId, ResourceSetName, Comment) == -1) { ErrorMessage = Data.ErrorMessage; return(false); } else { // File based resources are formatted: filename;full type name string[] tokens = Value.Split(';'); if (tokens.Length > 0) { string ResFileName = FilePath + tokens[0]; if (File.Exists(ResFileName)) { // DataManager knows about file resources and can figure type info if (Data.UpdateOrAddResource(Name, ResFileName, LocaleId, ResourceSetName, Comment, true) == -1) { ErrorMessage = Data.ErrorMessage; return(false); } } } } } } return(true); }
/// <summary> /// Generates Resx Files for standard non-Web Resource files /// based on the BasePhysicalPath /// </summary> /// <param name="outputPath"> /// Optional output path where resources are generated. /// If not specified the value is inferred for an ASP.NET Web app. /// </param> /// <returns></returns> public bool GenerateResXFiles() { var data = DbResourceDataManager.CreateDbResourceDataManager(); // Retrieve all resources for a ResourceSet for all cultures // The data is ordered by ResourceSet, LocaleId and resource ID as each // ResourceSet or Locale changes a new file is written var resources = data.GetAllResources(); if (resources == null) { return(false); } string lastSet = ""; string lastLocale = "@!"; //// Load the document schema XmlDocument doc = new XmlDocument(); doc.LoadXml(ResXDocumentTemplate); XmlWriter xWriter = null; var xmlSettings = new XmlWriterSettings(); //// Make sure we use fragment syntax so there's no validation //// otherwise loading the original string will fail xmlSettings.ConformanceLevel = ConformanceLevel.Document; xmlSettings.IndentChars = " "; xmlSettings.Indent = true; foreach (var res in resources) { res.LocaleId = res.LocaleId.ToLower(); string stringValue = res.Value as string; // Create a new output file if the resource set or locale changes if (res.ResourceSet != lastSet || res.LocaleId != lastLocale) { if (xWriter != null) { xWriter.WriteEndElement(); xWriter.Close(); } string localizedExtension = ".resx"; if (res.LocaleId != "") { localizedExtension = "." + res.LocaleId + ".resx"; } string fullFileName = FormatResourceSetPath(res.ResourceSet) + localizedExtension; XmlTextWriter writer = new XmlTextWriter(fullFileName, Encoding.UTF8); writer.Indentation = 3; writer.IndentChar = ' '; writer.Formatting = Formatting.Indented; xWriter = writer; xWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'"); xWriter.WriteStartElement("root"); // Write out the schema doc.DocumentElement.ChildNodes[0].WriteTo(xWriter); // Write out the leading resheader elements XmlNodeList Nodes = doc.DocumentElement.SelectNodes("resheader"); foreach (XmlNode Node in Nodes) { Node.WriteTo(xWriter); } lastSet = res.ResourceSet; lastLocale = res.LocaleId; } if (string.IsNullOrEmpty(res.Type)) // plain string value { //<data name="LinkButton1Resource1.Text" xml:space="preserve"> // <value>LinkButton</value> //</data> xWriter.WriteStartElement("data"); xWriter.WriteAttributeString("name", res.ResourceId); xWriter.WriteAttributeString("xml", "space", null, "preserve"); xWriter.WriteElementString("value", stringValue); if (!string.IsNullOrEmpty(res.Comment)) { xWriter.WriteElementString("comment", res.Comment); } xWriter.WriteEndElement(); // data } // File Resources get written to disk else if (res.Type == "FileResource") { string ResourceFilePath = FormatResourceSetPath(res.ResourceSet); string ResourcePath = new FileInfo(ResourceFilePath).DirectoryName; if (stringValue.IndexOf("System.String") > -1) { string[] Tokens = stringValue.Split(';'); Encoding Encode = Encoding.Default; try { if (Tokens.Length == 3) { Encode = Encoding.GetEncoding(Tokens[2]); } // Write out the file to disk File.WriteAllText(ResourcePath + "\\" + res.FileName, res.TextFile, Encode); } catch { } } else { File.WriteAllBytes(ResourcePath + "\\" + res.FileName, res.BinFile); } //<data name="Scratch" type="System.Resources.ResXFileRef, System.Windows.Forms"> // <value>Scratch.txt;System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252</value> //</data> xWriter.WriteStartElement("data"); xWriter.WriteAttributeString("name", res.ResourceId); xWriter.WriteAttributeString("type", "System.Resources.ResXFileRef, System.Windows.Forms"); // values are already formatted in the database xWriter.WriteElementString("value", stringValue); if (!string.IsNullOrEmpty(res.Comment)) { xWriter.WriteElementString("comment", res.Comment); } xWriter.WriteEndElement(); // data } } // foreach dr if (xWriter != null) { xWriter.WriteEndElement(); //xWriter.WriteRaw("\r\n</root>"); xWriter.Close(); } return(true); }