Westwind.Globalization.DbResXConverter.GenerateResXFiles C# (CSharp) Method

GenerateResXFiles() public method

Generates Resx Files for standard non-Web Resource files based on the BasePhysicalPath
public GenerateResXFiles ( IEnumerable resourceSets = null, bool generateStronglyTypedClasses = false ) : bool
resourceSets IEnumerable
generateStronglyTypedClasses bool
return bool
        public bool GenerateResXFiles(IEnumerable<string> resourceSets = null, bool generateStronglyTypedClasses = false)
        {
            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(applyValueConverters: true);
           
            if (resourceSets != null)
                resources = resources.Where(rs => resourceSets.Any(rs1 => rs1 == rs.ResourceSet))
                                     .ToList();

            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
                            var file = Path.Combine(ResourcePath, res.FileName);
                            File.Delete(file);
                            File.WriteAllText(file, res.TextFile, Encode);                            
                        }
                        catch
                        {
                        }
                    }
                    else
                    {
                        var file = Path.Combine(ResourcePath, res.FileName);
                        File.Delete(file); // overwrite doesn't appear to work so explicitly delete
                        File.WriteAllBytes(file, 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;
        }

Usage Example

        protected void btnExportResources_Click(object sender, EventArgs e)
        {
#if OnlineDemo
        this.ErrorDisplay.ShowError(WebUtils.LRes("FeatureDisabled"));
        return;
#endif

            DbResXConverter Exporter = new DbResXConverter(Context.Request.PhysicalApplicationPath);

            if (DbResourceConfiguration.Current.ResxExportProjectType == GlobalizationResxExportProjectTypes.WebForms)
            {
                if (!Exporter.GenerateLocalWebResourceResXFiles())
                {
                    ErrorDisplay.ShowError(WebUtils.LRes("ResourceGenerationFailed"));
                    return;
                }
                if (!Exporter.GenerateGlobalWebResourceResXFiles())
                {
                    ErrorDisplay.ShowError(WebUtils.LRes("ResourceGenerationFailed"));
                    return;
                }
            }
            else
            {
                if (!Exporter.GenerateResXFiles())
                {
                    ErrorDisplay.ShowError(WebUtils.LRes("ResourceGenerationFailed"));
                    return;
                }
            }

            ErrorDisplay.ShowMessage(WebUtils.LRes("ResourceGenerationComplete"));
        }