Ejemplo n.º 1
0
        public void UpdateResxWithChanges(string newResxPath)
        {
            var newFile = new FileInfo(newResxPath);
            if (newFile.Exists)
                newFile.Delete();

            var addedKeys = _resourcesAdded.Select(pair => pair.Key);
            var removedKeys = _resourcesRemoved.Select(pair => pair.Key);

            using(var reader = new ResXResourceReader(_sourceResxPath))
            using(var writer = new ResXResourceWriter(newResxPath))
            {
                foreach (DictionaryEntry resourceEntry in reader)
                {
                    string currentKey = (string)resourceEntry.Key;
                    if (addedKeys.Contains(currentKey))
                        continue;
                    if (removedKeys.Contains(currentKey))
                        continue;

                    var modifiedResource = _resourcesModified.FirstOrDefault(mod => mod.ResourceName == currentKey);
                    if (modifiedResource != null)
                        writer.AddResource(currentKey, modifiedResource.NewValue);
                    else
                        writer.AddResource(currentKey, resourceEntry.Value);
                }

                _resourcesAdded.ForEach(res => writer.AddResource(res.Key, res.Value));
            }
        }
Ejemplo n.º 2
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 !!";
        }
 public virtual void Shutdown() {
     if (resources != null) {
         using (var resourceWriter = new ResXResourceWriter(resourceFile)) {
             resources.ForEach(kvp => resourceWriter.AddResource(kvp.Key, kvp.Value));
         }
     }
 }
Ejemplo n.º 4
0
 protected void Op1_Click(object sender, EventArgs e) {
   List<string> files = new List<string>();
   foreach (LocPageGroup grp in groups().Where(g => g != LocPageGroup.newEA)) {
     GenResxContext ctx = new GenResxContext(grp);
     foreach (string s in TradosLib.GenResx(ctx)) files.Add(s);
     LocCfgPageGroupFilter group = LocCfg.Instance().findPageGroup(grp);
     //CSharp resources
     string globalRes = group.GlobalResourcePath;
     if (ctx.toTrans.Count > 0) {
       LowUtils.AdjustFileDir(globalRes);
       using (ResXResourceWriter wr = new ResXResourceWriter(globalRes))
         foreach (TradosLib.resxNameValue nv in ctx.toTrans)
           wr.AddResource(nv.Name, nv.Value);
       files.Add(globalRes);
     } else if (File.Exists(globalRes))
       File.Delete(globalRes);
     //JS resources
     string globalResJS = group.GlobalResourcePathJS;
     if (ctx.toTransJS.Count > 0) {
       LowUtils.AdjustFileDir(globalResJS);
       using (ResXResourceWriter wr = new ResXResourceWriter(globalResJS))
         foreach (TradosLib.resxNameValue nv in ctx.toTransJS)
           wr.AddResource(nv.Name, nv.Value);
       files.Add(globalResJS);
     } else if (File.Exists(globalResJS))
       File.Delete(globalResJS);
   }
   string[] filesArr = (from LocPageGroup grp in groups() from string s in TradosLib.oper1(grp) select s).ToArray();
   CountLab.Text = filesArr.Length.ToString();
   LogRep.DataSource = files; LogRep.DataBind();
 }
Ejemplo n.º 5
0
 public static void Convert(string jsonFile, string resxFile)
 {
     resxKey.Clear();
     JObject jsonJObject = JObject.Parse(File.ReadAllText(jsonFile));
     if (jsonJObject != null)
         using (ResXResourceWriter resx = new ResXResourceWriter(resxFile))
         {
             foreach (var property in jsonJObject.Properties())
             {
                 if (property.HasValues)
                 {
                     foreach (var childToken in property.Children())
                     {
                         ProcessJtoken(resx, childToken);
                     }
                 }
                 else
                 {
                     var key = property.Name.ToLower();
                     if (!resxKey.Contains(key))
                     {
                         resxKey.Add(key);
                         resx.AddResource(property.Name, property.Value);
                     }
                 }
             }
         }
 }
 private void WorkbookToResx(HSSFWorkbook workbook, string sheetName)
 {
     var sheet = NpoiHelper.GetSheet(workbook, sheetName);
     var cultureRow = NpoiHelper.GetRow(sheet, CultureRowNum);
     for (int cultureColumnIndex = 1; cultureColumnIndex < cultureRow.LastCellNum; cultureColumnIndex++)
     {
         string culture = cultureRow.GetCell(cultureColumnIndex, MissingCellPolicy.CREATE_NULL_AS_BLANK).StringCellValue;
         var resourceFile = Path.Combine(_outputPath, sheetName + "." + culture + ".resx");
         if(culture == _rootCulture)
         {
             resourceFile = Path.Combine(_outputPath, sheetName + ".resx");
         }
         using (var resxWriter = new ResXResourceWriter(resourceFile))
         {
             for (var rowIndex = 1; rowIndex <= sheet.LastRowNum; rowIndex++)
             {
                 var row = NpoiHelper.GetRow(sheet, rowIndex);
                 var valueRow = row.GetCell(cultureColumnIndex);
                 if (valueRow != null)
                 {
                     resxWriter.AddResource(
                         row.GetCell(NameColumnNum, MissingCellPolicy.CREATE_NULL_AS_BLANK).StringCellValue,
                         valueRow.StringCellValue);
                 }
             }
         }
     }
 }
Ejemplo n.º 7
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");
		}
Ejemplo n.º 8
0
        private void TranslateFile(string filename, string locale, string newDir)
        {
            string shortName = Path.GetFileName(filename);
            string nameWithoutExt = Path.GetFileNameWithoutExtension(filename);
            string newname = nameWithoutExt + "." + locale + ".resx";
            newname = newDir + "\\" + newname;

            //if file already exists
            bool fileExists = File.Exists(newname);
            Dictionary<string, string> existing = new Dictionary<string, string>();
            if (fileExists)
            {
                Console.WriteLine("File " + newname + " already exists. Existing resources in it will be preserved.");
                //get existing keys list
                ResXResourceReader readerNewFile = new ResXResourceReader(newname);
                foreach (DictionaryEntry d in readerNewFile)
                    existing.Add(d.Key.ToString(), d.Value.ToString());
                readerNewFile.Close();
            }
            else
            {
                Console.WriteLine("Creating file " + newname);
            }

            Console.WriteLine("Translating file " + shortName + " to " + locale + "....");

            Application.DoEvents(); //I know its bad but can't go multithreading, since I have to update UI

            ResXResourceReader reader = new ResXResourceReader(filename);
            ResXResourceWriter writer = new ResXResourceWriter(newname);
            foreach (DictionaryEntry d in reader)
            {
                //leave existing text intact (if its not empty)
                if (fileExists
                    && existing.Keys.Contains(d.Key.ToString())
                    && !string.IsNullOrEmpty(existing[d.Key.ToString()]))
                {
                    writer.AddResource(d.Key.ToString(), existing[d.Key.ToString()]);
                }
                else
                {
                    string originalString = d.Value.ToString();
                    if (!string.IsNullOrEmpty(originalString.Trim()))
                    {
                        string langPair = "hu|" + LanguageNamesList[locale];
                        //string translatedString = GoogleTranslate.TranslateText(originalString, langPair);

                        string translatedString = GoogleTranslate.TranslateGoogle(originalString, "hu", LanguageNamesList[locale]);

                        Console.WriteLine("[" + originalString + " -> " + translatedString + "]");

                        writer.AddResource(d.Key.ToString(), translatedString);
                        //Thread.Sleep(100); //to prevent spam detector at google
                    }
                }
            }
            writer.Close();
            reader.Close();
        }
Ejemplo n.º 9
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();
 }
Ejemplo n.º 10
0
 protected override void Generate()
 {
     using (var resx = new ResXResourceWriter (Writer)) {
         foreach (var resource_string in GetAllResourceStrings ()) {
             resx.AddResource (new ResXDataNode (resource_string.Id, resource_string.Translated));
         }
     }
 }
Ejemplo n.º 11
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();
        }
Ejemplo n.º 12
0
 public static void AddResource(string path, string key, string value)
 {
     var dict = ReadAllResources(path);
     using (var writer = new ResXResourceWriter(path))
     {
         dict[key] = value;
         foreach (var item in dict)
             writer.AddResource(item.Key, item.Value);
     }
 }
 public static void Update(string resourcePath, string key, string value)
 {
     if (!File.Exists(resourcePath))
     {
         return;
     }
     using (ResXResourceWriter resourceWriter = new ResXResourceWriter(resourcePath))
     {
     }
 }
Ejemplo n.º 14
0
		public override void Create(DecompileContext ctx) {
			var list = ReadResourceEntries(ctx);

			using (var writer = new ResXResourceWriter(Filename, TypeNameConverter)) {
				foreach (var t in list) {
					ctx.CancellationToken.ThrowIfCancellationRequested();
					writer.AddResource(t);
				}
			}
		}
        public void WriteToFile(string fileName)
        {
            using (var resxWriter = new ResXResourceWriter (fileName)) {

                Resources.ForEach (resxWriter.AddResource);

                if (Resources.Count == 0) {
                    resxWriter.AddMetadata ("", "");
                }
            }
        }
Ejemplo n.º 16
0
        public void ExportFromDatabase(string exportPath)
        {
            var allRecords = new DbFunctions(_connectionString).GetAllResources();

            foreach (ResourceRecord record in allRecords)
            {
                using (ResXResourceWriter writer = new ResXResourceWriter(GetExportPath(exportPath, record)))
                {
                    writer.AddResource(record.Key, record.Value);
                }
            }
        }
Ejemplo n.º 17
0
 public void BuildResX(string outputPath)
 {
     using (ResXResourceWriter w2 = new ResXResourceWriter(outputPath))
     {
         foreach (Item item in _items)
         {
             ResXDataNode node = new ResXDataNode(item.Name, item.Value);
             node.Comment = item.Comment;
             w2.AddResource(item.Name, node);
         }
     }
 }
Ejemplo n.º 18
0
        public override string GenerateOutputFile(LocalizedEntityBlock[] blocks)
        {
            var ms = new MemoryStream();

            using (var resxw = new ResXResourceWriter(ms))
                foreach (var block in blocks)
                    foreach (var r in block.LocalizationGridRows)
                        resxw.AddResource(r.LocalizableProperty.EntityName, r.Value);

            var array = ms.ToArray();
            return Encoding.UTF8.GetString(array, 3, array.Length - 3);
        }
Ejemplo n.º 19
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();
     }
 }
Ejemplo n.º 20
0
 protected override void Generate()
 {
     using (var resx = new ResXResourceWriter (Writer)) {
         foreach (var localized_string in Strings) {
             foreach (var resource_string in GetResourceStrings (localized_string)) {
                 if (!HasResourceStringBeenGenerated (resource_string)) {
                     MarkResourceStringAsGenerated (resource_string);
                     resx.AddResource (new ResXDataNode (resource_string.Id, resource_string.Translated));
                 }
             }
         }
     }
 }
        public static ProvisioningTemplate SaveResourceValues(ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
        {
            var tempFolder = System.IO.Path.GetTempPath();

            var languages = ResourceTokens.Select(t => t.Item2).Distinct();
            foreach (int language in languages)
            {
                var culture = new CultureInfo(language);

                var resourceFileName = System.IO.Path.Combine(tempFolder, string.Format("{0}.{1}.resx", creationInfo.ResourceFilePrefix, culture.Name));
                if (System.IO.File.Exists(resourceFileName))
                {
                    // Read existing entries, if any
                    using (ResXResourceReader resxReader = new ResXResourceReader(resourceFileName))
                    {
                        foreach (DictionaryEntry entry in resxReader)
                        {
                            // find if token is already there
                            var existingToken = ResourceTokens.FirstOrDefault(t => t.Item1 == entry.Key.ToString() && t.Item2 == language);
                            if (existingToken == null)
                            {
                                ResourceTokens.Add(new Tuple<string, int, string>(entry.Key.ToString(), language, entry.Value as string));
                            }
                        }
                    }
                }

            

                // Create new resource file
                using (ResXResourceWriter resx = new ResXResourceWriter(resourceFileName))
                {
                    foreach (var token in ResourceTokens.Where(t => t.Item2 == language))
                    {

                        resx.AddResource(token.Item1, token.Item3);
                    }
                }

                template.Localizations.Add(new Localization() { LCID = language, Name = culture.NativeName, ResourceFile = string.Format("{0}.{1}.resx", creationInfo.ResourceFilePrefix, culture.Name) });

                // Persist the file using the connector
                using (FileStream stream = System.IO.File.Open(resourceFileName, FileMode.Open))
                {
                    creationInfo.FileConnector.SaveFileStream(string.Format("{0}.{1}.resx", creationInfo.ResourceFilePrefix, culture.Name), stream);
                }
                // remove the temp resx file
                System.IO.File.Delete(resourceFileName);
            }
            return template;
        }
Ejemplo n.º 22
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();
 }
Ejemplo n.º 23
0
		/// <summary>
		/// Update all .resx in a project.
		/// </summary>
		public static void UpdateResourceFiles(CompilableProject project)
		{
			foreach (var resXFile in project.Items.OfType<FileProjectItem>().Where(f => ".resx".Equals(Path.GetExtension(f.FileName), StringComparison.OrdinalIgnoreCase))) {
				using (var buffer = new MemoryStream()) {
					using (var reader = new ResXResourceReader(resXFile.FileName) { UseResXDataNodes = true })
					using (var writer = new ResXResourceWriter(buffer, t => ConvertTypeName(t, resXFile.FileName, project))) {
						foreach (DictionaryEntry entry in reader) {
							writer.AddResource(entry.Key.ToString(), entry.Value);
						}
					}
					File.WriteAllBytes(resXFile.FileName, buffer.ToArray());
				}
			}
		}
Ejemplo n.º 24
0
		public void SaveAsResx(string filename, bool includeDescriptions)
		{
			using (ResXResourceWriter writer = new ResXResourceWriter(filename)) {
				foreach (ResourceEntry entry in Entries.Values.OrderBy(e => e.Key, StringComparer.OrdinalIgnoreCase)) {
					string normalizedValue = entry.Value.Replace("\r", "").Replace("\n", Environment.NewLine);
					if (includeDescriptions) {
						string normalizedDescription = entry.Description.Replace("\r", "").Replace("\n", Environment.NewLine);
						writer.AddResource(new ResXDataNode(entry.Key, normalizedValue) { Comment = normalizedDescription });
					} else {
						writer.AddResource(entry.Key, normalizedValue);
					}
				}
			}
		}
Ejemplo n.º 25
0
        private static void GenerateQuoatationFile(ParserBase parserBase)
        {
            IList<Quoatation> quotationList = parserBase.Parse();

            var resourcePrefix = parserBase.FileName;
            var fileName = parserBase.FileName + ".resx";
            using (var resx = new ResXResourceWriter(fileName))
            {
                for (int i = 0; i < quotationList.Count(); i++)
                {
                    //var json = JsonConvert.SerializeObject(quotationList[i]);
                    resx.AddResource(string.Format("{0}_{1}", resourcePrefix, i), quotationList[i].Text);
                }
            }
        }
Ejemplo n.º 26
0
    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();
      }
    }
Ejemplo n.º 27
0
        private static void Create(ResourceInfo resource)
        {
            var path = resource.Path;

            using (var fs = File.Create(path))
            using (var writer = new ResXResourceWriter(fs))
            {
                foreach (var item in resource.Strings)
                {
                    writer.AddResource(
                        item.Key, item.Value);
                }
            }

            Console.WriteLine("Created new resource {0}!", path);
        }
Ejemplo n.º 28
0
		protected ResXDataNode GetNodeFromResXReader (ResXDataNode node)
		{
			StringWriter sw = new StringWriter ();
			using (ResXResourceWriter writer = new ResXResourceWriter (sw)) {
				writer.AddResource (node);
			}

			StringReader sr = new StringReader (sw.GetStringBuilder ().ToString ());

			using (ResXResourceReader reader = new ResXResourceReader (sr)) {
				reader.UseResXDataNodes = true;
				IDictionaryEnumerator enumerator = reader.GetEnumerator ();
				enumerator.MoveNext ();

				return ((DictionaryEntry) enumerator.Current).Value as ResXDataNode;
			}
		}
Ejemplo n.º 29
0
        private void WriteResources(string userCodePath, string resourcesPath, IDictionary<string, object> resources)
        {
            Contract.Requires(!string.IsNullOrEmpty(userCodePath));
            Contract.Requires(!string.IsNullOrEmpty(resourcesPath));
            Contract.Requires(resources != null);

            var absoluteResourcesPath = Path.Combine(_command.Project.GetProjectDir(), resourcesPath);

            _command.Project.EditFile(resourcesPath);

            using (var writer = new ResXResourceWriter(absoluteResourcesPath))
            {
                resources.Each(i => writer.AddResource(i.Key, i.Value));
            }

            _command.Project.AddFile(resourcesPath);
        }
Ejemplo n.º 30
0
        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();
        }