public void GenerateDesignerFileTest() { var tempFile = Path.GetTempFileName(); try { var testData = TestData.SampleEntries(); ResXFile.Write(tempFile, testData); var className = "TestClassName"; var namespaceName = "fmdev.ResX.Tests"; Assert.IsTrue(ResXFile.GenerateDesignerFile(tempFile, className, namespaceName), "Designer file generation must return true"); var expectedDesignerFile = Path.Combine(Path.GetDirectoryName(tempFile), $"{className}.Designer.cs"); Assert.IsTrue(File.Exists(expectedDesignerFile), "Generated designer file must be written"); Assert.IsTrue(File.ReadAllText(expectedDesignerFile).Contains($"public class {className} "), "generated public designer class must be public"); File.Delete(expectedDesignerFile); Assert.IsTrue(ResXFile.GenerateDesignerFile(tempFile, className, namespaceName, true /*internalClass*/), "Designer file generation must return true"); Assert.IsTrue(File.Exists(expectedDesignerFile), "Generated designer file must be written"); Assert.IsTrue(File.ReadAllText(expectedDesignerFile).Contains($"internal class {className} "), "generated internal designer class must be internal"); File.Delete(expectedDesignerFile); } finally { File.Delete(tempFile); } }
/// <summary> /// Creates a new resource file. /// </summary> /// <returns>An ResXFile object to work with.</returns> public ResXFile CreateResxFile() { var root = new ResXRoot(); root.Resheader = new List <Resheader>(); root.Resheader.Add(new Resheader { Name = "resmimetype", Value = "text/microsoft-resx" }); root.Resheader.Add(new Resheader { Name = "version", Value = "2.0" }); root.Resheader.Add(new Resheader { Name = "reader", Value = "System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" }); root.Resheader.Add(new Resheader { Name = "writer", Value = "System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" }); root.Assembly = new ResXAssembly { Name = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", Alias = "System.Windows.Forms" }; root.Data = new List <Data>(); var ret = new ResXFile(root); return(ret); }
/// <summary> /// Saves the resource file to the given path. /// </summary> /// <param name="resxFile">The resource file object.</param> /// <param name="filePath">The path where the resource file will be saved to.</param> public void SaveResXFile(ResXFile resxFile, string filePath) { if (filePath == null) { throw new ArgumentNullException(nameof(filePath)); } }
public void SaveAsResX(string fileName, ResXSaveOption options) { var entries = new List <ResXEntry>(); foreach (var f in Files) { foreach (var u in f.TransUnits) { var entry = new ResXEntry() { Id = u.GetId(Dialect), Value = u.Target }; if (options.HasFlag(ResXSaveOption.IncludeComments) && u.Optional.Notes.Count() > 0) { entry.Comment = u.Optional.Notes.First().Value; } entries.Add(entry); } } if (options.HasFlag(ResXSaveOption.SortEntries)) { entries.Sort(); } ResXFile.Write(fileName, entries, options.HasFlag(ResXSaveOption.IncludeComments) ? ResXFile.Option.None : ResXFile.Option.SkipComments); }
public ResourceFile(string filename) { if (!File.Exists(filename)) { throw new Exception("File not found or invalid filename specified"); } FilePath = filename; Entries = new List <ResourceFileEntry>(); string parserType = SupportedFileTypes.ParserToUse(filename); switch (parserType) { case ".resx": ResXFile tempResX = new ResXFile(filename); foreach (ResourceFileEntry cfe in tempResX.Entries) { Entries.Add(cfe); } break; case ".strings": AppleStringsFile tempAppleStringsFile = new AppleStringsFile(filename); foreach (ResourceFileEntry cfe in tempAppleStringsFile.Entries) { Entries.Add(cfe); } break; default: throw new Exception("FileType not supported"); } }
public ImportResult ImportResX(string filename, string language) { var result = new ImportResult(); var entries = ResXFile.Read(filename); foreach (var e in entries) { var addOrUpdate = AddOrUpdateString(e.Id, language, e.Value, DefaultNewState, e.Comment); if (addOrUpdate == AddOrUpdateResult.Added) { result.AddedItems.Add(e.Id); } if (addOrUpdate == AddOrUpdateResult.Updated) { result.UpdatedItems.Add(e.Id); } } if (!GetLanguages().Contains(language)) { var langs = GetLanguages(); langs.Add(language); SetLanguages(langs); } return(result); }
public void ReadTest() { var tempFile = Path.GetTempFileName(); try { var testData = TestData.SampleEntries(); Assert.IsTrue(testData.Count > 0, "test data must not be empty"); ResXFile.Write(tempFile, testData); var entries = ResXFile.Read(tempFile); foreach (var writtenEntry in testData) { Assert.IsTrue(entries.Exists(e => e.Id == writtenEntry.Id && e.Value == writtenEntry.Value && e.Comment == writtenEntry.Comment), $"item '{writtenEntry.Id}' must be in read entries"); } // skip comments test entries = ResXFile.Read(tempFile, ResXFile.Option.SkipComments); Assert.IsTrue(entries.All(e => string.IsNullOrEmpty(e.Comment)), "comments must be empty"); foreach (var writtenEntry in testData) { Assert.IsTrue(entries.Exists(e => e.Id == writtenEntry.Id && e.Value == writtenEntry.Value), $"item '{writtenEntry.Id}' must be in read entries"); } } finally { File.Delete(tempFile); } }
public void ResXFileName() { string filename = GetTestFile("AboutForm.resx"); ResXFile resXFile = new ResXFile(filename, new CultureInfo("de")); Assert.AreEqual(filename, resXFile.NonLocalizedFileName, true); Assert.AreEqual(GetTestFile("de\\AboutForm.de.resx"), resXFile.LocalizedFileName, true); Assert.AreEqual("de", resXFile.Culture.Name); }
/// <summary> /// Updates the xlf data from the provided resx source file. /// </summary> /// <param name="sourceFile">The source file to be processed.</param> /// <param name="updatedResourceStateString">The state string that should be used for updated items.</param> /// <param name="addedResourceStateString">The state string that should be used for added items.</param> /// <returns>Return the ids of the updated/added/removed items in separate lists.</returns> public UpdateResult Update(string sourceFile, string updatedResourceStateString, string addedResourceStateString) { var resxData = new Dictionary <string, ResXEntry>(); // id, value, comment foreach (var entry in ResXFile.Read(sourceFile, ResXFile.Option.None)) { resxData.Add(entry.Id, entry); } var updatedItems = new List <string>(); var addedItems = new List <string>(); var removedItems = new List <string>(); foreach (var f in Files) { foreach (var u in f.TransUnits) { var key = u.GetId(Dialect); if (resxData.ContainsKey(key)) { if (XmlUtil.NormalizeLineBreaks(u.Source) != XmlUtil.NormalizeLineBreaks(resxData[key].Value)) { // source text changed u.Source = resxData[key].Value; u.Optional.TargetState = updatedResourceStateString; u.Optional.SetCommentFromResx(resxData[key].Comment); updatedItems.Add(key); } } else { removedItems.Add(key); } resxData.Remove(key); } foreach (var id in removedItems) { f.RemoveTransUnit(id, Dialect); } foreach (var d in resxData) { var unit = f.AddTransUnit(d.Key, d.Value.Value, d.Value.Value, XlfFile.AddMode.FailIfExists, Dialect); unit.Optional.TargetState = addedResourceStateString; unit.Optional.SetCommentFromResx(d.Value.Comment); addedItems.Add(d.Key); } } return(new UpdateResult(addedItems, removedItems, updatedItems)); }
private ResXFile AddResxFile(string file) { // This method adds a .resx file "file" to our .resx cache. The method causes the file // to be cracked for contained files. ResXFile resxFile = new ResXFile(file, BaseLinkedFileDirectory); resXFiles.AddDependencyFile(file, resxFile); isDirty = true; return(resxFile); }
internal ResXFile(string filename, string baseLinkedFileDirectory) : base(filename) { // Creates a new ResXFile object and populates the class member variables // by computing a list of linked files within the .resx that was passed in. // // filename is the filename of the .resx file that is to be examined. if (File.Exists(FileName)) { linkedFiles = ResXFile.GetLinkedFiles(filename, baseLinkedFileDirectory); } }
public void ReadResources() { string filename = GetTestFile("AboutForm.resx"); ResXFile resXFile = new ResXFile(filename, new CultureInfo("fr")); resXFile.Read(); ICollection <LocString> strings = resXFile.AllStrings; foreach (LocString locstr in strings) { Console.WriteLine("Name:{0} NonLocValue:{1} LocValue:{2} Comment:{3}", locstr.Name, locstr.NonLocalized, locstr.Localized, locstr.Comment); } }
public void InvalidGenerateDesignerFileTest() { Assert.ThrowsException <FileNotFoundException>(() => ResXFile.GenerateDesignerFile("ThisResXFileDoesNotExist.rex", "someclass", "some.namespace"), "Nonexistent resX file must lead to FileNotFoundException"); var tempFile = Path.GetTempFileName(); try { Assert.ThrowsException <ArgumentException>(() => ResXFile.GenerateDesignerFile(tempFile, null, null), "Empty class names should not be allowed and result in an ArgumentException"); Assert.ThrowsException <ArgumentException>(() => ResXFile.GenerateDesignerFile(tempFile, "myClass", null), "Empty namespace names should not be allowed and result in an ArgumentException"); } finally { File.Delete(tempFile); } }
/// <summary> /// Saves the resource file to the given path. /// </summary> /// <param name="resxFile">The resource file object.</param> /// <param name="file">The <see cref="Stream"/> where the resource data will be saved to.</param> public void SaveResXFile(ResXFile resxFile, Stream file) { if (resxFile == null) { throw new ArgumentNullException(nameof(resxFile)); } if (file == null) { throw new ArgumentNullException(nameof(file)); } using (var streamWriter = new StreamWriter(file)) { _serializer.Serialize(streamWriter, resxFile.GetResXRoot()); } }
/// <summary> /// Reads .resx file from stream. /// </summary> /// <param name="file"><see cref="Stream"/> with .resx data.</param> /// <returns>An object which represents the .resx file.</returns> public ResXFile ReadResXFile(Stream file) { ResXFile ret; try { using (var streamReader = new StreamReader(file)) { var fileContent = _serializer.Deserialize(streamReader); ret = new ResXFile((ResXRoot)fileContent); } } catch (Exception ex) { throw new SerializationException("There was an error while parsing the given resx file.", ex); } return(ret); }
public void ExportResX(string filename, string language, SaveOptions options) { if (!GetLanguages().Contains(language)) { throw new ArgumentException($"'{language}' is not a configured language."); } var entries = new List <ResXEntry>(); foreach (var item in Items) { var entry = new ResXEntry(); TextItem text; if (!item.Texts.TryGetValue(language, out text) && !item.Texts.TryGetValue(NeutralLanguage, out text)) { throw new MissingTranslationsException(new List <string>() { $"{item.Id};{language}" }); } entry.Id = item.Id; entry.Value = text.Value; if (!options.HasFlag(SaveOptions.SkipComments)) { string comment; if (item.Comments.TryGetValue(language, out comment) || item.Comments.TryGetValue(NeutralLanguage, out comment)) { entry.Comment = comment; } } entries.Add(entry); } if (options.HasFlag(SaveOptions.SortEntries)) { entries.Sort(); } ResXFile.Write(filename, entries); }
public void WriteUnixEolTest() { var tempFile = Path.GetTempFileName(); try { var testData = TestData.SampleEntriesWithUnixLineEndings(); ResXFile.Write(tempFile, testData); var content = File.ReadAllText(tempFile, Encoding.UTF8).Replace("\r", string.Empty); foreach (var entry in testData) { Assert.IsTrue(content.Contains($"<data name=\"{entry.Id}\""), $"file must contain entry '{entry.Id}'"); Assert.IsTrue(content.Contains($"<value>{entry.Value}</value>"), $"file must contain expected value for entry '{entry.Id}'"); Assert.IsTrue(content.Contains(entry.Comment), $"file must contain comment for entry '{entry.Id}'"); } } finally { File.Delete(tempFile); } }
public void WriteSkipCommentsTest() { var tempFile = Path.GetTempFileName(); try { var testData = TestData.SampleEntries(); ResXFile.Write(tempFile, testData, ResXFile.Option.SkipComments); var content = File.ReadAllText(tempFile, Encoding.UTF8); foreach (var entry in testData) { Assert.IsTrue(content.Contains($"<data name=\"{entry.Id}\""), $"file must contain entry '{entry.Id}'"); Assert.IsTrue(content.Contains($"<value>{entry.Value}</value>"), $"file must contain expected value for entry '{entry.Id}'"); Assert.IsFalse(content.Contains(entry.Comment), $"file must not comment for entry '{entry.Id}'"); } } finally { File.Delete(tempFile); } }
public void WriteWindowsEolTest() { var tempFile = Path.GetTempFileName(); try { var testData = TestData.SampleEntriesWithWindowsLineEndings(); ResXFile.Write(tempFile, testData); var content = File.ReadAllText(tempFile, Encoding.UTF8); Assert.IsTrue(content.Contains("\r\n"), "file content is expected to have windows line endings"); foreach (var entry in testData) { Assert.IsTrue(content.Contains($"<data name=\"{entry.Id}\""), $"file must contain entry '{entry.Id}'"); Assert.IsTrue(content.Contains($"<value>{entry.Value}</value>"), $"file must contain expected value for entry '{entry.Id}'"); Assert.IsTrue(content.Contains(entry.Comment), $"file must contain comment for entry '{entry.Id}'"); } } finally { File.Delete(tempFile); } }
internal ResXFile GetResXFileInfo(string resxFile) { // First, try to retrieve the resx information from our hashtable. ResXFile retVal = (ResXFile)resXFiles.GetDependencyFile(resxFile); if (retVal == null) { // Ok, the file wasn't there. Add it to our cache and return it to the caller. retVal = AddResxFile(resxFile); } else { // The file was there. Is it up to date? If not, then we'll have to refresh the file // by removing it from the hashtable and readding it. if (retVal.HasFileChanged()) { resXFiles.RemoveDependencyFile(resxFile); isDirty = true; retVal = AddResxFile(resxFile); } } return(retVal); }
private ResXFile AddResxFile(string file) { // This method adds a .resx file "file" to our .resx cache. The method causes the file // to be cracked for contained files. ResXFile resxFile = new ResXFile(file, BaseLinkedFileDirectory); _resXFiles.AddDependencyFile(file, resxFile); _isDirty = true; return resxFile; }
public bool Execute(string projectDir) { List <string> filesOutputted = new List <string>(); Dictionary <string, List <ResXEntry> > parsedSourceFiles = new Dictionary <string, List <ResXEntry> >(); try { foreach (var file in Directory.GetFiles(projectDir, "*.xlf", SearchOption.AllDirectories)) { var doc = new XlfDocument(file); var xlfFile = doc.Files.Single(); // The two-char language code string targetLanguageCode = Path.GetFileName(file).Split('.').Reverse().ElementAt(1); // Original seems to include project directory in path, so we go up one level first, and then we need to get just the directory string originalFile = Path.Combine(Directory.GetParent(projectDir).FullName, xlfFile.Original.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar)); if (!File.Exists(originalFile)) { Log.LogError("Original file not found at path: " + originalFile); return(false); } string outDir = Path.GetDirectoryName(originalFile); string originalFileName = Path.GetFileName(originalFile); string outFileName = Path.Combine(outDir, $"{Path.GetFileNameWithoutExtension(originalFileName)}.{targetLanguageCode}.resx"); // First update the XLF file List <ResXEntry> parsedSourceFile; if (!parsedSourceFiles.TryGetValue(originalFile, out parsedSourceFile)) { try { parsedSourceFile = ResXFile.Read(originalFile); parsedSourceFiles[originalFile] = parsedSourceFile; } catch (Exception ex) { Log.LogError("Invalid source file: " + originalFile + ". " + ex.ToString()); return(false); } } UpdateXlfFile(doc, parsedSourceFile); doc.SaveAsResX(outFileName); Log.LogMessage("Exported " + outFileName); filesOutputted.Add(outFileName); } } catch (Exception ex) { Log.LogErrorFromException(ex); return(false); } finally { //if (filesOutputted.Count > 0) //{ // File.WriteAllText("XliffCompilerWrittenFiles.txt", string.Join("\n", filesOutputted)); //} } return(true); }
public static List <SatelliteAssembly> GetAssemblies(string planXml, string culture, string basePath, string configuration, string fullOutputDirectory) { List <SatelliteAssembly> assemblies = new List <SatelliteAssembly>(); XmlDocument doc = new XmlDocument(); doc.Load(planXml); Console.WriteLine("Reading Satellite Assembly Generation Plan"); foreach (XmlNode sAssembly in doc.SelectNodes("/Resources/Resource")) { SatelliteAssembly assembly = new SatelliteAssembly() { Name = sAssembly.SelectSingleNode("AssemblyName").InnerText, Location = sAssembly.SelectSingleNode("Location").InnerText, }; if (assembly.Name.Length > 0) { try { string projectOutDir = GetProjectOutputDir(assembly, basePath, configuration); assembly.FullOutputPath = Path.Combine(Path.Combine(projectOutDir, culture), sAssembly.SelectSingleNode("SatelliteAssembly").InnerText); assembly.Culture = culture; assembly.Files = new List <ResXFile>(); XmlNode node = sAssembly.SelectSingleNode("AssemblyType"); try { if (node != null) { assembly.Type = (SatelliteAssembly.AssemblyType)Enum.Parse(typeof(SatelliteAssembly.AssemblyType), node.InnerText); } } catch { } node = sAssembly.SelectSingleNode("AssemblyKeyFile"); if (node != null) { if (Path.IsPathRooted(node.InnerText)) { assembly.KeyFile = node.InnerText; } else { assembly.KeyFile = Path.Combine(Path.Combine(basePath, assembly.Location), node.InnerText); } } foreach (XmlNode resx in sAssembly.SelectNodes("Resx")) { string logicalName = string.Format("{0}.{1}.resources", resx.SelectSingleNode("LogicalName").InnerText, culture); ResXFile file = new ResXFile() { Name = resx.SelectSingleNode("Name").InnerText.Replace(assembly.Location, ""), LogicalName = logicalName, Output = Path.Combine(fullOutputDirectory, logicalName), RelativePath = resx.SelectSingleNode("RelativePath").InnerText }; assembly.Files.Add(file); } if (assembly.Name.Length > 0) { assemblies.Add(assembly); } } catch { Console.WriteLine(string.Format("Error for '{0}'", assembly.Name)); } } } return(assemblies); }