public static int Main(string[] args) { try{ Console.WriteLine("! MakeRes is using .NET version: " + Environment.Version.ToString()); ResourceWriter rw = new ResourceWriter(args[0] + ".resources"); for(int i = 1; i < args.Length; i = i + 2) { using(FileStream fs = File.OpenRead(args[i + 1])) { byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); Console.WriteLine("ID = " + args[i]); rw.AddResource(args[i], buffer); fs.Close(); SHA1 sha = new SHA1CryptoServiceProvider(); byte[] result = sha.ComputeHash(buffer); WriteHash(args[0] + "."+ args[i], result); } } rw.Close(); }catch(Exception ex) { Console.WriteLine("# MareRes Error: " + ex.Message + "\r\n" + ex.StackTrace); return 1; } return 0; }
static void Main() { ResourceWriter writer = new ResourceWriter("test.resources"); writer.AddResource("1", "2"); writer.Generate(); writer.Close(); }
static void Assemble(string pattern) { string[] files = Directory.GetFiles(Directory.GetCurrentDirectory(), pattern); foreach (string file in files) { if (Path.GetExtension(file).ToUpper() == ".XML") { try { XmlDocument doc = new XmlDocument(); doc.Load(file); string resfilename = "StringResources." + doc.DocumentElement.Attributes["language"].InnerText + ".resources"; ResourceWriter rw = new ResourceWriter(resfilename); foreach (XmlElement el in doc.DocumentElement.ChildNodes) { rw.AddResource(el.Attributes["name"].InnerText, el.InnerText); } rw.Generate(); rw.Close(); } catch (Exception e) { Console.WriteLine("Error while processing " + file + " :"); Console.WriteLine(e.ToString()); } } } }
static void Main() { ResourceWriter rw = new ResourceWriter("MCListBox.resources"); using(Image image = Image.FromFile("../../TRFFC10a.ICO")) { rw.AddResource("StopLight",image); rw.Close(); } }
public static int Pack (List<string> files) { IResourceWriter output = null; try { if (files [0].EndsWith (".resx")) { output = new ResXResourceWriter (files [0]); } else { output = new ResourceWriter (files [0]); } } catch { Console.WriteLine ("Error creating {0} file", files [0]); } int i = 1; while (i < files.Count) { string f = files [i++]; string key; string file = f; if (f.StartsWith ("@")) { files.AddRange (System.IO.File.ReadAllLines (f.Substring (1))); continue; } int comma = file.IndexOf (','); if (comma != -1) { key = file.Substring (comma + 1); file = file.Substring (0, comma); } else { key = Path.GetFileName (file); } using (FileStream source = File.OpenRead (file)){ byte [] buffer = new byte [source.Length]; source.Read (buffer, 0, (int) source.Length); // Sadly, we cant just pass byte arrays to resourcewriter, we need // to wrap this on a MemoryStream MemoryStream value = new MemoryStream (buffer); output.AddResource (Uri.EscapeUriString (key).ToLowerInvariant (), value); } } output.Generate (); return 0; }
public static ResourceWriter GenerateResourceStream(Dictionary<string, string> inp_dict, MemoryStream ms) { ResourceWriter rw = new ResourceWriter(ms); foreach (KeyValuePair<string, string> e in inp_dict) { string name = e.Key; string values = e.Value; rw.AddResource(name, values); } rw.Generate(); ms.Seek(0L, SeekOrigin.Begin); return rw; }
private static void CreateResourceFile( string csFile, string resFile, string outputDir, out string sourceHash, out int viewCount) { viewCount = -1; sourceHash = string.Empty; var codeProvider = new CSharpCodeProvider(); var inMemoryCodeCompiler = codeProvider.CreateCompiler(); var parameters = new CompilerParameters(); parameters.ReferencedAssemblies.Add("System.Data.Entity.dll"); parameters.GenerateInMemory = true; CompilerResults results = inMemoryCodeCompiler.CompileAssemblyFromFile(parameters, csFile); if (results.Errors.Count == 0) { Assembly resultingAssembly = results.CompiledAssembly; Type[] typeList = resultingAssembly.GetTypes(); foreach (Type type in typeList) { if (type.BaseType == typeof(EntityViewContainer)) { MethodInfo[] methodInfo = type.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance); var instance = (EntityViewContainer)Activator.CreateInstance(type); sourceHash = instance.HashOverAllExtentViews; viewCount = instance.ViewCount; using (var resWriter = new ResourceWriter(Path.Combine(outputDir, resFile))) { foreach (MethodInfo method in methodInfo) { if (char.IsDigit(method.Name, method.Name.Length - 1)) { var result = (KeyValuePair<string, string>)method.Invoke(instance, null); resWriter.AddResource(method.Name.Replace("GetView", string.Empty), result); } } resWriter.Generate(); resWriter.Close(); } } } } else { Console.WriteLine("Unable to Generate Resource File"); } }
public static void Main(string[] args) { const string usage = "Usage: cscscript res <fileIn> <fileOut>...\n" + "Generates .resources file.\n" + "fileIn - input file (etc .bmp). Specify 'dummy' to prepare empty .resources file (etc. css res dummy Scripting.Form1.resources).\n" + "fileOut - output file name (etc .resource).\n"; try { //Debug.Assert(false); if (args.Length < 2) Console.WriteLine(usage); else { //currently no .resx compilation with ResGen.exe is implemented, only dummy ressource copying if (string.Compare(args[0], "dummy") == 0) { if (Environment.GetEnvironmentVariable(@"CSSCRIPT_DIR") == null) return; //CS-Script is not installed string srcFile = Environment.ExpandEnvironmentVariables(@"%CSSCRIPT_DIR%\lib\resources.template"); string destFile = ResolveAsmLocation(args[1]); if (!File.Exists(destFile)) File.Copy(srcFile, destFile, true); } else { var fileToEmbedd = Environment.ExpandEnvironmentVariables(args[0]); var resFile = Environment.ExpandEnvironmentVariables(args[1]); using (ResourceWriter resourceWriter = new ResourceWriter(resFile)) { resourceWriter.AddResource(Path.GetFileName(fileToEmbedd), File.ReadAllBytes(fileToEmbedd)); resourceWriter.Generate(); } } } } catch (Exception ex) { Console.WriteLine(ex.Message); throw ex; } }
static public void Main(string[] args) { string sourceDir = Path.GetDirectoryName(args[0]); string[] files = new string[] { Path.Combine(sourceDir, "css_logo_256x256.png"), Path.Combine(sourceDir, "donate.png") }; var resFile = Path.Combine(sourceDir, "images.resources"); using (var resourceWriter = new ResourceWriter(resFile)) { foreach (string file in files) resourceWriter.AddResource(Path.GetFileName(file), new Bitmap(file)); resourceWriter.Generate(); } }
public void Bug81759() { MemoryStream ms = new MemoryStream(); using (ResourceReader xr = new ResourceReader( "Test/resources/bug81759.resources")) { ResourceWriter rw = new ResourceWriter(ms); foreach (DictionaryEntry de in xr) { rw.AddResource((string)de.Key, de.Value); } rw.Close(); } ResourceReader rr = new ResourceReader(new MemoryStream(ms.ToArray())); foreach (DictionaryEntry de in rr) { Assert.AreEqual("imageList.ImageSize", de.Key as string, "#1"); Assert.AreEqual("Size", de.Value.GetType().Name, "#2"); } }
private void AddRESX(string string2) { string path = Path.ChangeExtension(string2, ".resources"); if (File.Exists(path)) { File.Delete(path); } using (ResXResourceReader reader = new ResXResourceReader(string2)) { reader.BasePath = SourcePath; using (ResourceWriter writer = new ResourceWriter(path)) { foreach (DictionaryEntry entry in reader) { string name = entry.Key.ToString(); writer.AddResource(name, entry.Value); } } } Options.EmbeddedResources.Add(path); }
private static void CompileEmbeddedRes(PlgxPluginInfo plgx) { foreach (string strResSrc in plgx.EmbeddedResourceSources) { string strResFileName = plgx.BaseFileName + "." + UrlUtil.ConvertSeparators( UrlUtil.MakeRelativePath(plgx.CsprojFilePath, strResSrc), '.'); string strResFile = UrlUtil.GetFileDirectory(plgx.CsprojFilePath, true, true) + strResFileName; if (strResSrc.EndsWith(".resx", StrUtil.CaseIgnoreCmp)) { string strRsrc = UrlUtil.StripExtension(strResFile) + ".resources"; ResXResourceReader r = new ResXResourceReader(strResSrc); ResourceWriter w = new ResourceWriter(strRsrc); r.BasePath = UrlUtil.GetFileDirectory(strResSrc, false, true); foreach (DictionaryEntry de in r) { w.AddResource((string)de.Key, de.Value); } w.Generate(); w.Close(); r.Close(); if (File.Exists(strRsrc)) { plgx.CompilerParameters.EmbeddedResources.Add(strRsrc); Program.TempFilesPool.Add(strRsrc); } } else { File.Copy(strResSrc, strResFile, true); plgx.CompilerParameters.EmbeddedResources.Add(strResFile); } } }
public string WriteResources() { IDeclarationTarget idt = null; if (this.IsPartial) { return(null); } for (idt = this; idt != null && (!(idt is INameSpaceDeclaration)); idt = idt.ParentTarget) { ; } if ((idt == null) || (!(idt is INameSpaceDeclaration))) { throw new InvalidOperationException("Object in an invalid state."); } INameSpaceDeclaration insd = (INameSpaceDeclaration)idt; TemporaryFile tf; if (this == this.Project.Resources) { tf = TemporaryFileHelper.GetTemporaryDirectory("", true).Files.GetTemporaryFile(string.Format("Resources.resources", insd.FullName, this.Name)); } else { tf = TemporaryFileHelper.GetTemporaryDirectory("", true).Files.GetTemporaryFile(string.Format("{0}.{1}.resources", insd.FullName, this.Name)); } tf.OpenStream(FileMode.Create); ResourceWriter rw = new ResourceWriter(tf.FileStream); foreach (IDeclarationResourcesStringTableEntry idrste in this.StringTable.Values) { rw.AddResource(idrste.Name, idrste.Value); } rw.Close(); tf.CloseStream(); return(tf.FileName); }
[Test] // bug #81757 public void ReadNullResource() { MemoryStream stream = new MemoryStream(); object value = null; ResourceWriter rw = new ResourceWriter(stream); rw.AddResource("NullTest", value); rw.Generate(); stream.Position = 0; using (ResourceReader rr = new ResourceReader(stream)) { int entryCount = 0; foreach (DictionaryEntry de in rr) { Assert.AreEqual("NullTest", de.Key, "#1"); Assert.IsNull(de.Value, "#2"); Assert.AreEqual(0, entryCount, "#3"); entryCount++; } Assert.AreEqual(1, entryCount, "#4"); } }
static public void Main(string[] args) { string sourceDir = Path.GetDirectoryName(args[0]); string[] files = new string[] { Path.Combine(sourceDir, "css_logo_256x256.png"), Path.Combine(sourceDir, "donate.png") }; var resFile = Path.Combine(sourceDir, "images.resources"); using (var resourceWriter = new ResourceWriter(resFile)) { foreach (string file in files) { resourceWriter.AddResource(Path.GetFileName(file), new Bitmap(file)); } resourceWriter.Generate(); } }
private void WriteResourceFile(string resxFileName) { var resxFilePath = Path.Combine("..", "WebSites", SiteName, "Resources"); var resxFullFileName = Path.Combine(resxFilePath, resxFileName); if (File.Exists(resxFullFileName)) { using (var fs = File.OpenRead(resxFullFileName)) { var document = XDocument.Load(fs); var binDirPath = Path.Combine(resxFilePath, "bin"); if (!Directory.Exists(binDirPath)) { Directory.CreateDirectory(binDirPath); } // Put in "bin" sub-folder of resx file var targetPath = Path.Combine( binDirPath, Path.ChangeExtension(resxFileName, ".resources")); using (var targetStream = File.Create(targetPath)) { var rw = new ResourceWriter(targetStream); foreach (var e in document.Root.Elements("data")) { var name = e.Attribute("name").Value; var value = e.Element("value").Value; rw.AddResource(name, value); } rw.Generate(); } } } }
private void btnCreateResources_Click(object sender, EventArgs e) { string fileTxt = txtOpenFileTxt.Text; string rootDirectory = Path.GetDirectoryName(fileTxt) + @"\"; //获取文件所在目录 string fileName = Path.GetFileNameWithoutExtension(fileTxt); //获取文件名不包含后缀 IResourceWriter writer = new ResourceWriter(rootDirectory + fileName + ".resources"); if (string.IsNullOrWhiteSpace(fileTxt)) { MessageBox.Show("未选择文件请重试"); return; } string txtKeyValue = File.ReadAllText(fileTxt); string[] strKeyValueArrays = txtKeyValue.Split(','); foreach (var strKeyValueArray in strKeyValueArrays) { string[] strSingleArrays = strKeyValueArray.Split('='); writer.AddResource(strSingleArrays[0].Trim(), strSingleArrays[1].Trim()); } writer.Close(); }
/// <summary> /// Export a list of strings to a .resources file, a binary file format used in .NET applications. /// </summary> /// <param name="file">The path to create the file at.</param> /// <param name="categories">The list of strings, organized into categories.</param> public static void ExportToBinaryRes(string file, List <Category> categories) { ResourceWriter res = new ResourceWriter(file); foreach (Category cat in categories) { string name = cat.Name + "."; if (name == ".") { name = ""; } foreach (Translation item in cat.Translations) { res.AddResource(name + item.Id, item.TranslatedItem); } } res.Generate(); res.Close(); }
public static void UpdateResEntry(string resourceFile, string name, object value) { using (var reader = new ResourceReader(resourceFile)) { using (var writer = new ResourceWriter(resourceFile)) { var de = reader.GetEnumerator(); while (de.MoveNext()) { if (de.Entry.Key.ToString().Equals(name, StringComparison.InvariantCultureIgnoreCase)) { writer.AddResource(name, value); } else { writer.AddResource(de.Entry.Key.ToString(), de.Entry.Value.ToString()); } } writer.AddResource(name, value); } } }
private Resource RebuildWpfRoot() { using (MemoryStream stream = new MemoryStream()) { using (ResourceWriter writer = new ResourceWriter(stream)) { int count = 0; foreach (KeyValuePair <string, ResourcePart> pair in wpfRootParts) { if (!unusedWpfResourceExclusions.Contains(pair.Value.Name)) { if (pair.Value.Baml != null) { if (!usedBamlsCache.Contains(pair.Value)) { Log($"Cleaned up unused BAML: {pair.Key}"); continue; } } else if (!usedWpfResources.Contains(pair.Value.Name) && removeUnknownResources) { Log($"Cleaned up unused WPF resource: {pair.Key}"); continue; } } writer.AddResource(pair.Key, pair.Value.Stream, false); count++; } if (count > 0) { writer.Generate(); } } return(new EmbeddedResource(wpfRootResource.Name, wpfRootResource.Attributes, stream.ToArray())); } }
public void AddResource_Name_Duplicate() { MemoryStream ms = new MemoryStream(); ResourceWriter writer = new ResourceWriter(ms); writer.AddResource("FirstName", "Miguel"); try { writer.AddResource("FirstNaMe", "Chris"); Assert.Fail("#1"); } catch (ArgumentException ex) { // Item has already been added. Key is dictionary: // 'FirstName' Key being added: 'FirstNaMe' Assert.AreEqual(typeof(ArgumentException), ex.GetType(), "#2"); Assert.IsNull(ex.InnerException, "#3"); Assert.IsNotNull(ex.Message, "#4"); Assert.IsNull(ex.ParamName, "#5"); } writer.AddResource("Name", "Miguel"); writer.Close(); }
public static void ExceptionforResWriter06() { Assert.Throws <ArgumentOutOfRangeException>(() => { byte[] buffer = new byte[_RefBuffer.Length]; using (var ms2 = new MemoryStream(buffer, true)) { var rw1 = new ResourceWriter(ms2); try { rw1.Generate(); } finally { Assert.Throws <NotSupportedException>(() => { rw1.Dispose(); }); } } }); }
private void BuildBinaryResource() { if (File.Directory == null) { return; } var extension = String.IsNullOrEmpty(Language) ? "resources" : $"{Language}.resources"; var path = Path.Combine(File.Directory.FullName, $"{Name}.{extension}"); using var resx = new ResourceWriter(path); foreach (var(key, value) in Translations) { resx.AddResource(key, value); } resx.Generate(); resx.Close(); Console.WriteLine($"Binary resource file generated: {path}"); }
private void method_1(string string_4) { string text = Path.ChangeExtension(string_4, ".resources"); if (File.Exists(text)) { File.Delete(text); } using (ResXResourceReader resXResourceReader = new ResXResourceReader(string_4)) { resXResourceReader.BasePath = this.SourcePath; using (ResourceWriter resourceWriter = new ResourceWriter(text)) { foreach (object obj in resXResourceReader) { DictionaryEntry dictionaryEntry = (DictionaryEntry)obj; resourceWriter.AddResource(dictionaryEntry.Key.ToString(), dictionaryEntry.Value); } } } this.Options.EmbeddedResources.Add(text); }
public static void ExceptionforResWriter03() { Assert.Throws <ArgumentNullException>(() => { byte[] buffer = new byte[_RefBuffer.Length]; using (var ms2 = new MemoryStream(buffer, true)) { var rw1 = new ResourceWriter(ms2); try { rw1.AddResource(null, "args"); } finally { Assert.Throws <ArgumentOutOfRangeException>(() => { rw1.Dispose(); }); } } }); }
public void Generate_Closed() { MemoryStream ms = new MemoryStream(); ResourceWriter writer = new ResourceWriter(ms); writer.AddResource("Name", "Miguel"); writer.Close(); try { writer.Generate(); Assert.Fail("#B1"); } catch (InvalidOperationException ex) { // The resource writer has already been closed // and cannot be edited Assert.AreEqual(typeof(InvalidOperationException), ex.GetType(), "#B2"); Assert.IsNull(ex.InnerException, "#B3"); Assert.IsNotNull(ex.Message, "#B4"); } }
public void Map() { if (!_assembly.HasWpfResource) { return; } var resource = _assembly.GetWpfResource(); if (!resource.HasWpfBaml) { return; } var data = resource.GetData(); bool changed = false; using (var outputStream = new MemoryStream()) { using (var reader = new ResourceReaderEx(data)) { using (var writer = new ResourceWriter(outputStream)) { while (reader.Read()) { byte[] resourceData = reader.Data; Map(reader, ref resourceData, ref changed); writer.AddResourceData(reader.Name, reader.TypeName, resourceData); } } } if (changed) { resource.SetData(outputStream.ToArray()); } } }
static void Main(string[] args) { string dataDirectory = args[0]; string targetFile = args[1]; XmlDocument map = new XmlDocument(); XmlNode xFilesNode = map.CreateElement("Files"); ResourceWriter writer = new ResourceWriter(targetFile); foreach (string file in Directory.GetFiles(dataDirectory, "*", SearchOption.AllDirectories)) { XmlNode xFile = map.CreateElement("File"); string id = Guid.NewGuid().ToString(); string targetDirectory = Path.GetDirectoryName(file).Replace(dataDirectory, ""); if (targetDirectory.StartsWith("\\")) { targetDirectory = targetDirectory.Substring(1); } xFile.AppendChild(createNode(map, "Id", id)); xFile.AppendChild(createNode(map, "Directory", targetDirectory));; xFile.AppendChild(createNode(map, "Filename", Path.GetFileName(file))); xFilesNode.AppendChild(xFile); writer.AddResourceData(id, "setupData", Compress(File.ReadAllBytes(file))); } map.AppendChild(xFilesNode); using (MemoryStream msData = new MemoryStream()) { using (StreamWriter sw = new StreamWriter(msData, Encoding.UTF8)) { map.Save(sw); writer.AddResourceData("map", "setupData", msData.ToArray()); } } writer.Generate(); writer.Dispose(); }
protected virtual void WriteMetadata(TextWriter writer, string requestedModule) { var context = new TypescriptGenerationContext(); var schema0 = new ContentRepository.Schema.Metadata.Schema(new[] { "Application", "ApplicationCacheFile", "FieldSettingContent", "JournalNode" }); var schema1 = new TypescriptTypeCollectorVisitor(context).Visit(schema0); switch (requestedModule) { case "enums": new TypescriptEnumsVisitor(context, writer).Visit(schema1); break; case "complextypes": new TypescriptComplexTypesVisitor(context, writer).Visit(schema1); break; case "contenttypes": new TypescriptClassesVisitor(context, writer).Visit(schema1); break; case "resources": ResourceWriter.WriteResourceClasses(writer); break; case "schemas": new TypescriptCtdVisitor(context, writer).Visit(schema1); break; case "fieldsettings": new TypescriptFieldSettingsVisitor(context, writer).Visit(schema1); break; default: throw new InvalidOperationException( $"Unknown module name: {requestedModule}. Valid names: {string.Join(", ", ModuleNames)}"); } }
void bw_portable_DoWork(object sender, DoWorkEventArgs e) { DisableAll(true); string path = (string)e.Argument; try { List <FileHandle.FileEx> files = new List <FileHandle.FileEx>(); int i = 1; foreach (string item in lstFiles.Items) { Log(string.Format("Encrypting {0} | {1}/{2}", Path.GetFileName(item), i, lstFiles.Items.Count), Type.Notice); FileHandle.FileEx file = new FileHandle.FileEx(); file.name = Path.GetFileName(item); file.data = File.ReadAllBytes(item); files.Add(file); i++; } byte[] rawData = FileHandle.CombineFiles(files.ToArray()); byte[] encryptedData = Encryption.Encrypt(rawData, txtPassword.Text); Log("File(s) encrypted successfully !", Type.Success); string ResFile = Path.Combine(Application.StartupPath, "Encrypted.resources"); using (ResourceWriter Writer = new ResourceWriter(ResFile)) { Writer.AddResource("encfile", encryptedData); Writer.Generate(); } string Source = XProtect.Properties.Resources.stub; Compiler.Compile(Source, path, ResFile, null); File.Delete(ResFile); } catch { Log("Some error occured !", Type.Error); } DisableAll(false); }
public SpecialResourceWriter() { // Load all bunlde IList <IResourceBundle> allBundle = new List <IResourceBundle>(20); allBundle.Add(ResourceBundleFactory.CreateBundle("CanonMarkernote", null, ResourceBundleFactory.USE_TXTFILE)); allBundle.Add(ResourceBundleFactory.CreateBundle("CasioMarkernote", null, ResourceBundleFactory.USE_TXTFILE)); allBundle.Add(ResourceBundleFactory.CreateBundle("Commons", null, ResourceBundleFactory.USE_TXTFILE)); allBundle.Add(ResourceBundleFactory.CreateBundle("ExifInteropMarkernote", null, ResourceBundleFactory.USE_TXTFILE)); allBundle.Add(ResourceBundleFactory.CreateBundle("ExifMarkernote", null, ResourceBundleFactory.USE_TXTFILE)); allBundle.Add(ResourceBundleFactory.CreateBundle("FujiFilmMarkernote", null, ResourceBundleFactory.USE_TXTFILE)); allBundle.Add(ResourceBundleFactory.CreateBundle("GpsMarkernote", null, ResourceBundleFactory.USE_TXTFILE)); allBundle.Add(ResourceBundleFactory.CreateBundle("IptcMarkernote", null, ResourceBundleFactory.USE_TXTFILE)); allBundle.Add(ResourceBundleFactory.CreateBundle("JpegMarkernote", null, ResourceBundleFactory.USE_TXTFILE)); allBundle.Add(ResourceBundleFactory.CreateBundle("KodakMarkernote", null, ResourceBundleFactory.USE_TXTFILE)); allBundle.Add(ResourceBundleFactory.CreateBundle("KyoceraMarkernote", null, ResourceBundleFactory.USE_TXTFILE)); allBundle.Add(ResourceBundleFactory.CreateBundle("NikonTypeMarkernote", null, ResourceBundleFactory.USE_TXTFILE)); allBundle.Add(ResourceBundleFactory.CreateBundle("OlympusMarkernote", null, ResourceBundleFactory.USE_TXTFILE)); allBundle.Add(ResourceBundleFactory.CreateBundle("PanasonicMarkernote", null, ResourceBundleFactory.USE_TXTFILE)); allBundle.Add(ResourceBundleFactory.CreateBundle("PentaxMarkernote", null, ResourceBundleFactory.USE_TXTFILE)); allBundle.Add(ResourceBundleFactory.CreateBundle("SonyMarkernote", null, ResourceBundleFactory.USE_TXTFILE)); IEnumerator <IResourceBundle> enumRb = allBundle.GetEnumerator(); while (enumRb.MoveNext()) { IResourceBundle bdl = enumRb.Current; IDictionary <string, string> idic = bdl.Entries; IDictionaryEnumerator enumDic = (IDictionaryEnumerator)idic.GetEnumerator(); using (var rw = new ResourceWriter(bdl.Fullname + ".resources")) { while (enumDic.MoveNext()) { rw.AddResource((string)enumDic.Key, (string)enumDic.Value); } } } }
private static void BuildResources(XmlElement root) { string outFile = root.GetAttribute("out"); if (string.IsNullOrEmpty(outFile)) { Console.WriteLine("Out file is not specified"); return; } ResourceWriter writer = new ResourceWriter(outFile); foreach (XmlNode nodeI in root.ChildNodes) { XmlElement elementI = nodeI as XmlElement; if (elementI != null) { if (elementI.Name == "icon") { string name = elementI.GetAttribute("name"); if (string.IsNullOrEmpty(name)) { Console.WriteLine("Missing name attribute"); writer.Close(); return; } string src = elementI.GetAttribute("src"); if (string.IsNullOrEmpty(src)) { Console.WriteLine("Missing src attribute"); writer.Close(); return; } writer.AddResource(name, new Icon(src)); } } } writer.Close(); }
public static void GenerateResources() { byte[] buffer = new byte[_RefBuffer.Length]; using (var ms2 = new MemoryStream(buffer, true)) { using (var rw = new ResourceWriter(ms2)) { foreach (var e in s_dict) { string name = e.Key; string values = e.Value; rw.AddResource(name, values); } rw.Generate(); } } bool hError = buffer.SequenceEqual(_RefBuffer); Assert.True(hError, "The generated Resource does not match the reference"); }
[Test] // AddResource (string, byte []) public void AddResource0_Name_Null() { byte [] value = new byte [] { 5, 7 }; MemoryStream ms = new MemoryStream(); ResourceWriter writer = new ResourceWriter(ms); try { writer.AddResource((string)null, value); Assert.Fail("#1"); } catch (ArgumentNullException ex) { Assert.AreEqual(typeof(ArgumentNullException), ex.GetType(), "#2"); Assert.IsNull(ex.InnerException, "#3"); Assert.IsNotNull(ex.Message, "#4"); Assert.IsNotNull(ex.ParamName, "#5"); Assert.AreEqual("name", ex.ParamName, "#6"); } writer.Close(); }
public static void InsertEmployee(string key, string value, string comment) { bool temp = false; for (int i = 0; i < l.Count; i++) { if (l[i].key == key) { temp = true; } } if (temp == false) { l.Add(new ResourceObj(key, value, comment)); } ResourceWriter rsxw = new ResourceWriter(path); for (int i = 0; i < l.Count; i++) { rsxw.AddResource("obj" + i.ToString(), l[i]); } rsxw.Close(); }
public static void Main(string[] args) { String fileName = "genstrings.resources"; if(File.Exists(Environment.CurrentDirectory+"\\" + fileName)) File.Delete(Environment.CurrentDirectory+"\\" + fileName); ResourceWriter writer = new ResourceWriter(fileName); writer.AddResource("English_Text", ReadTextFile("english.txt")); writer.AddResource("Japanese_Text", ReadTextFile("japanese.txt")); writer.AddResource("German_Text", ReadTextFile("german.txt")); writer.AddResource("Arabic_Text", ReadTextFile("arabic.txt")); writer.AddResource("Korean_Text", ReadTextFile("korean.txt")); writer.AddResource("ChineseTra_Text", ReadTextFile("chinesetra.txt")); writer.AddResource("ChineseSim_Text", ReadTextFile("chinesesim.txt")); writer.AddResource("Spanish_Text", ReadTextFile("spanish.txt")); writer.AddResource("Italian_Text", ReadTextFile("italian.txt")); writer.AddResource("French_Text", ReadTextFile("french.txt")); writer.AddResource("Turkish_Text", ReadTextFile("turkish.txt")); writer.AddResource("NorwegianBok_Text", ReadTextFile("norwegianbok.txt")); writer.AddResource("NorwegianNyn_Text", ReadTextFile("norwegiannyn.txt")); writer.Generate(); writer.Close(); }
private static Stream GetResxResourceStream(string resxFilePath) { using (var fs = File.OpenRead(resxFilePath)) { var document = XDocument.Load(fs); var ms = new MemoryStream(); var rw = new ResourceWriter(ms); foreach (var e in document.Root.Elements("data")) { string name = e.Attribute("name").Value; string value = e.Element("value").Value; rw.AddResource(name, value); } rw.Generate(); ms.Seek(0, SeekOrigin.Begin); return(ms); } }
public void AddResource_Stream_Details() { MemoryStream ms = new MemoryStream(); ResourceWriter rw = new ResourceWriter(ms); ResourceStream stream = new ResourceStream("MonoTest"); // Set Position so we can test the ResourceWriter is resetting // it to 0 when generating. stream.Position = 2; rw.AddResource("Name", stream); rw.Generate(); ms.Position = 0; ResourceReader rr = new ResourceReader(ms); string value = GetStringFromResource(rr, "Name"); Assert.AreEqual("MonoTest", value, "#A1"); Assert.AreEqual(false, stream.IsDiposed, "#A2"); // Test the second overload stream.Reset(); ms = new MemoryStream(); rw = new ResourceWriter(ms); rw.AddResource("Name", stream, true); rw.Generate(); ms.Position = 0; rr = new ResourceReader(ms); value = GetStringFromResource(rr, "Name"); Assert.AreEqual("MonoTest", value, "#B1"); Assert.AreEqual(true, stream.IsDiposed, "#B2"); rr.Close(); rw.Close(); stream.Close(); }
public void Save(Stream stream, bool leaveOpen) { using (var writer = new ResourceWriter(stream, leaveOpen)) { if (ResourceType == ResourceType.AnimationPack) { // For AnimationPacks we write a model file header, and then a chunk containing the pack data. writer.WriteFileHeader(ResourceFileIdentifier.Model, Version, ResourceType.ModelPack); writer.WriteResourceChunk(this); return; } writer.WriteFileHeader(ResourceFileIdentifier.Model, Version, ResourceType); switch (ResourceType) { case ResourceType.Epl: // We have to write this to the file so we can remember it when we load it. //writer.WriteBoolean( ( ( Epl ) this ).IncludesProperties ); break; case ResourceType.Node: Node.WriteRecursive(writer, ( Node )this); return; case ResourceType.ChunkType000100F8: { var chunk = ( ChunkType000100F8 )this; writer.WriteInt32(chunk.Data.Length); writer.WriteBytes(chunk.Data); return; } } WriteCore(writer); } }
private void WriteDataToResourceFile(String fileFormat, ResourceWriter resWriter, CultureInfo culture){ ArrayList xmlTable; ArrayList xmlList; Int32 ielementCount; String elementName; StringBuilder resourceHolder; String resourceName; XmlTextReader reader; xmlTable = new ArrayList(); xmlList = new ArrayList(); reader = new XmlTextReader(xmlSchemaFile + "_" + fileFormat + ".xml"); ielementCount=0; while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: if (reader.HasAttributes) { if(++ielementCount>2){ xmlTable.Add(String.Empty); xmlList.Add(reader[0]); } } break; } } reader.Close(); reader = new XmlTextReader(xmlDataFile + "_" + fileFormat + "_" + culture.ToString() + ".xml"); elementName = String.Empty; while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: elementName = reader.Name; break; case XmlNodeType.Text: if(xmlList.Contains(elementName)){ xmlTable[xmlList.IndexOf(elementName)] = (String)xmlTable[xmlList.IndexOf(elementName)] + reader.Value + separator; } break; } } reader.Close(); resourceHolder = new StringBuilder(); foreach(String str111 in xmlList){ resourceHolder.Append((String)xmlTable[xmlList.IndexOf(str111)] + EOL); } resourceName = baseFileName + fileFormat + culture.ToString(); resWriter.AddResource(resourceName, resourceHolder.ToString()); }
public virtual bool runTest() { Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; String strLoc = "Loc_000oo"; ResourceWriter writer; ThreadStart tdst1; Thread[] thdPool; Boolean fLoopExit; try { do { iCountTestcases++; if(File.Exists(Environment.CurrentDirectory+"\\Co3878_A.resources")) File.Delete(Environment.CurrentDirectory+"\\Co3878_A.resources"); writer = new ResourceWriter("Co3878_A.resources"); for(int i=0; i<iNumberOfStringsInFile; i++) writer.AddResource("Key " + i, "Value " + i); writer.Generate(); writer.Close(); iThreadsCompleted = 0; thdPool = new Thread[iNumberOfThreads]; for(int i=0; i<iNumberOfThreads; i++){ tdst1 = new ThreadStart(this.RSMangerForEachThread); thdPool[i] = new Thread(tdst1); } for(int i=0; i<iNumberOfThreads; i++){ thdPool[i].Start(); } do { int numberAlive = 0; fLoopExit = false; Thread.Sleep(100); for(int i=0; i<iNumberOfThreads; i++){ if(thdPool[i].IsAlive) { fLoopExit = true; numberAlive ++; } } }while(fLoopExit); if(iThreadsCompleted != iNumberOfThreads){ iCountErrors++; Console.WriteLine("Err_67423csd! All the thrads didn't execute the function. Expected, " + iNumberOfThreads + " completed, " + iThreadsCompleted); } iCountTestcases++; if(File.Exists(Environment.CurrentDirectory+"\\Co3878_B.resources")) File.Delete(Environment.CurrentDirectory+"\\Co3878_B.resources"); writer = new ResourceWriter("Co3878_B.resources"); for(int i=0; i<iNumberOfStringsInFile; i++) writer.AddResource("Key " + i, "Value " + i); writer.Generate(); writer.Close(); manager = ResourceManager.CreateFileBasedResourceManager("Co3878_B", Environment.CurrentDirectory, null); iThreadsCompleted = 0; thdPool = new Thread[iNumberOfThreads]; for(int i=0; i<iNumberOfThreads; i++){ tdst1 = new ThreadStart(this.RSMangerForAllThreads); thdPool[i] = new Thread(tdst1); } for(int i=0; i<iNumberOfThreads; i++){ thdPool[i].Start(); } do { fLoopExit = false; Thread.Sleep(100); for(int i=0; i<iNumberOfThreads; i++){ if(thdPool[i].IsAlive) fLoopExit = true; } }while(fLoopExit); if(iThreadsCompleted != iNumberOfThreads){ iCountErrors++; Console.WriteLine("Err_7539cd! All the threads didn't execute the function. Expected, " + iNumberOfThreads + " completed, " + iThreadsCompleted); } manager.ReleaseAllResources(); } while (false); } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy! strLoc=="+ strLoc +", exc_general=="+exc_general); } if ( iCountErrors == 0 ) { Console.WriteLine( "paSs. "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases); return true; } else { Console.WriteLine("FAiL! "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums ); return false; } }
private void DoThings() { String[] bogusHeaders; ResourceWriter resWriter; String[] dateInfoCustomFormats; Hashtable dupTable; CultureInfo culture; DateTimeFormatInfo dateInfo; StreamWriter xmlwriter; XmlTextWriter myXmlTextWriter; Calendar otherCalendar; Calendar gregorian; Hashtable calendars; String[] tempFormats; calendars = new Hashtable(); calendars.Add(0x0401, new HijriCalendar()); calendars.Add(0x0404, new TaiwanCalendar()); calendars.Add(0x040D, new HebrewCalendar()); calendars.Add(0x0411, new JapaneseCalendar()); calendars.Add(0x0412, new KoreanCalendar()); calendars.Add(0x041E, new ThaiBuddhistCalendar()); otherCalendar = null; gregorian = new GregorianCalendar(); resWriter = new ResourceWriter(resourceBaseName + ".resources"); resWriter.AddResource(resCultures, cultures); WriteXMLForCultures(cultures); for(int iCul = 0; iCul<cultures.Length; iCul++) { culture = cultures[iCul]; dateInfo = DateTimeFormatInfo.GetInstance(culture); try { otherCalendar = (Calendar)calendars[culture.LCID]; } catch { } bogusHeaders = new String[formalFormats.Length]; for(int i=0; i<bogusHeaders.Length; i++) { bogusHeaders[i] = "AA_" + i; } if(iCul==0) { GenerateXmlSchema(bogusHeaders, fileFormalFormats, false, culture); } if(calendars.ContainsKey(culture.LCID)) { xmlwriter = File.CreateText(xmlDataFile + "_" + fileFormalFormats + "_" + culture.ToString() + "_" + otherCalendarString + ".xml"); myXmlTextWriter = new XmlTextWriter(xmlwriter); myXmlTextWriter.Formatting = Formatting.Indented; myXmlTextWriter.WriteStartElement("NewDataSet"); tempFormats = new String[formalFormats.Length]; formalFormats.CopyTo(tempFormats, 0); for(int i=0; i<tempFormats.Length; i++) { if(Char.IsUpper(tempFormats[i][0])) tempFormats[i] = tempFormats[i] + " "; } WriteRealHeaders(myXmlTextWriter, bogusHeaders, tempFormats); WriteValues(myXmlTextWriter, bogusHeaders, formalFormats, culture, otherCalendar); WriteDataToResourceFile(fileFormalFormats, resWriter, culture, false, true); } xmlwriter = File.CreateText(xmlDataFile + "_" + fileFormalFormats + "_" + culture.ToString() + ".xml"); myXmlTextWriter = new XmlTextWriter(xmlwriter); myXmlTextWriter.Formatting = Formatting.Indented; myXmlTextWriter.WriteStartElement("NewDataSet"); tempFormats = new String[formalFormats.Length]; formalFormats.CopyTo(tempFormats, 0); for(int i=0; i<tempFormats.Length; i++) { if(Char.IsUpper(tempFormats[i][0])) tempFormats[i] = tempFormats[i] + " "; } WriteRealHeaders(myXmlTextWriter, bogusHeaders, tempFormats); WriteValues(myXmlTextWriter, bogusHeaders, formalFormats, culture, gregorian); WriteDataToResourceFile(fileFormalFormats, resWriter, culture, false, false); dateInfoCustomFormats = DateTimeFormatInfo.GetInstance(culture).GetAllDateTimePatterns(); dupTable = new Hashtable(); for(int i=0; i<dateInfoCustomFormats.Length; i++) { try { dupTable.Add(dateInfoCustomFormats[i], null); } catch { } } dateInfoCustomFormats = new String[dupTable.Count]; Int32 iTemp1=0; foreach(String strN in dupTable.Keys) dateInfoCustomFormats[iTemp1++] = strN; bogusHeaders = new String[dateInfoCustomFormats.Length]; for(int i=0; i<bogusHeaders.Length; i++) { bogusHeaders[i] = "AA_" + i; } GenerateXmlSchema(bogusHeaders, fileDateTimePatterns, true, culture); if(calendars.ContainsKey(culture.LCID)) { xmlwriter = File.CreateText(xmlDataFile + "_" + fileDateTimePatterns + "_" + culture.ToString() + "_" + otherCalendarString + ".xml"); myXmlTextWriter = new XmlTextWriter(xmlwriter); myXmlTextWriter.Formatting = Formatting.Indented; myXmlTextWriter.WriteStartElement("NewDataSet"); WriteRealHeaders(myXmlTextWriter, bogusHeaders, dateInfoCustomFormats); WriteValues(myXmlTextWriter, bogusHeaders, dateInfoCustomFormats, culture, otherCalendar); WriteDataToResourceFile(fileDateTimePatterns, resWriter, culture, true, true); } xmlwriter = File.CreateText(xmlDataFile + "_" + fileDateTimePatterns + "_" + culture.ToString() + ".xml"); myXmlTextWriter = new XmlTextWriter(xmlwriter); myXmlTextWriter.Formatting = Formatting.Indented; myXmlTextWriter.WriteStartElement("NewDataSet"); WriteRealHeaders(myXmlTextWriter, bogusHeaders, dateInfoCustomFormats); WriteValues(myXmlTextWriter, bogusHeaders, dateInfoCustomFormats, culture, gregorian); WriteDataToResourceFile(fileDateTimePatterns, resWriter, culture, true, false); bogusHeaders = new String[ourOwnCustomFormats.Length]; for(int i=0; i<bogusHeaders.Length; i++) { bogusHeaders[i] = "AA_" + i; } if(iCul==0) { GenerateXmlSchema(bogusHeaders, fileCustomFormats, false, culture); } if(calendars.ContainsKey(culture.LCID)) { xmlwriter = File.CreateText(xmlDataFile + "_" + fileCustomFormats + "_" + culture.ToString() + "_" + otherCalendarString + ".xml"); myXmlTextWriter = new XmlTextWriter(xmlwriter); myXmlTextWriter.Formatting = Formatting.Indented; myXmlTextWriter.WriteStartElement("NewDataSet"); tempFormats = new String[ourOwnCustomFormats.Length]; ourOwnCustomFormats.CopyTo(tempFormats, 0); for(int i=0; i<tempFormats.Length; i++) { if(ourOwnCustomFormats[i]=="DD") tempFormats[i] = tempFormats[i] + " "; } WriteRealHeaders(myXmlTextWriter, bogusHeaders, tempFormats); WriteValues(myXmlTextWriter, bogusHeaders, ourOwnCustomFormats, culture, otherCalendar); WriteDataToResourceFile(fileCustomFormats, resWriter, culture, false, true); } xmlwriter = File.CreateText(xmlDataFile + "_" + fileCustomFormats + "_" + culture.ToString() + ".xml"); myXmlTextWriter = new XmlTextWriter(xmlwriter); myXmlTextWriter.Formatting = Formatting.Indented; myXmlTextWriter.WriteStartElement("NewDataSet"); tempFormats = new String[ourOwnCustomFormats.Length]; ourOwnCustomFormats.CopyTo(tempFormats, 0); for(int i=0; i<tempFormats.Length; i++) { if(ourOwnCustomFormats[i]=="DD") tempFormats[i] = tempFormats[i] + " "; } WriteRealHeaders(myXmlTextWriter, bogusHeaders, tempFormats); WriteValues(myXmlTextWriter, bogusHeaders, ourOwnCustomFormats, culture, gregorian); WriteDataToResourceFile(fileCustomFormats, resWriter, culture, false, false); } resWriter.Generate(); resWriter.Close(); }
/// <summary> /// This method generates resource files directly using the ResourceWriter class. /// </summary> public void GenerateResourceFiles() { // Generate the New Zealand resource file. ResourceWriter rw = new ResourceWriter(EN_NZRESFILE); rw.AddResource("promptValidDeg", "Please enter a viable outside temperature (-100 to 60)."); rw.AddResource("dist1", "(in kilometres) ==>"); rw.AddResource("degree1", "in Celsius ==>"); rw.AddResource("degree2", "-100"); rw.AddResource("degree3", "60"); rw.Generate(); rw.Close(); Console.WriteLine("Generating resource file: {0}", EN_NZRESFILE); // Generate the Germand resource file. rw = new ResourceWriter(DERESFILE); rw.AddResource("promptName", "Geben Sie Ihren Namen ein ==>"); rw.AddResource("promptAge", "Geben Sie Ihr Alter ein ==>"); rw.AddResource("promptDegrees", "Geben Sie die aktuelle Temperatur ein,"); rw.AddResource("promptMissing", "Stellen Sie sicher, dass Sie einen gültigen Wert eingeben."); rw.AddResource("promptValidAge", "Geben Sie ein gültiges Alter für einen Erwachsenen ein (15 und älter)."); rw.AddResource("promptDist", "Geben Sie an, wie weit Sie zur Arbeit fahren"); rw.AddResource("promptValidDist", "Geben Sie einen gültigen Abstand ein (größer als Null)."); rw.AddResource("promptValidDeg", "Geben Sie eine Außentemperatur ein (-60C bis 60F)."); rw.AddResource("promptEntries", "Sie trugen die folgenden Informationen ein:"); rw.AddResource("dist1", "(in den Kilometern) ==>"); rw.AddResource("degree1", "in Celsius ==>"); rw.AddResource("degree2", "-60"); rw.AddResource("degree3", "60"); rw.AddResource("outputName", "Name:"); rw.AddResource("outputAge", "Alter:"); rw.AddResource("outputDegrees", "Temperatur:"); rw.AddResource("outputDist", "Abstand Zur Arbeit:"); rw.Generate(); rw.Close(); Console.WriteLine("Generating resource file: {0}", DERESFILE); }//GenerateResourceFiles()
public bool runTest() { Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; String strLoc = "Loc_000oo"; String strValue = String.Empty; IDictionaryEnumerator idic; try { ResourceWriter resWriter; ResourceReader resReader; Stream stream = null; MemoryStream ms; FileStream fs; if(File.Exists(Environment.CurrentDirectory+"\\Co5445.resources")) File.Delete(Environment.CurrentDirectory+"\\Co5445.resources"); strLoc = "Loc_20xcy"; stream = null; iCountTestcases++; try { resWriter = new ResourceWriter(stream); iCountErrors++; printerr( "Error_29vc8! ArgumentNullException expected"); } catch ( ArgumentNullException aExc) { } catch ( Exception exc) { iCountErrors++; printerr( "Error_10s9x! ArgumentNullException expected , got exc=="+exc.ToString()); } strLoc = "Loc_3f98d"; new FileStream("Co5445.resources", FileMode.Create).Close(); fs = new FileStream("Co5445.resources", FileMode.Open, FileAccess.Read, FileShare.None); iCountTestcases++; try { resWriter = new ResourceWriter(fs); iCountErrors++; printerr( "Error_2c88s! ArgumentException expected"); } catch (ArgumentException aExc) { } catch ( Exception exc) { iCountErrors++; printerr( "Error_2x0zu! ArgumentException expected, got exc=="+exc.ToString()); } strLoc = "Loc_f0843"; ms = new MemoryStream(); resWriter = new ResourceWriter(ms); resWriter.AddResource("Harrison", "Ford"); resWriter.AddResource("Mark", "Hamill"); resWriter.Generate(); ms.Position = 0; resReader = new ResourceReader(ms); idic = resReader.GetEnumerator(); idic.MoveNext(); iCountTestcases++; if(!idic.Value.Equals("Ford")) { iCountErrors++; printerr( "Error_2d0s9 Expected==Ford, value=="+idic.Value.ToString()); } idic.MoveNext(); iCountTestcases++; if(!idic.Value.Equals("Hamill")) { iCountErrors++; printerr( "Error_2ce80 Expected==Hamill, value=="+idic.Value.ToString()); } strLoc = "Loc_20984"; iCountTestcases++; if(idic.MoveNext()) { iCountErrors++; printerr( "Error_f4094! Should have hit the end of the stream already"); } fs.Close(); strLoc = "Loc_04853fd"; if(File.Exists(Environment.CurrentDirectory+"\\Co5445.resources")) File.Delete(Environment.CurrentDirectory+"\\Co5445.resources"); } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy! strLoc=="+ strLoc +", exc_general=="+exc_general.ToString()); } if ( iCountErrors == 0 ) { Console.WriteLine( "paSs. "+s_strTFName+" ,iCountTestcases=="+iCountTestcases.ToString()); return true; } else { Console.WriteLine("FAiL! "+s_strTFName+" ,iCountErrors=="+iCountErrors.ToString()+" , BugNums?: "+s_strActiveBugNums ); return false; } }
/// <remarks> /// Builds resource files out of the ResAsm format /// </remarks> static void Assemble(string pattern) { string[] files = Directory.GetFiles(Directory.GetCurrentDirectory(), pattern); int linenr = 0; foreach (string file in files) { try { StreamReader reader = new StreamReader(file, new UTF8Encoding()); string resfilename = Path.GetFileNameWithoutExtension(file) + ".resources"; ResourceWriter rw = new ResourceWriter(resfilename); linenr = 0; while (true) { string line = reader.ReadLine(); linenr++; if (line == null) { break; } line = line.Trim(); // skip empty or comment lines if (line.Length == 0 || line[0] == '#') { continue; } // search for a = char int idx = line.IndexOf('='); if (idx < 0) { Console.WriteLine("error in file " + file + " at line " + linenr); continue; } string key = line.Substring(0, idx).Trim(); string val = line.Substring(idx + 1).Trim(); object entryval = null; if (val[0] == '"') { // case 1 : string value val = val.Trim(new char[] {'"'}); StringBuilder tmp = new StringBuilder(); for (int i = 0; i < val.Length; ++i) { switch (val[i]) { // handle the \ char case '\\': ++i; if (i < val.Length) switch (val[i]) { case '\\': tmp.Append('\\'); break; case 'n': tmp.Append('\n'); break; case '\"': tmp.Append('\"'); break; } break; default: tmp.Append(val[i]); break; } } entryval = tmp.ToString(); } else { // case 2 : no string value -> load resource entryval = LoadResource(val); } rw.AddResource(key, entryval); } rw.Generate(); rw.Close(); reader.Close(); } catch (Exception e) { Console.WriteLine("Error in line " + linenr); Console.WriteLine("Error while processing " + file + " :"); Console.WriteLine(e.ToString()); } } }
private void GoDoPictureFormatting(CultureInfo culture, ResourceWriter resWriter) { NumberFormatInfo numInfo = NumberFormatInfo.GetInstance(culture); String[] bogusHeaders = new String[pictureFormats.Length]; for(int i=0; i<bogusHeaders.Length; i++){ bogusHeaders[i] = "AA_" + i; } GenerateXmlSchema(bogusHeaders, strPic); StreamWriter xmlwriter = File.CreateText(xmlDataFile + "_" + strPic + "_" + culture.ToString() + ".xml"); XmlTextWriter myXmlTextWriter = new XmlTextWriter(xmlwriter); myXmlTextWriter.Formatting = Formatting.Indented; myXmlTextWriter.WriteStartElement("NewDataSet"); WriteRealHeaders(myXmlTextWriter, bogusHeaders, pictureFormats); { Int64 value; for(int i=0; i<numberTable.Length; i++){ value = numberTable[i]; myXmlTextWriter.WriteStartElement("Table"); myXmlTextWriter.WriteElementString("Number", value.ToString(numInfo)); for(int j=0; j<bogusHeaders.Length; j++){ myXmlTextWriter.WriteElementString(bogusHeaders[j], value.ToString(pictureFormats[j], numInfo)); } myXmlTextWriter.WriteEndElement(); } } { Decimal value; for(int i=0; i<decimalTable.Length; i++){ value = decimalTable[i]; myXmlTextWriter.WriteStartElement("Table"); myXmlTextWriter.WriteElementString("Number", value.ToString(numInfo)); for(int j=0; j<bogusHeaders.Length; j++){ myXmlTextWriter.WriteElementString(bogusHeaders[j], value.ToString(pictureFormats[j], numInfo)); } myXmlTextWriter.WriteEndElement(); } } { Double value; for(int i=0; i<doubleTable.Length; i++){ value = doubleTable[i]; myXmlTextWriter.WriteStartElement("Table"); myXmlTextWriter.WriteElementString("Number", value.ToString("R", numInfo)); for(int j=0; j<bogusHeaders.Length; j++){ myXmlTextWriter.WriteElementString(bogusHeaders[j], value.ToString(pictureFormats[j], numInfo)); } myXmlTextWriter.WriteEndElement(); } } myXmlTextWriter.WriteEndElement(); myXmlTextWriter.Flush(); myXmlTextWriter.Close(); WriteDataToResourceFile(strPic, resWriter, culture); }
public static string ToResource(string xapFile) { var resourceFile = Path.Combine(Path.GetTempPath(), "SLViewer.resources"); using (var resourceWriter = new ResourceWriter(resourceFile)) { resourceWriter.AddResource("content.xap", File.ReadAllBytes(xapFile)); resourceWriter.Generate(); } return resourceFile; }
private void DoThings() { String[] bogusHeaders; ResourceWriter resWriter; CultureInfo culture; NumberFormatInfo numInfo; StreamWriter xmlwriter; XmlTextWriter myXmlTextWriter; resWriter = new ResourceWriter(resourceBaseName + ".resources"); resWriter.AddResource(resCultures, cultures); for(int iCul = 0; iCul<cultures.Length; iCul++){ culture = cultures[iCul]; numInfo = NumberFormatInfo.GetInstance(culture); if(verbose) Console.WriteLine(culture); if(verbose) Console.WriteLine("Numerical values and its formats"); bogusHeaders = new String[numericalFormats.Length]; for(int i=0; i<bogusHeaders.Length; i++){ bogusHeaders[i] = "AA_" + i; } if(iCul==0){ GenerateXmlSchema(bogusHeaders, strInt); } xmlwriter = File.CreateText(xmlDataFile + "_" + strInt + "_" + culture.ToString() + ".xml"); myXmlTextWriter = new XmlTextWriter(xmlwriter); myXmlTextWriter.Formatting = Formatting.Indented; myXmlTextWriter.WriteStartElement("NewDataSet"); WriteRealHeaders(myXmlTextWriter, bogusHeaders, numericalFormats); WriteValues(myXmlTextWriter, NumberType.Int, bogusHeaders, numericalFormats, numInfo); WriteDataToResourceFile(strInt, resWriter, culture); if(verbose) Console.WriteLine("Decimal values and its formats"); bogusHeaders = new String[decimalFormats.Length]; for(int i=0; i<bogusHeaders.Length; i++){ bogusHeaders[i] = "AA_" + i; } if(iCul==0){ GenerateXmlSchema(bogusHeaders, strDec); } xmlwriter = File.CreateText(xmlDataFile + "_" + strDec + "_" + culture.ToString() + ".xml"); myXmlTextWriter = new XmlTextWriter(xmlwriter); myXmlTextWriter.Formatting = Formatting.Indented; myXmlTextWriter.WriteStartElement("NewDataSet"); WriteRealHeaders(myXmlTextWriter, bogusHeaders, decimalFormats); WriteValues(myXmlTextWriter, NumberType.Decimal, bogusHeaders, decimalFormats, numInfo); WriteDataToResourceFile(strDec, resWriter, culture); if(verbose) Console.WriteLine("Double values and its formats"); bogusHeaders = new String[doubleFormats.Length]; for(int i=0; i<bogusHeaders.Length; i++){ bogusHeaders[i] = "AA_" + i; } if(iCul==0){ GenerateXmlSchema(bogusHeaders, strDbl); } xmlwriter = File.CreateText(xmlDataFile + "_" + strDbl + "_" + culture.ToString() + ".xml"); myXmlTextWriter = new XmlTextWriter(xmlwriter); myXmlTextWriter.Formatting = Formatting.Indented; myXmlTextWriter.WriteStartElement("NewDataSet"); WriteRealHeaders(myXmlTextWriter, bogusHeaders, doubleFormats); WriteValues(myXmlTextWriter, NumberType.Double, bogusHeaders, doubleFormats, numInfo); WriteDataToResourceFile(strDbl, resWriter, culture); if(verbose) Console.WriteLine("Picture values and its formats"); GoDoPictureFormatting(culture, resWriter); } resWriter.Generate(); resWriter.Close(); }
public Boolean runTest() { Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; String strLoc = "Loc_000oo"; String strValue = String.Empty; Co5209AddResource_str_ubArr cc = new Co5209AddResource_str_ubArr(); IDictionaryEnumerator idic; try { do { ResourceWriter resWriter; ResourceReader resReader; int statusBits = 0; int resultBits = 0; Byte[] ubArr = null; if(File.Exists(Environment.CurrentDirectory+"\\Co5209.resources")) File.Delete(Environment.CurrentDirectory+"\\Co5209.resources"); strLoc = "Loc_204gh"; resWriter = new ResourceWriter("Co5209.resources"); strLoc = "Loc_209tj"; try { iCountTestcases++; resWriter.AddResource(null, ubArr); iCountErrors++; printerr("Error_20fhs! Expected Exception not thrown"); } catch (ArgumentException) {} catch (Exception exc) { iCountErrors++; printerr("Error_2t0jg! Unexpected exception exc=="+exc.ToString()); } strLoc = "Loc_t4j80"; ubArr = null; iCountTestcases++; try { resWriter.AddResource("key with null value", ubArr); } catch (Exception exc) { iCountErrors++; printerr("Error_59ufd! Unexpected exc=="+exc.ToString()); } Byte[] ubArr1 = {(Byte)'v', (Byte)'a', (Byte)'l', (Byte)'u', (Byte)'e', (Byte)' ', (Byte)'1',}; Byte[] ubArr2 = {(Byte)'v', (Byte)'a', (Byte)'l', (Byte)'u', (Byte)'e', (Byte)' ', (Byte)'2',}; Byte[] ubArr3 = {(Byte)'v', (Byte)'a', (Byte)'l', (Byte)'u', (Byte)'e', (Byte)' ', (Byte)'3',}; Byte[] ubArr4 = {(Byte)'v', (Byte)'a', (Byte)'l', (Byte)'u', (Byte)'e', (Byte)' ', (Byte)'4',}; Byte[] ubArr5 = {(Byte)'v', (Byte)'a', (Byte)'l', (Byte)'u', (Byte)'e', (Byte)' ', (Byte)'5',}; Byte[] ubArr6 = {(Byte)'v', (Byte)'a', (Byte)'l', (Byte)'u', (Byte)'e', (Byte)' ', (Byte)'6',}; strLoc = "Loc_59ugd"; resWriter.AddResource("key 1", ubArr1); resWriter.AddResource("key 2", ubArr2); resWriter.AddResource("key 3", ubArr3); resWriter.AddResource("key 4", ubArr4); resWriter.AddResource("key 5", ubArr5); resWriter.AddResource("key 6", ubArr6); strLoc = "Loc_230rj"; iCountTestcases++; try { resWriter.AddResource("key 1", ubArr6); iCountErrors++; printerr("Error_2th8e! Names are not unique"); } catch (ArgumentException) {} catch (Exception exc) { iCountErrors++; printerr("Error_298hg! Unexpected exception=="+exc.ToString()); } resWriter.Generate(); iCountTestcases++; if(!File.Exists(Environment.CurrentDirectory+"\\Co5209.resources")) { iCountErrors++; printerr("Error_23094! Expected file was not created"); } resWriter.Close(); strLoc = "Loc_30tud"; resReader = new ResourceReader(Environment.CurrentDirectory+"\\Co5209.resources"); strLoc = "Loc_0576cd"; byte[] btTemp; Boolean fNotEqual; IDictionaryEnumerator resEnumerator = resReader.GetEnumerator(); idic = resReader.GetEnumerator(); while(idic.MoveNext()) { if(idic.Key.Equals("key 1")) { btTemp = (byte[])idic.Value; fNotEqual = false; for(int i=0;i<btTemp.Length; i++) { if(btTemp[i]!=ubArr1[i]) fNotEqual = true; } if(!fNotEqual) statusBits = statusBits | 0x1; } else if(idic.Key.Equals("key 2")) { btTemp = (byte[])idic.Value; fNotEqual = false; for(int i=0;i<btTemp.Length; i++) { if(btTemp[i]!=ubArr2[i]) fNotEqual = true; } if(!fNotEqual) statusBits = statusBits | 0x2; } else if(idic.Key.Equals("key 3")) { btTemp = (byte[])idic.Value; fNotEqual = false; for(int i=0;i<btTemp.Length; i++) { if(btTemp[i]!=ubArr3[i]) fNotEqual = true; } if(!fNotEqual) statusBits = statusBits | 0x4; } else if(idic.Key.Equals("key 4")) { btTemp = (byte[])idic.Value; fNotEqual = false; for(int i=0;i<btTemp.Length; i++) { if(btTemp[i]!=ubArr4[i]) fNotEqual = true; } if(!fNotEqual) statusBits = statusBits | 0x8; } else if(idic.Key.Equals("key 5")) { btTemp = (byte[])idic.Value; fNotEqual = false; for(int i=0;i<btTemp.Length; i++) { if(btTemp[i]!=ubArr5[i]) fNotEqual = true; } if(!fNotEqual) statusBits = statusBits | 0x10; } else if(idic.Key.Equals("key 6")) { btTemp = (byte[])idic.Value; fNotEqual = false; for(int i=0;i<btTemp.Length; i++) { if(btTemp[i]!=ubArr6[i]) fNotEqual = true; } if(!fNotEqual) statusBits = statusBits | 0x20; } } resultBits = 0x1 | 0x2 | 0x4 | 0x8 | 0x10 | 0x20; iCountTestcases++; if(statusBits != resultBits) { iCountErrors++; printerr("Error_238fh! The names are incorrect, StatusBits=="+statusBits); } strLoc = "Loc_t0dds"; iCountTestcases++; if(idic.MoveNext()) { iCountErrors++; printerr("Error_2398r! , There shouldn't have been more elementes : GetValue=="+idic.Value); } resReader.Close(); strLoc = "Loc_957fd"; } while (false); } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy! strLoc=="+ strLoc +", exc_general=="+exc_general); } if ( iCountErrors == 0 ) { Console.WriteLine( "paSs. "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases); return true; } else { Console.WriteLine("FAiL! "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums ); return false; } }