Messages.cs 2.7 KB

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