PageRenderTime 54ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/Gettext.CsUtils/Core/Gettext.Cs/Resource/FileBasedResourceManager.cs

https://code.google.com/p/gettext-cs-utils/
C# | 295 lines | 192 code | 40 blank | 63 comment | 37 complexity | eea468ef0c196d55d85739108bc675af MD5 | raw file
  1. /**
  2. * gettext-cs-utils
  3. *
  4. * Copyright 2011 Manas Technology Solutions
  5. * http://www.manas.com.ar/
  6. *
  7. * This library is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * This library is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with this library. If not, see <http://www.gnu.org/licenses/>.
  19. *
  20. **/
  21. ???using System;
  22. using System.Collections.Generic;
  23. using System.Linq;
  24. using System.Text;
  25. using System.Globalization;
  26. using System.Reflection;
  27. using System.IO;
  28. using System.Collections;
  29. namespace Gettext.Cs
  30. {
  31. /// <summary>
  32. /// Extendable file based resource manager.
  33. /// </summary>
  34. public class FileBasedResourceManager : System.Resources.ResourceManager
  35. {
  36. #region Properties
  37. string path;
  38. string fileformat;
  39. /// <summary>
  40. /// Path to retrieve the files from.
  41. /// </summary>
  42. public string Path
  43. {
  44. get { return path; }
  45. set { path = value; }
  46. }
  47. /// <summary>
  48. /// Format of the resource set po file based on {{culture}} and {{resource}} placeholders.
  49. /// </summary>
  50. public string FileFormat
  51. {
  52. get { return fileformat; }
  53. set { fileformat = value; }
  54. }
  55. #endregion
  56. #region Notification Events
  57. /// <summary>
  58. /// Arguments for events related to the creation, successful or not, of a resource set.
  59. /// </summary>
  60. public class ResourceSetCreationEventArgs : EventArgs
  61. {
  62. /// <summary>
  63. /// Exception in case of error, null on success.
  64. /// </summary>
  65. public Exception Exception { get; set; }
  66. /// <summary>
  67. /// FileName from where the resource set was loaded.
  68. /// </summary>
  69. public String FileName { get; set; }
  70. /// <summary>
  71. /// Type of the resource set being initialized.
  72. /// </summary>
  73. public Type ResourceSetType { get; set; }
  74. /// <summary>
  75. /// Instance of the resource set created, may be null on error.
  76. /// </summary>
  77. public System.Resources.ResourceSet ResourceSet { get; set; }
  78. /// <summary>
  79. /// Whether the creation was successful.
  80. /// </summary>
  81. public bool Success { get; set; }
  82. }
  83. /// <summary>
  84. /// Event that notifies the successful creation of a resource set.
  85. /// </summary>
  86. public event EventHandler<ResourceSetCreationEventArgs> CreatedResourceSet;
  87. /// <summary>
  88. /// Event that notifies an error creating a resource set.
  89. /// </summary>
  90. public event EventHandler<ResourceSetCreationEventArgs> FailedResourceSet;
  91. protected void RaiseCreatedResourceSet(string filename, System.Resources.ResourceSet set)
  92. {
  93. var handler = CreatedResourceSet;
  94. if (handler != null)
  95. {
  96. handler(this, new ResourceSetCreationEventArgs
  97. {
  98. FileName = filename,
  99. ResourceSet = set,
  100. ResourceSetType = this.ResourceSetType,
  101. Success = true
  102. });
  103. }
  104. }
  105. protected void RaiseFailedResourceSet(string filename, Exception ex)
  106. {
  107. var handler = FailedResourceSet;
  108. if (handler != null)
  109. {
  110. handler(this, new ResourceSetCreationEventArgs
  111. {
  112. FileName = filename,
  113. ResourceSet = null,
  114. ResourceSetType = this.ResourceSetType,
  115. Success = false,
  116. Exception = ex
  117. });
  118. }
  119. }
  120. #endregion
  121. /// <summary>
  122. /// Creates a new instance.
  123. /// </summary>
  124. /// <param name="name">Name of the resource</param>
  125. /// <param name="path">Path to retrieve the files from</param>
  126. /// <param name="fileformat">Format of the file name using {{resource}} and {{culture}} placeholders.</param>
  127. public FileBasedResourceManager(string name, string path, string fileformat)
  128. : base()
  129. {
  130. this.path = path;
  131. this.fileformat = fileformat;
  132. this.BaseNameField = name;
  133. base.IgnoreCase = false;
  134. base.ResourceSets = new System.Collections.Hashtable();
  135. }
  136. protected override string GetResourceFileName(System.Globalization.CultureInfo culture)
  137. {
  138. return fileformat.Replace("{{culture}}", culture.Name).Replace("{{resource}}", BaseNameField);
  139. }
  140. protected override System.Resources.ResourceSet InternalGetResourceSet(System.Globalization.CultureInfo culture, bool createIfNotExists, bool tryParents)
  141. {
  142. if (path == null && fileformat == null) return null;
  143. if (culture == null || culture.Equals(CultureInfo.InvariantCulture)) return null;
  144. System.Resources.ResourceSet rs = null;
  145. Hashtable resourceSets = this.ResourceSets;
  146. if (!TryFetchResourceSet(resourceSets, culture, out rs))
  147. {
  148. string resourceFileName = this.FindResourceFile(culture);
  149. if (resourceFileName == null)
  150. {
  151. if (tryParents)
  152. {
  153. CultureInfo parent = culture.Parent;
  154. rs = this.InternalGetResourceSet(parent, createIfNotExists, tryParents);
  155. AddResourceSet(resourceSets, culture, ref rs);
  156. return rs;
  157. }
  158. }
  159. else
  160. {
  161. rs = this.CreateResourceSet(resourceFileName);
  162. AddResourceSet(resourceSets, culture, ref rs);
  163. return rs;
  164. }
  165. }
  166. return rs;
  167. }
  168. protected virtual System.Resources.ResourceSet InternalCreateResourceSet(string resourceFileName)
  169. {
  170. object[] args = new object[] { resourceFileName };
  171. return (System.Resources.ResourceSet)Activator.CreateInstance(this.ResourceSetType, args);
  172. }
  173. private System.Resources.ResourceSet CreateResourceSet(string resourceFileName)
  174. {
  175. System.Resources.ResourceSet set = null;
  176. try
  177. {
  178. set = InternalCreateResourceSet(resourceFileName);
  179. RaiseCreatedResourceSet(resourceFileName, set);
  180. }
  181. catch (Exception ex)
  182. {
  183. RaiseFailedResourceSet(resourceFileName, ex);
  184. }
  185. return set;
  186. }
  187. private string FindResourceFile(CultureInfo culture)
  188. {
  189. string resourceFileName = this.GetResourceFileName(culture);
  190. string path = this.path ?? String.Empty;
  191. // Try with simple path + filename combination
  192. string fullpath = System.IO.Path.Combine(path, resourceFileName);
  193. if (File.Exists(fullpath)) return fullpath;
  194. // If path is relative, attempt different directories
  195. if (path == String.Empty || !System.IO.Path.IsPathRooted(path))
  196. {
  197. // Try the entry assembly dir
  198. if (Assembly.GetEntryAssembly() != null)
  199. {
  200. string dir = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), path);
  201. fullpath = System.IO.Path.Combine(dir, resourceFileName);
  202. if (File.Exists(fullpath)) return fullpath;
  203. }
  204. // Else try the executing assembly dir
  205. if (Assembly.GetExecutingAssembly() != null)
  206. {
  207. if (Assembly.GetEntryAssembly() == null || System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) != System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location))
  208. {
  209. string dir = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), path);
  210. fullpath = System.IO.Path.Combine(dir, resourceFileName);
  211. if (File.Exists(fullpath)) return fullpath;
  212. }
  213. }
  214. }
  215. return null;
  216. }
  217. private void AddResourceSet(Hashtable localResourceSets, CultureInfo culture, ref System.Resources.ResourceSet rs)
  218. {
  219. lock (localResourceSets)
  220. {
  221. if (localResourceSets.Contains(culture))
  222. {
  223. var existing = (System.Resources.ResourceSet)localResourceSets[culture];
  224. if (existing != null && !object.Equals(existing, rs))
  225. {
  226. rs.Dispose();
  227. rs = existing;
  228. var a = (System.Collections.Specialized.NameValueCollection)System.Configuration.ConfigurationManager.GetSection("appSettings");
  229. }
  230. }
  231. else
  232. {
  233. localResourceSets.Add(culture, rs);
  234. }
  235. }
  236. }
  237. private bool TryFetchResourceSet(Hashtable localResourceSets, CultureInfo culture, out System.Resources.ResourceSet set)
  238. {
  239. lock (localResourceSets)
  240. {
  241. if (ResourceSets.Contains(culture))
  242. {
  243. set = (System.Resources.ResourceSet)ResourceSets[culture];
  244. return true;
  245. }
  246. set = null;
  247. return false;
  248. }
  249. }
  250. private bool ValidateGetResourceSet(CultureInfo culture)
  251. {
  252. return !(culture == null || culture.Equals(CultureInfo.InvariantCulture) || String.IsNullOrEmpty(culture.Name));
  253. }
  254. }
  255. }