Messages.cs 2.7 KB

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