예제 #1
0
        public static void UpdateResourceFile(Hashtable data, string path, TranslatorForm form)
        {
            form.TextOutput = "Writing " + path + "...";

            Hashtable resourceEntries = new Hashtable();
            bool check = false;

            //Get existing resources
            ResXResourceReader reader = new ResXResourceReader(path);
            if (reader != null)
            {
                IDictionaryEnumerator id = reader.GetEnumerator();
                foreach (DictionaryEntry d in reader)
                {
                    if (d.Value == null)
                        resourceEntries.Add(d.Key.ToString(), "");
                    else
                        resourceEntries.Add(d.Key.ToString(), d.Value.ToString());
                }
                reader.Close();
            }

            //Modify resources here...
            foreach (String key in data.Keys)
            {
                if (!resourceEntries.ContainsKey(key))
                {

                    String value = data[key].ToString();
                    if (value == null) value = "";

                    resourceEntries.Add(key, value);
                }
            }

            //Write the combined resource file
            ResXResourceWriter resourceWriter = new ResXResourceWriter(path);

            foreach (String key in resourceEntries.Keys)
            {
                resourceWriter.AddResource(key, resourceEntries[key]);
            }
            resourceWriter.Generate();
            resourceWriter.Close();

            //Check if entered correctly
            reader = new ResXResourceReader(path);
            if (reader != null)
            {
                foreach (DictionaryEntry d in reader)
                    foreach (String key in resourceEntries.Keys)
                    {
                        if ((string) d.Key == key && (string) d.Value == (string) resourceEntries[key]) check = true;
                    }
                reader.Close();
            }

            if (check) form.TextOutput = path + " written successfully";
            else form.TextOutput = path + " not written !!";
        }
예제 #2
0
		public void Test ()
		{
			Thread.CurrentThread.CurrentCulture =
					Thread.CurrentThread.CurrentUICulture = new CultureInfo ("de-DE");

			ResXResourceWriter w = new ResXResourceWriter (fileName);
			w.AddResource ("point", new Point (42, 43));
			w.Generate ();
			w.Close ();

			int count = 0;
			ResXResourceReader r = new ResXResourceReader (fileName);
			IDictionaryEnumerator e = r.GetEnumerator ();
			while (e.MoveNext ()) {
				if ((string) e.Key == "point") {
					Assert.AreEqual (typeof (Point), e.Value.GetType (), "#1");
					Point p = (Point) e.Value;
					Assert.AreEqual (42, p.X, "#2");
					Assert.AreEqual (43, p.Y, "#3");
					count++;
				}
			}
			r.Close ();
			Assert.AreEqual (1, count, "#100");
		}
예제 #3
0
 public static void generateResourceFile(string sourceDirectory, string targetResrouceFile)
 {
     IEnumerable<string> files = Directory.EnumerateFiles(sourceDirectory,"*.*",SearchOption.AllDirectories);
     ResXResourceWriter rw=new ResXResourceWriter(targetResrouceFile);
     string baseUI = "";
     string baseCOM = "";
     StringBuilder allACE = new StringBuilder();
     StringBuilder allJS = new StringBuilder();
     StringBuilder allCom = new StringBuilder();
     StringBuilder allUI = new StringBuilder();
     StringBuilder allCSS = new StringBuilder();
     StringBuilder jquery = new StringBuilder();
     string jq_timePicker = "";
     foreach(string file in files){
         if(!file.Contains(".svn")){/* don't include subversion files */
             /* only include certain files. Other files don't get included */
             if(file.EndsWith(".png")||file.EndsWith(".jpg")
             ||file.EndsWith(".gif")||file.EndsWith(".ico")) {
                 rw.AddResource(getRscString(file,sourceDirectory),File.ReadAllBytes(file));
             }else if(file.EndsWith(".js")||file.EndsWith(".html")||
             file.EndsWith(".css")||file.EndsWith(".aspx")||file.EndsWith(".sql")
             ||file.EndsWith(".txt")) {
                 string content = File.ReadAllText(file);
                 if(file.EndsWith(".css")){
                     allCSS.Append(content+Environment.NewLine);
                 } else if(file.EndsWith(".js")) {
                     if(file.ToLower().Contains("ui\\ui.js")){
                         baseUI = content+Environment.NewLine+Environment.NewLine;
                     } else if(file.ToLower().Contains("commerce\\commerce.js")) {
                         baseCOM = content+Environment.NewLine+Environment.NewLine;
                     } else if(file.ToLower().Contains("timepicker\\jquery-timepicker.js")) {
                         jq_timePicker = content + Environment.NewLine + Environment.NewLine;
                     } else if(file.ToLower().Contains("jquery\\jquery")) {
                         jquery.Append(content+Environment.NewLine+Environment.NewLine);
                     } else if(file.ToLower().Contains("ui\\")){
                         allUI.Append(content+Environment.NewLine+Environment.NewLine);
                         allJS.Append(content+Environment.NewLine+Environment.NewLine);
                     } else if(file.ToLower().Contains("ace\\")){
                         allACE.Append(content+Environment.NewLine+Environment.NewLine);
                     } else if(file.ToLower().Contains("commerce\\")){
                         allCom.Append(content+Environment.NewLine+Environment.NewLine);
                         allJS.Append(content+Environment.NewLine+Environment.NewLine);
                     }else{
                         allJS.Append(content+Environment.NewLine+Environment.NewLine);
                     }
                 }
                 rw.AddResource(getRscString(file,sourceDirectory),content);
             } else if(file.ToLower() == "thumbs.db") {
                 File.Delete(file); /* evil */
             }
         }
     }
     rw.AddResource("admin__renditionjs", baseUI + baseCOM + allJS.ToString());
     rw.AddResource("admin__acejs", allACE.ToString());
     rw.AddResource("admin__jqueryjs", jquery.ToString());
     rw.AddResource("admin__renditionUIjs", allACE.ToString() + baseUI + allUI.ToString());
     rw.Generate();
     rw.Close();
 }
예제 #4
0
        public static void CreateResourceFile(String path)
        {
            var pathString = Path.GetDirectoryName(path);
            if (!Directory.Exists(pathString)) System.IO.Directory.CreateDirectory(pathString);

            ResXResourceWriter resourceWriter = new ResXResourceWriter(path);
            resourceWriter.Generate();
            resourceWriter.Close();
        }
    static void Main(string[] args) {
      if (args.Length != 2) {
        Program.PrintUsage();
        return;
      }
      string inputPath = args[0];
      if (!File.Exists(inputPath)) {
        Program.PrintUsage();
        return;
      }
      string outputPath = args[1];
      try {
        if (File.Exists(outputPath)) {
          File.Delete(outputPath);
        }
      } catch {
        Console.WriteLine("Unable to delete the output file. Please make sure file is writable");
        return;
      }
      using (ResXResourceWriter resourceWriter =
          new ResXResourceWriter(outputPath)) {
        using (FileStream fileStream = new FileStream(inputPath,
                                                      FileMode.Open,
                                                      FileAccess.Read,
                                                      FileShare.Read)) {
          using (StreamReader reader = new StreamReader(fileStream)) {
            while (reader.Peek() != -1) {
              string line = reader.ReadLine();
              int equalToIndex = line.IndexOf(Program.EqualTo);
              string key = line.Substring(1, equalToIndex - 3);
              string value = line.Substring(equalToIndex + 3,
                                            line.Length - key.Length - 8);

              if (value.IndexOf(Program.NumText) != -1) {
                // Check if the value obtained contains a text which matches
                // "NUM_*". If it does, replace the NUM_* by {*}.
                int count = Regex.Matches(value, @"NUM_\d").Count;
                for (int i = 0; i < count; ++i) {
                  value = value.Replace(Program.NumText + i, "{" + i + "}");
                }
              }
              resourceWriter.AddResource(key, value);
            }
          }
        }
        resourceWriter.Generate();
      }
    }
예제 #6
0
파일: MainForm.cs 프로젝트: Gevil/Projects
        private void btnSave_Click(object sender, EventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Title = "Save resource file";
            dlg.Filter = "Resource File|*.resx";
            dlg.FileName = cbDestLang.SelectedValue.ToString() + ".resx";
            if (dlg.ShowDialog() != DialogResult.OK) return;

            ResXResourceWriter rsxw = new ResXResourceWriter(dlg.FileName);
            var table = (DataTable) grid.DataSource;
            foreach( DataRow row in table.Rows )
            {
                rsxw.AddResource( row[0].ToString(), row[2].ToString());
            }
            rsxw.Generate();
            rsxw.Close();
        }
예제 #7
0
파일: RootCategory.cs 프로젝트: rsdn/janus
		/// <summary>
		/// Сохранить дерево ресурсов в каталог.
		/// </summary>
		public void Save(string directory)
		{
			ResourceItem[] ris = GetAllItems();
			foreach (CultureInfo ci in GetCultures())
			{
				using (ResXResourceWriter rxrw = new ResXResourceWriter(
					Path.Combine(directory, TreeName
						+ (ci == CultureInfo.InvariantCulture ? "" : "." + ci.TwoLetterISOLanguageName)
						+ ".resx")))
				{
					foreach (ResourceItem ri in ris)
						if (ri.ValueCollection[ci] != null)
							rxrw.AddResource(ri.Name, ri.ValueCollection[ci]);
					rxrw.Generate();
				}
			}
		}
예제 #8
0
        public void GivenThereIsAResxFileWhichFullPathIsHasTheseContents(string p0, Table table)
        {
            using (var fileStream = File.Create(Path.Combine(_testFolder, p0)))
            {
                using (var resxWriter = new ResXResourceWriter(fileStream))
                {
                    foreach (var row in table.Rows)
                    {
                        resxWriter.AddResource(row["Name"], row["Value"]);
                    }

                    resxWriter.Generate();
                    resxWriter.Close();
                }

                fileStream.Close();
            }
        }
예제 #9
0
        public void GenerateResxFile(TextWriter textWriter)
        {
            var enumTables = LoadEnumTables();
            var enumValues = LoadEnumValues(enumTables);

            using (ResXResourceWriter writer = new ResXResourceWriter(textWriter))
            {
                
                foreach (EnumRecord value in enumValues)
                {
                    writer.AddResource(new ResXDataNode(GetDescriptionResKey(value.Name, value.Lookup), value.Description));
                    writer.AddResource(new ResXDataNode(GetLongDescriptionResKey(value.Name, value.Lookup), value.LongDescription));
                }

                writer.Generate();
            }

        }
예제 #10
0
        public static void AddResourceString(string path, string key, string value)
        {
            using (ResXResourceReader reader = new ResXResourceReader(path))
            {
                reader.UseResXDataNodes = true;

                Hashtable resources = new Hashtable();

                using (ResXResourceWriter writer = new ResXResourceWriter(path))
                {
                    ITypeResolutionService iResoulution = null;

                    foreach (DictionaryEntry entry in reader)
                    {
                        if (entry.Value == null)
                        {
                            resources.Add(entry.Key.ToString(), "");
                        }
                        else
                        {
                            // ReSharper disable once ExpressionIsAlwaysNull
                            resources.Add(entry.Key.ToString(),
                                ((ResXDataNode) entry.Value).GetValue(iResoulution).ToString());
                        }

                        ResXDataNode dataNode = (ResXDataNode) entry.Value;

                        if (dataNode != null)
                        {
                            writer.AddResource(dataNode);
                        }
                    }

                    if (!resources.ContainsKey(key))
                    {
                        writer.AddResource(key, value);
                    }

                    writer.Generate();
                }
            }
        }
예제 #11
0
        public static void UpdateResourceFile(Hashtable data, String path)
        {
            Hashtable resourceEntries = new Hashtable();

            //Add all changes...
            foreach (String key in data.Keys)
            {
                String value = data[key].ToString();
                if (value == null) value = "";
                resourceEntries.Add(key, value);
            }

            //Get existing resources
            ResXResourceReader reader = new ResXResourceReader(path);
            if (reader != null)
            {
                IDictionaryEnumerator id = reader.GetEnumerator();
                foreach (DictionaryEntry d in reader)
                {
                    if (!resourceEntries.ContainsKey(d.Key.ToString()))
                    {
                        if (d.Value == null)
                            resourceEntries.Add(d.Key.ToString(), "");
                        else
                            resourceEntries.Add(d.Key.ToString(), d.Value.ToString());
                    }
                }
                reader.Close();
            }

            //Write the combined resource file
            ResXResourceWriter resourceWriter = new ResXResourceWriter(path);

            foreach (String key in resourceEntries.Keys)
            {
                resourceWriter.AddResource(key, resourceEntries[key]);
            }
            resourceWriter.Generate();
            resourceWriter.Close();

        }
        public static void Main()
        {
            System.Resources.ResXResourceWriter resourceWriter = new ResXResourceWriter("Content.resx");
            FileStream contentFile;
            StreamReader fileReader;

            contentFile = new System.IO.FileStream("ResourceHeader.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
            fileReader = new StreamReader(contentFile);
            resourceWriter.AddResource("ResourceHeader", fileReader.ReadToEnd());

            contentFile = new System.IO.FileStream("gplexx.frame", FileMode.Open, FileAccess.Read, FileShare.Read);
            fileReader = new StreamReader(contentFile);
            resourceWriter.AddResource("GplexxFrame", fileReader.ReadToEnd());

            contentFile = new System.IO.FileStream("GplexBuffers.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
            fileReader = new StreamReader(contentFile);
            resourceWriter.AddResource("GplexBuffers", fileReader.ReadToEnd());

            resourceWriter.Generate();
            resourceWriter.Close();
        }
예제 #13
0
		private static bool OutputAltResx(string file, string locale)
		{
			Console.WriteLine("Processing: " + file);	
			ResXResourceReader resxReader = new ResXResourceReader(file);
			FileInfo currentResxFile = new FileInfo(file);
			string newResxFileName = String.Format("{0}.{1}{2}", currentResxFile.FullName.Substring(0, currentResxFile.FullName.Length - 5), locale, currentResxFile.Extension);
			ResXResourceWriter resxWriter = new ResXResourceWriter(newResxFileName);
			foreach (DictionaryEntry resource in resxReader)
			{
				if ("Sidebar.WidthInPixels".Equals(resource.Key))
				{
					resxWriter.AddResource(resource.Key.ToString(), "225");
					continue;
				}
				
				if (resource.Value.GetType() == typeof(string))
					resxWriter.AddResource(resource.Key.ToString(), MungeResource(resource.Value as string,  StaticKeyValue(resource.Key.ToString())));
				else
					resxWriter.AddResource(resource.Key.ToString(), resource.Value);
			}
			resxWriter.Generate();
			resxWriter.Close();		
			return true;
		}
예제 #14
0
        // Write any localized strings to the localized file
        public void Write()
        {
            // Create the new file.
            ResXResourceWriter writer = new ResXResourceWriter(LocalizedFileName);

            // Iterate the list view and write current items.
            foreach (LocString locstr in AllStrings) {
                if (!string.IsNullOrEmpty(locstr.Localized))
                    writer.AddResource(locstr.Name, locstr.Localized);
            }

            // Write all the non-string nodes back to the file.
            foreach (ResXDataNode dataNode in nonStringNodes)
                writer.AddResource(dataNode);

            writer.Generate();
            writer.Close();
        }
예제 #15
0
        static void Main(string[] args)
        {
            Console.WriteLine("Psuedoizer: Adapted from MSDN BugSlayer 2004-Apr i18n Article.");
            if(args.Length < 2)
            {
                Console.WriteLine("Purpose: Takes an English resource file (resx) and creates an artificial");
                Console.WriteLine("         but still readable Euro-like language to exercise your i18n code");
                Console.WriteLine("         without a formal translation.");
                Console.WriteLine(String.Empty);
                Console.WriteLine("Psuedoizer.exe infile outfile [/b]");
                Console.WriteLine("    Example:");
                Console.WriteLine("    Psuedoizer.exe strings.en.resx strings.ja-JP.resx");
                Console.WriteLine("    /b - Include blank resources");
                System.Environment.Exit(1);
            }

            string fileName = args[0];
            string fileSaveName = args[1];
            bool IncludeBlankResources = (args.Length >= 3 && args[2] == "/b");

            // Open the input file.
            ResXResourceReader reader = new ResXResourceReader ( fileName ) ;

            try
            {
                // Get the enumerator.  If this throws an ArguementException
                // it means the file is not a .RESX file.
                IDictionaryEnumerator enumerator = reader.GetEnumerator ( ) ;

                // Allocate the list for this instance.
                SortedList textResourcesList = new SortedList ( ) ;

                // Run through the file looking for only true text related
                // properties and only those with values set.
                foreach ( DictionaryEntry dic in reader )
                {
                    // Only consider this entry if the value is something.
                    if ( null != dic.Value )
                    {
                        // Is this a System.String.
                        if ( "System.String" == dic.Value.GetType().ToString())
                        {
                            String KeyString = dic.Key.ToString ( ) ;

                            // Make sure the key name does not start with the
                            // "$" or ">>" meta characters and is not an empty
                            // string (or we're explicitly including empty strings).
                            if ( ( false == KeyString.StartsWith ( ">>" ) ) &&
                                ( false == KeyString.StartsWith ( "$"  ) ) &&
                                ( IncludeBlankResources || "" != dic.Value.ToString() )  )
                            {
                                // We've got a winner.
                                textResourcesList.Add ( dic.Key , dic.Value ) ;
                            }

                            // Special case the Windows Form "$this.Text" or
                            // I don't get the form titles.
                            if ( 0 == String.Compare ( KeyString,"$this.Text"))
                            {
                                textResourcesList.Add ( dic.Key , dic.Value ) ;
                            }

                        }
                    }
                }

                // It's entirely possible that there are no text strings in the
                // .ResX file.
                if ( textResourcesList.Count > 0 )
                {
                    if ( null != fileSaveName )
                    {
                        // Create the new file.
                        ResXResourceWriter writer =
                            new ResXResourceWriter ( fileSaveName ) ;

                        foreach ( DictionaryEntry textdic in textResourcesList )
                        {
                            writer.AddResource ( textdic.Key.ToString(), Psuedoizer.ConvertToFakeInternationalized(textdic.Value.ToString()));
                        }

                        writer.Generate ( ) ;
                        writer.Close ( ) ;
                        Console.WriteLine("Converted " + textResourcesList.Count + " text resource(s).");
                    }
                }
                else
                {
                    Console.Write("WARNING: No text resources found in " + fileName);
                    System.Environment.Exit(2);
                }
            }
            catch(Exception e)
            {
                Console.Write(e.ToString());
                System.Environment.Exit(1);
            }
        }
		public void ResxFileProcessed ()
		{
			// resources in resx should be present in codecompileunit with correct property type
			string [] unmatchables;
			CodeCompileUnit ccu;
			
			Bitmap bmp = new Bitmap (100, 100);
			MemoryStream wav = new MemoryStream (1000);
			
			string resxFileName = Path.GetTempFileName();
			
			using (ResXResourceWriter writer = new ResXResourceWriter(resxFileName)) {
				writer.AddResource ("astring", "myvalue"); // dont use key of "string" as its a keyword
				writer.AddResource ("bmp", bmp);
				writer.AddResource ("wav", wav);
				writer.Generate ();
			}
			
			ccu = StronglyTypedResourceBuilder.Create (resxFileName,
								"TestRes",
								"TestNamespace",
								"TestResourcesNameSpace",
								provider,
								true,
								out unmatchables);
			
			CodeMemberProperty cmp;
			cmp = StronglyTypedResourceBuilderCodeDomTest.Get<CodeMemberProperty> ("astring", ccu);
			Assert.IsNotNull (cmp);
			Assert.AreEqual ("System.String", cmp.Type.BaseType);
			
			cmp = StronglyTypedResourceBuilderCodeDomTest.Get<CodeMemberProperty> ("wav", ccu);
			Assert.IsNotNull (cmp);
			Assert.AreEqual ("System.IO.UnmanagedMemoryStream", cmp.Type.BaseType);
			
			cmp = StronglyTypedResourceBuilderCodeDomTest.Get<CodeMemberProperty> ("bmp", ccu);
			Assert.IsNotNull (cmp);
			Assert.AreEqual ("System.Drawing.Bitmap", cmp.Type.BaseType);
			
			wav.Close ();
			File.Delete (resxFileName);
		}
예제 #17
0
        private void saveResxFiles(bool askUnsaved)
        {
            try
            {
                if (askUnsaved)
                {
                    if (!unsavedChanges)
                        return;

                    if (DialogResult.No == MessageBox.Show(this, LangHandler.GetString("txtSave1"), LangHandler.GetString("txtSave2"), MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                        return;
                }

                txtComment_Leave(null, EventArgs.Empty);
                txtValue_Leave(null, EventArgs.Empty);

                if (SettingsHandler.Instance.SortByKeyOnSave && dataGridView.Columns.Contains("keys"))
                    dataGridView.Sort(dataGridView.Columns["keys"], ListSortDirection.Ascending);

                for (int column = 1; column < dataGridView.Columns.Count; column++)
                {
                    using (ResXResourceWriter resourceWriter = new ResXResourceWriter(dataGridView.Columns[column].Name))
                    {
                        for (int row = 0; row < dataGridView.Rows.Count; row++)
                        {
                            ResXDataNode currentNode = dataGridView.Rows[row].Cells[column].Tag as ResXDataNode;
                            Object currentValue = dataGridView.Rows[row].Cells[column].Value as Object;
                            bool isReadOnly = dataGridView.Rows[row].Cells[column].ReadOnly;

                            if (currentValue != null && !isReadOnly)
                            {
                                ResXDataNode nodeToAdd = new ResXDataNode((string)dataGridView.Rows[row].Cells["keys"].Value, currentValue);
                                if (currentNode != null) nodeToAdd.Comment = currentNode.Comment;
                                resourceWriter.AddResource(nodeToAdd);
                                continue;
                            }

                            if (currentNode != null && isReadOnly)
                            {
                                resourceWriter.AddResource(currentNode);
                            }
                        }

                        resourceWriter.Generate();
                        resourceWriter.Close();
                    }
                }

                unsavedChanges = false;
                resetColors();
            }
            catch (Exception ex)
            {
            #if (DEBUG)
                MessageBox.Show(this, string.Format("{0}\n\n{1}", ex.Message, ex.StackTrace), LangHandler.GetString("errorSaving"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            #else
                MessageBox.Show(this, ex.Message, LangHandler.GetString("errorSaving"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            #endif
            }
        }
예제 #18
0
            }
            catch(Exception e)
            {
                System.Console.Error.WriteLine("Got exception: {0} while testing {1}",
                    e.Message, fileName);
                return false;
            }
            return true;
        }

        private void BrowseClick(object sender, System.EventArgs e)
        {
            if (sender == btnBrowseForResx)
            {
                if (SFDlg.ShowDialog() != DialogResult.Cancel)
                    txtResxFile.Text = SFDlg.FileName;
            }
            else
            {
                if (OFDlg.ShowDialog() != DialogResult.Cancel)
                    txtZipFile.Text = OFDlg.FileName;
            }
        }

        private void btnCancel_Click(object sender, System.EventArgs e)
        {
예제 #19
0
        /// <summary>
        /// 保存配置数据.如果加载失败,将抛异常
        /// </summary>
        public void Save()
        {
            SecurityOpr secOpr = null;
            StringBuilder sb = null;
            StringWriter stringWriter = null;
            try
            {
                secOpr = new SecurityOpr(GlobalVar.Instanse.SecurityKey);
                sb = new StringBuilder();
                stringWriter = new StringWriter(sb);
                m_Writer = new ResXResourceWriter(stringWriter);
                foreach (KeyValuePair<string, object> item in m_cfgDatas)
                    m_Writer.AddResource(item.Key, item.Value);
                m_Writer.Generate();//将数据写入字符串流

                //将数据进行加密写入文件
                secOpr.WriteToFile(m_StrPath, sb.ToString());
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (m_Writer != null)
                    m_Writer.Close();
                if (stringWriter != null)
                    stringWriter.Close();
            }
        }
예제 #20
0
 public void writeModifiedResX(string modifiedResXFile)
 {
     using (var resourceWriter = new ResXResourceWriter(modifiedResXFile))
     {
         foreach (DictionaryEntry resourceEntry in _resourceEntries)
         {
             var dnode = (ResXDataNode)resourceEntry.Value;
             resourceWriter.AddResource(dnode);
         }
         resourceWriter.Generate();
     }
 }
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        public void Run(string fileName, string fileSaveName)
        {
            // Open the input file.
            ResXResourceReader reader = new ResXResourceReader(fileName);

            try {
                // Get the enumerator.  If this throws an ArguementException
                // it means the file is not a .RESX file.
                IDictionaryEnumerator enumerator = reader.GetEnumerator();

                // Allocate the list for this instance.
                SortedList textResourcesList = new SortedList();

                // Run through the file looking for only true text related
                // properties and only those with values set.
                foreach (DictionaryEntry dic in reader) {
                    // Only consider this entry if the value is something.
                    if (null != dic.Value) {
                        // Is this a System.String.
                        if ("System.String" == dic.Value.GetType().ToString()) {
                            String KeyString = dic.Key.ToString();

                            // Make sure the key name does not start with the
                            // "$" or ">>" meta characters and is not an empty
                            // string.
                            if ((false == KeyString.StartsWith(">>")) &&
                                    (false == KeyString.StartsWith("$")) &&
                                    ("" != dic.Value.ToString())) {
                                // We've got a winner.
                                textResourcesList.Add(dic.Key, dic.Value);
                            }

                            // Special case the Windows Form "$this.Text" or
                            // I don't get the form titles.
                            if (0 == String.Compare(KeyString, "$this.Text")) {
                                textResourcesList.Add(dic.Key, dic.Value);
                            }

                        }
                    }
                }

                // It's entirely possible that there are no text strings in the
                // .ResX file.
                if (textResourcesList.Count > 0) {
                    if (null != fileSaveName) {
                        // Create the new file.
                        ResXResourceWriter writer =
                                new ResXResourceWriter(fileSaveName);

                        foreach (DictionaryEntry textdic in textResourcesList) {
                            writer.AddResource(textdic.Key.ToString(), Psuedoizer.ConvertToFakeInternationalized(textdic.Value.ToString()));
                        }

                        writer.Generate();
                        writer.Close();
                        Console.WriteLine("Converted " + textResourcesList.Count + " text resource(s).");
                    }
                } else {
                    Console.Write("WARNING: No text resources found in " + fileName);
                    System.Environment.Exit(2);
                }
            } catch (Exception e) {
                Console.Write(e.ToString());
                System.Environment.Exit(1);
            }
        }
예제 #22
0
 public static void WriteResX(string fileName, List<ResourceDefinition> lstResDef)
 {
     try
     {
         using (ResXResourceWriter writer = new ResXResourceWriter(fileName))
         {
             foreach (ResourceDefinition obj in lstResDef)
                 writer.AddResource(obj.Key, obj.Value);
             writer.Generate();
         }
     }
     catch { throw new Exception("Error while saving " + fileName); }
 }
예제 #23
0
        private static void TranslateSingleFile(string fileName, string fileSaveName, bool includeBlankResources)
        {
            // Open the input file.
            ResXResourceReader reader = new ResXResourceReader(fileName);
            try
            {
                // Get the enumerator.  If this throws an ArguementException
                // it means the file is not a .RESX file.
                IDictionaryEnumerator enumerator = reader.GetEnumerator();
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine("WARNING: could not parse " + fileName);
                Console.WriteLine("         " + ex.Message);
                return;
            }

            // Allocate the list for this instance.
            SortedList textResourcesList = new SortedList();

            // Run through the file looking for only true text related
            // properties and only those with values set.
            foreach (DictionaryEntry dic in reader)
            {
                // Only consider this entry if the value is something.
                if (null != dic.Value)
                {
                    // Is this a System.String.
                    if ("System.String" == dic.Value.GetType().ToString())
                    {
                        String KeyString = dic.Key.ToString();

                        // Make sure the key name does not start with the
                        // "$" or ">>" meta characters and is not an empty
                        // string (or we're explicitly including empty strings).
                        if ((false == KeyString.StartsWith(">>")) &&
                            (false == KeyString.StartsWith("$")) &&
                            (includeBlankResources || "" != dic.Value.ToString()))
                        {
                            // We've got a winner.
                            textResourcesList.Add(dic.Key, dic.Value);
                        }

                        // Special case the Windows Form "$this.Text" or
                        // I don't get the form titles.
                        if (0 == String.Compare(KeyString, "$this.Text"))
                        {
                            textResourcesList.Add(dic.Key, dic.Value);
                        }

                    }
                }
            }

            // It's entirely possible that there are no text strings in the
            // .ResX file.
            if (textResourcesList.Count > 0)
            {
                if (null != fileSaveName)
                {
                    if (File.Exists(fileSaveName))
                        File.Delete(fileSaveName);

                    // Create the new file.
                    ResXResourceWriter writer =
                        new ResXResourceWriter(fileSaveName);

                    foreach (DictionaryEntry textdic in textResourcesList)
                    {
                        writer.AddResource(textdic.Key.ToString(), Psuedoizer.ConvertToFakeInternationalized(textdic.Value.ToString()));
                    }

                    writer.Generate();
                    writer.Close();
                    Console.WriteLine(String.Format("{0}: converted {1} text resource(s).", fileName, textResourcesList.Count));
                }
            }
            else
            {
                Console.WriteLine("WARNING: No text resources found in " + fileName);
            }
        }
예제 #24
0
        public int AddOrUpdateResource(string key, string value, int forceupdate = 0)
        {
            int result = 0;

            var resx = new List<DictionaryEntry>();
            string resourceFilepath = "D:\\LC\\OCR\\Convertor\\Licence\\info.resx";
            using (var reader = new ResXResourceReader(resourceFilepath))
            {
                resx = reader.Cast<DictionaryEntry>().ToList();
                var existingResource = resx.Where(r => r.Key.ToString() == key).FirstOrDefault();
                if (existingResource.Key == null && existingResource.Value == null) // NEW!
                {
                    resx.Add(new DictionaryEntry() { Key = key, Value = value });
                    result = 1;
                }

                if (forceupdate == 0)
                {
                    if (existingResource.Key != null && (existingResource.Value == null || existingResource.Value == "")) // NEW!
                    {
                        var modifiedResx = new DictionaryEntry() { Key = existingResource.Key, Value = value };
                        resx.Remove(existingResource);  // REMOVING RESOURCE!
                        resx.Add(modifiedResx);  // AND THEN ADDING RESOURCE!
                        result = 1;
                    }
                }
                if (forceupdate == 1)
                {
                    if (existingResource.Key != null) // NEW!
                    {
                        var modifiedResx = new DictionaryEntry() { Key = existingResource.Key, Value = value };
                        resx.Remove(existingResource);  // REMOVING RESOURCE!
                        resx.Add(modifiedResx);  // AND THEN ADDING RESOURCE!
                        result = 1;
                    }

                }
            }
            if (result > 0)
            {
                using (var writer = new ResXResourceWriter(resourceFilepath))
                {
                    resx.ForEach(r =>
                    {
                        // Again Adding all resource to generate with final items
                        writer.AddResource(r.Key.ToString(), r.Value.ToString());
                    });
                    writer.Generate();
                }
            }
            return result;
        }
예제 #25
0
        public static Boolean UpdateResourceFile(String key, String value, String path)
        {
            Hashtable resourceEntries = new Hashtable();

            //Get existing resources
            if (File.Exists(path))
            {
                ResXResourceReader reader = new ResXResourceReader(path);
                if (reader != null)
                {
                    IDictionaryEnumerator id = reader.GetEnumerator();
                    foreach (DictionaryEntry d in reader)
                    {
                        if (d.Value == null)
                            resourceEntries.Add(d.Key.ToString(), "");
                        else
                            resourceEntries.Add(d.Key.ToString(), d.Value.ToString());
                    }
                    reader.Close();
                }
            }
            //Modify resources here...
            var updDone = false;
                if (resourceEntries.ContainsKey(key))
                {
                    if ((string) resourceEntries[key] != value)
                    {
                        resourceEntries[key] = value;
                        updDone = true;
                    }
                }
                else
                {
                    resourceEntries.Add(key,value);
                    updDone = true;
                }

            //Write the combined resource file
            if (updDone)
            {
                ResXResourceWriter resourceWriter = new ResXResourceWriter(path);

                foreach (String key2 in resourceEntries.Keys)
                {
                    resourceWriter.AddResource(key2, resourceEntries[key2]);
                }
                resourceWriter.Generate();
                resourceWriter.Close();
            }
            return updDone;
        }
예제 #26
0
 /// <summary>
 /// Write a ResX file to disk
 /// </summary>
 /// <param name="fileName"></param>
 protected void WriteResX(string fileName, Dictionary<string, string> dict)
 {
     try
     {
         using (ResXResourceWriter writer = new ResXResourceWriter(fileName))
         {
             foreach (string key in dict.Keys)
                 writer.AddResource(key, dict[key]);
             writer.Generate();
         }
     }
     catch { throw new Exception("Error while saving " + fileName); }
 }
예제 #27
0
 public void GenerateAll()
 {
     StringBuilder sb = new StringBuilder();
     foreach (PringlesCopyCollection collection in ParsedCopyDeck)
     {
         string countryCode = collection.CountryCode.Replace("_", "-");
         string[] countryCodeParts = countryCode.Split('-');
         if (countryCodeParts.Count() != 2)
         {
             sb.AppendLine("Not a valid country code: " + countryCode);
             continue;
         }
         else
         {
             countryCodeParts[1] = countryCodeParts[1].ToUpperInvariant();
             countryCode = countryCodeParts[0] + "-" + countryCodeParts[1];
         }
         if (collection.Copy.Count == 0)
         {
             sb.AppendLine("Empty copy for: " + countryCode);
             continue;
         }
         using (IResourceWriter writer = new ResXResourceWriter((Path + @"\SiteCopy." + countryCode + ".resx").Replace(" ", "")))
         {
             foreach (LocalisationTagValuePair item in collection.Copy)
             {
                 try
                 {
                     item.Tag = item.Tag.Replace(" ", "_");
                     if(Regex.IsMatch(item.Tag, @"^\d"))
                     {
                         int separatorIndex = item.Tag.IndexOf("_");
                         string prefix = item.Tag.Substring(0, separatorIndex);
                         item.Tag = item.Tag.Remove(0, separatorIndex);
                         item.Tag = (item.Tag + '_' + prefix).TrimEnd('_').TrimStart('_');
                         item.Tag = item.Tag.Trim();
                     }
                     writer.AddResource(item.Tag, item.Value);
                 }
                 catch (Exception e)
                 {
                     sb.AppendLine(string.Format("{0}: Error while parsing {1}, error type: {2}", collection.CountryCode, item.Tag, e.Message));
                     continue;
                 }
             }
             writer.Generate();
         }
     }
     ErrorLog = sb.ToString();
 }
예제 #28
0
		public void AddResource_WithComment ()
		{
			ResXResourceWriter w = new ResXResourceWriter (fileName);
			ResXDataNode node = new ResXDataNode ("key", "value");
    			node.Comment = "comment is preserved";
			w.AddResource (node);
			w.Generate ();
			w.Close ();

			ResXResourceReader r = new ResXResourceReader (fileName);
			ITypeResolutionService typeres = null;
			r.UseResXDataNodes = true;
			
			int count = 0;
			foreach (DictionaryEntry o in r)
			{
				string key = o.Key.ToString();
				node = (ResXDataNode)o.Value;
				string value = node.GetValue (typeres).ToString ();
				string comment = node.Comment;

				Assert.AreEqual ("key", key, "key");
				Assert.AreEqual ("value", value, "value");
				Assert.AreEqual ("comment is preserved", comment, "comment");
				Assert.AreEqual (0, count, "too many nodes");
				count++;
			}
			r.Close ();

			File.Delete (fileName);
		}
예제 #29
0
		public void SaveFile(string filename, Stream stream)
		{
			switch (Path.GetExtension(filename).ToLowerInvariant()) {
					
					// write XML resource
				case ".resx":
					ResXResourceWriter rxw = new ResXResourceWriter(stream);
					foreach (KeyValuePair<string, ResourceItem> entry in resources) {
						if (entry.Value != null) {
							ResourceItem item = entry.Value;
							rxw.AddResource(item.Name, item.ResourceValue);
						}
					}
					foreach (KeyValuePair<string, ResourceItem> entry in metadata) {
						if (entry.Value != null) {
							ResourceItem item = entry.Value;
							rxw.AddMetadata(item.Name, item.ResourceValue);
						}
					}
					rxw.Generate();
					rxw.Close();
					break;
					
					// write default resource
				default:
					ResourceWriter rw = new ResourceWriter(stream);
					foreach (KeyValuePair<string, ResourceItem> entry in resources) {
						ResourceItem item = (ResourceItem)entry.Value;
						rw.AddResource(item.Name, item.ResourceValue);
					}
					rw.Generate();
					rw.Close();
					break;
			}
		}
예제 #30
0
		public void TestWriter ()
		{
			ResXResourceWriter w = new ResXResourceWriter (fileName);
			w.AddResource ("String", "hola");
			w.AddResource ("String2", (object) "hello");
			w.AddResource ("Int", 42);
			w.AddResource ("Enum", PlatformID.Win32NT);
			w.AddResource ("Convertible", new Point (43, 45));
			w.AddResource ("Serializable", new ArrayList (new byte [] { 1, 2, 3, 4 }));
			w.AddResource ("ByteArray", new byte [] { 12, 13, 14 });
			w.AddResource ("ByteArray2", (object) new byte [] { 15, 16, 17 });
			w.AddResource ("IntArray", new int [] { 1012, 1013, 1014 });
			w.AddResource ("StringArray", new string [] { "hello", "world" });
			w.AddResource ("Image", new Bitmap (1, 1));
			w.AddResource ("StrType", new MyStrType ("hello"));
			w.AddResource ("BinType", new MyBinType ("world"));

			try {
				w.AddResource ("NonSerType", new MyNonSerializableType ());
				Assert.Fail ("#0");
			} catch (InvalidOperationException) {
			}

			w.Generate ();
			w.Close ();

			ResXResourceReader r = new ResXResourceReader (fileName);
			Hashtable h = new Hashtable ();
			foreach (DictionaryEntry e in r) {
				h.Add (e.Key, e.Value);
			}
			r.Close ();

			Assert.AreEqual ("hola", (string) h ["String"], "#1");
			Assert.AreEqual ("hello", (string) h ["String2"], "#2");
			Assert.AreEqual (42, (int) h ["Int"], "#3");
			Assert.AreEqual (PlatformID.Win32NT, (PlatformID) h ["Enum"], "#4");
			Assert.AreEqual (43, ((Point) h ["Convertible"]).X, "#5");
			Assert.AreEqual (2, (byte) ((ArrayList) h ["Serializable"]) [1], "#6");
			Assert.AreEqual (13, ((byte []) h ["ByteArray"]) [1], "#7");
			Assert.AreEqual (16, ((byte []) h ["ByteArray2"]) [1], "#8");
			Assert.AreEqual (1013, ((int []) h ["IntArray"]) [1], "#9");
			Assert.AreEqual ("world", ((string []) h ["StringArray"]) [1], "#10");
			Assert.AreEqual (typeof (Bitmap), h ["Image"].GetType (), "#11");
			Assert.AreEqual ("hello", ((MyStrType) h ["StrType"]).Value, "#12");
			Assert.AreEqual ("world", ((MyBinType) h ["BinType"]).Value, "#13");

			File.Delete (fileName);
		}