Messages.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text.RegularExpressions;
  7. namespace NLangDetect.Core.Utils
  8. {
  9. public static class Messages
  10. {
  11. private static readonly Dictionary<string, string> _messages;
  12. static Messages()
  13. {
  14. _messages = LoadMessages();
  15. }
  16. public static string getString(string key)
  17. {
  18. string value;
  19. return
  20. _messages.TryGetValue(key, out value)
  21. ? value
  22. : string.Format("!{0}!", key);
  23. }
  24. private static Dictionary<string, string> LoadMessages()
  25. {
  26. var manifestName = typeof(Messages).Assembly.GetManifestResourceNames().FirstOrDefault(i => i.IndexOf("messages.properties", StringComparison.Ordinal) != -1);
  27. Stream messagesStream =
  28. typeof(Messages).Assembly
  29. .GetManifestResourceStream(manifestName);
  30. if (messagesStream == null)
  31. {
  32. throw new InternalException(string.Format("Couldn't get embedded resource named '{0}'.", manifestName));
  33. }
  34. using (messagesStream)
  35. using (var sr = new StreamReader(messagesStream))
  36. {
  37. var messages = new Dictionary<string, string>();
  38. while (!sr.EndOfStream)
  39. {
  40. string line = sr.ReadLine();
  41. if (string.IsNullOrEmpty(line))
  42. {
  43. continue;
  44. }
  45. string[] keyValue = line.Split('=');
  46. if (keyValue.Length != 2)
  47. {
  48. throw new InternalException(string.Format("Invalid format of the 'Messages.properties' resource. Offending line: '{0}'.", line.Trim()));
  49. }
  50. string key = keyValue[0];
  51. string value = UnescapeUnicodeString(keyValue[1]);
  52. messages.Add(key, value);
  53. }
  54. return messages;
  55. }
  56. }
  57. /// <remarks>
  58. /// Taken from: http://stackoverflow.com/questions/1615559/converting-unicode-strings-to-escaped-ascii-string/1615860#1615860
  59. /// </remarks>
  60. private static string UnescapeUnicodeString(string s)
  61. {
  62. if (s == null)
  63. {
  64. return null;
  65. }
  66. return
  67. Regex.Replace(
  68. s,
  69. @"\\u(?<Value>[a-zA-Z0-9]{4})",
  70. match => ((char)int.Parse(match.Groups["Value"].Value, NumberStyles.HexNumber)).ToString());
  71. }
  72. }
  73. }