2
0

AppResourceFilesCompiler.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. //
  2. // System.Web.Compilation.AppResourceFilesCompiler: A compiler for application resource files
  3. //
  4. // Authors:
  5. // Marek Habersack ([email protected])
  6. //
  7. // (C) 2006 Marek Habersack
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. #if NET_2_0
  30. using System;
  31. using System.CodeDom;
  32. using System.CodeDom.Compiler;
  33. using System.Collections;
  34. using System.Collections.Generic;
  35. using System.Globalization;
  36. using System.IO;
  37. using System.Reflection;
  38. using System.Resources;
  39. using System.Web.Util;
  40. using Microsoft.CSharp;
  41. //using Microsoft.VisualBasic;
  42. //using Microsoft.JScript;
  43. namespace System.Web.Compilation
  44. {
  45. class LengthComparer<T>: Comparer<T>
  46. {
  47. private int CompareStrings (string a, string b)
  48. {
  49. if (a == null || b == null)
  50. return 0;
  51. return (int)b.Length - (int)a.Length;
  52. }
  53. public override int Compare (T _a, T _b)
  54. {
  55. string a = null, b = null;
  56. if (_a is string && _b is string) {
  57. a = _a as string;
  58. b = _b as string;
  59. } else if (_a is List<string> && _b is List<string>) {
  60. List<string> tmp = _a as List<string>;
  61. a = tmp [0];
  62. tmp = _b as List<string>;
  63. b = tmp [0];
  64. } else
  65. return 0;
  66. return CompareStrings (a, b);
  67. }
  68. }
  69. internal class AppResourceFilesCompiler
  70. {
  71. public enum FcCodeGenerator
  72. {
  73. Typed,
  74. CSharp,
  75. VBasic,
  76. JScript
  77. };
  78. protected string [] filePaths = null;
  79. protected FcCodeGenerator codeGenerator = FcCodeGenerator.CSharp;
  80. protected string codeGenType = null;
  81. protected List<string> [] resxFiles = null;
  82. protected List<string> resourceFiles = null;
  83. protected Dictionary<string,bool?> assemblies = null;
  84. protected string tempdirectory = null;
  85. protected Random rnd = null;
  86. public FcCodeGenerator CodeGen {
  87. get { return codeGenerator; }
  88. set { codeGenerator = value; }
  89. }
  90. virtual public string TempDir {
  91. get {
  92. if (tempdirectory != null)
  93. return tempdirectory;
  94. return (tempdirectory = GenTempDir (Path.GetTempPath ()));
  95. }
  96. set { tempdirectory = value; }
  97. }
  98. public string Source {
  99. get { return FilesToString (); }
  100. }
  101. public CodeCompileUnit CompileUnit {
  102. get { return FilesToDom (); }
  103. }
  104. protected AppResourceFilesCompiler ()
  105. {
  106. filePaths = new string [] {};
  107. }
  108. public AppResourceFilesCompiler (string filePath)
  109. {
  110. DoInit (filePath, FcCodeGenerator.CSharp);
  111. }
  112. public AppResourceFilesCompiler (string filePath, FcCodeGenerator cg)
  113. {
  114. DoInit (filePath, cg);
  115. }
  116. public AppResourceFilesCompiler (string[] filePaths)
  117. {
  118. DoInit (filePaths, FcCodeGenerator.CSharp);
  119. }
  120. public AppResourceFilesCompiler (string[] filePaths, FcCodeGenerator cg)
  121. {
  122. DoInit (filePaths, cg);
  123. }
  124. public AppResourceFilesCompiler (string filePath, string genType)
  125. {
  126. DoInit (filePath, genType);
  127. }
  128. public AppResourceFilesCompiler (string[] filePaths, string genType)
  129. {
  130. DoInit (filePaths, genType);
  131. }
  132. private void DoInit (string filePath, string genType)
  133. {
  134. this.codeGenType = genType;
  135. DoInit (filePath, FcCodeGenerator.Typed);
  136. }
  137. private void DoInit (string [] filePaths, string genType)
  138. {
  139. this.codeGenType = genType;
  140. DoInit (filePaths, FcCodeGenerator.Typed);
  141. }
  142. private void DoInit (string filePath, FcCodeGenerator cg)
  143. {
  144. this.codeGenerator = cg;
  145. if (filePath != null)
  146. this.filePaths = new string [] { filePath };
  147. }
  148. private void DoInit (string [] filePaths, FcCodeGenerator cg)
  149. {
  150. this.codeGenerator = cg;
  151. if (filePaths != null)
  152. this.filePaths = (string [])filePaths.Clone ();
  153. }
  154. protected CodeDomProvider GetCodeProvider ()
  155. {
  156. switch (codeGenerator) {
  157. default:
  158. goto case FcCodeGenerator.CSharp;
  159. case FcCodeGenerator.CSharp:
  160. return new CSharpCodeProvider ();
  161. // case FcCodeGenerator.VBasic:
  162. // return new VBCodeProvider ();
  163. // case FcCodeGenerator.JScript:
  164. // return new JScriptCodeProvider ();
  165. case FcCodeGenerator.Typed:
  166. return null;
  167. }
  168. }
  169. protected string FilesToString ()
  170. {
  171. CodeCompileUnit unit = FilesToDom ();
  172. CodeDomProvider provider = GetCodeProvider ();
  173. StringWriter writer = new StringWriter ();
  174. CodeGeneratorOptions opts = new CodeGeneratorOptions ();
  175. opts.BlankLinesBetweenMembers = false;
  176. provider.GenerateCodeFromCompileUnit (unit, writer, opts);
  177. string ret = writer.ToString ();
  178. writer.Close ();
  179. return ret;
  180. }
  181. protected CodeCompileUnit FilesToDom ()
  182. {
  183. CollectFiles ();
  184. if (resxFiles == null || resxFiles.Length == 0)
  185. return null;
  186. string destdir = TempDir;
  187. string s, resfile;
  188. resourceFiles = new List<string> (resxFiles.Length);
  189. CodeCompileUnit ret = new CodeCompileUnit ();
  190. foreach (List<string> al in resxFiles) {
  191. if (al == null)
  192. continue;
  193. for (int i = 0; i < al.Count; i++) {
  194. s = al [i];
  195. if (s == null)
  196. continue;
  197. resfile = CompileFile (destdir, s);
  198. resourceFiles.Add (resfile);
  199. if (i > 0 || resfile == null)
  200. continue;
  201. // Default file. Generate the class
  202. DomFromResource (resfile, ret);
  203. }
  204. }
  205. if (assemblies != null)
  206. foreach (KeyValuePair<string,bool?> de in assemblies)
  207. ret.ReferencedAssemblies.Add (de.Key);
  208. return ret;
  209. }
  210. private void DomFromResource (string resfile, CodeCompileUnit unit)
  211. {
  212. string fname, nsname, classname;
  213. fname = Path.GetFileNameWithoutExtension (resfile);
  214. nsname = Path.GetFileNameWithoutExtension (fname);
  215. classname = Path.GetExtension (fname);
  216. if (classname == null || classname.Length == 0) {
  217. classname = nsname;
  218. nsname = "Resources";
  219. } else {
  220. nsname = String.Format ("Resources.{0}", nsname);
  221. classname = classname.Substring(1);
  222. }
  223. Dictionary<string,bool> imports = new Dictionary<string,bool> ();
  224. if (assemblies == null)
  225. assemblies = new Dictionary<string,bool?> ();
  226. CodeNamespace ns = new CodeNamespace (nsname);
  227. imports ["System"] = true;
  228. imports ["System.Globalization"] = true;
  229. imports ["System.Reflection"] = true;
  230. imports ["System.Resources"] = true;
  231. CodeTypeDeclaration cls = new CodeTypeDeclaration (classname);
  232. cls.IsClass = true;
  233. cls.TypeAttributes = TypeAttributes.Public | TypeAttributes.Sealed;
  234. CodeMemberField cmf = new CodeMemberField (typeof(CultureInfo), "culture");
  235. cmf.InitExpression = new CodePrimitiveExpression (null);
  236. cmf.Attributes = MemberAttributes.Private | MemberAttributes.Final | MemberAttributes.Static;
  237. cls.Members.Add (cmf);
  238. cmf = new CodeMemberField (typeof(ResourceManager), "resourceManager");
  239. cmf.InitExpression = new CodePrimitiveExpression (null);
  240. cmf.Attributes = MemberAttributes.Private | MemberAttributes.Final | MemberAttributes.Static;
  241. cls.Members.Add (cmf);
  242. // Property: ResourceManager
  243. CodeMemberProperty cmp = new CodeMemberProperty ();
  244. cmp.Attributes = MemberAttributes.Public | MemberAttributes.Final | MemberAttributes.Static;
  245. cmp.Name = "ResourceManager";
  246. cmp.HasGet = true;
  247. cmp.Type = new CodeTypeReference (typeof(ResourceManager));
  248. CodePropertyResourceManagerGet (cmp.GetStatements, resfile, classname);
  249. cls.Members.Add (cmp);
  250. // Property: Culture
  251. cmp = new CodeMemberProperty ();
  252. cmp.Attributes = MemberAttributes.Public | MemberAttributes.Final;
  253. cmp.Attributes = MemberAttributes.Public | MemberAttributes.Final | MemberAttributes.Static;
  254. cmp.Name = "Culture";
  255. cmp.HasGet = true;
  256. cmp.HasSet = true;
  257. cmp.Type = new CodeTypeReference (typeof(CultureInfo));
  258. CodePropertyGenericGet (cmp.GetStatements, "culture", classname);
  259. CodePropertyGenericSet (cmp.SetStatements, "culture", classname);
  260. cls.Members.Add (cmp);
  261. // Add the resource properties
  262. try {
  263. ResourceReader res = new ResourceReader (resfile);
  264. foreach (DictionaryEntry de in res) {
  265. Type type = de.Value.GetType ();
  266. if (!imports.ContainsKey (type.Namespace))
  267. imports [type.Namespace] = true;
  268. string asname = new AssemblyName (type.Assembly.FullName).Name;
  269. if (!assemblies.ContainsKey (asname))
  270. assemblies [asname] = true;
  271. cmp = new CodeMemberProperty ();
  272. cmp.Attributes = MemberAttributes.Public | MemberAttributes.Final | MemberAttributes.Static;
  273. cmp.Name = SanitizeResourceName ((string)de.Key);
  274. cmp.HasGet = true;
  275. CodePropertyResourceGet (cmp.GetStatements, (string)de.Key, type, classname);
  276. cmp.Type = new CodeTypeReference (type);
  277. cls.Members.Add (cmp);
  278. }
  279. } catch (Exception ex) {
  280. }
  281. foreach (KeyValuePair<string,bool> de in imports)
  282. ns.Imports.Add (new CodeNamespaceImport(de.Key));
  283. ns.Types.Add (cls);
  284. unit.Namespaces.Add (ns);
  285. }
  286. private string SanitizeResourceName (string name)
  287. {
  288. return name.Replace (' ', '_').Replace ('-', '_').Replace ('.', '_');
  289. }
  290. private CodeObjectCreateExpression NewResourceManager (string name, string typename)
  291. {
  292. CodeExpression resname = new CodePrimitiveExpression (name);
  293. CodePropertyReferenceExpression asm = new CodePropertyReferenceExpression (
  294. new CodeTypeOfExpression (new CodeTypeReference (typename)),
  295. "Assembly");
  296. return new CodeObjectCreateExpression ("System.Resources.ResourceManager",
  297. new CodeExpression [] {resname, asm});
  298. }
  299. private void CodePropertyResourceManagerGet (CodeStatementCollection csc, string resfile, string typename)
  300. {
  301. string name = Path.GetFileNameWithoutExtension (resfile);
  302. CodeStatement st;
  303. CodeExpression exp;
  304. exp = new CodeFieldReferenceExpression (new CodeTypeReferenceExpression (typename), "resourceManager");
  305. st = new CodeConditionStatement (
  306. new CodeBinaryOperatorExpression (
  307. exp,
  308. CodeBinaryOperatorType.IdentityInequality,
  309. new CodePrimitiveExpression (null)),
  310. new CodeStatement [] { new CodeMethodReturnStatement (exp) });
  311. csc.Add (st);
  312. st = new CodeAssignStatement (exp, NewResourceManager (name, typename));
  313. csc.Add (st);
  314. csc.Add (new CodeMethodReturnStatement (exp));
  315. }
  316. private void CodePropertyResourceGet (CodeStatementCollection csc, string resname, Type restype, string typename)
  317. {
  318. CodeStatement st = new CodeVariableDeclarationStatement (
  319. typeof (ResourceManager),
  320. "rm",
  321. new CodePropertyReferenceExpression (
  322. new CodeTypeReferenceExpression (typename), "ResourceManager"));
  323. csc.Add (st);
  324. st = new CodeConditionStatement (
  325. new CodeBinaryOperatorExpression (
  326. new CodeVariableReferenceExpression ("rm"),
  327. CodeBinaryOperatorType.IdentityEquality,
  328. new CodePrimitiveExpression (null)),
  329. new CodeStatement [] { new CodeMethodReturnStatement (new CodePrimitiveExpression (null)) });
  330. csc.Add (st);
  331. bool gotstr = (restype == typeof (string));
  332. CodeExpression exp = new CodeMethodInvokeExpression (
  333. new CodeVariableReferenceExpression ("rm"),
  334. gotstr ? "GetString" : "GetObject",
  335. new CodeExpression [] { new CodePrimitiveExpression (resname),
  336. new CodeFieldReferenceExpression (
  337. new CodeTypeReferenceExpression (typename), "culture") });
  338. st = new CodeVariableDeclarationStatement (
  339. restype,
  340. "obj",
  341. gotstr ? exp : new CodeCastExpression (restype, exp));
  342. csc.Add (st);
  343. csc.Add (new CodeMethodReturnStatement (new CodeVariableReferenceExpression ("obj")));
  344. }
  345. private void CodePropertyGenericGet (CodeStatementCollection csc, string field, string typename)
  346. {
  347. csc.Add(new CodeMethodReturnStatement (
  348. new CodeFieldReferenceExpression (
  349. new CodeTypeReferenceExpression (typename), field)));
  350. }
  351. private void CodePropertyGenericSet (CodeStatementCollection csc, string field, string typename)
  352. {
  353. csc.Add(new CodeAssignStatement (
  354. new CodeFieldReferenceExpression (new CodeTypeReferenceExpression (typename), field),
  355. new CodeVariableReferenceExpression ("value")));
  356. }
  357. private uint CountChars (char c, string s)
  358. {
  359. uint ret = 0;
  360. foreach (char ch in s) {
  361. if (ch == c)
  362. ret++;
  363. }
  364. return ret;
  365. }
  366. private void CollectFiles ()
  367. {
  368. List<string> files = new List<string> (filePaths);
  369. List<List<string>> groups = new List<List<string>> ();
  370. LengthComparer<string> lcString = new LengthComparer<string> ();
  371. LengthComparer<List<string>> lcList = new LengthComparer<List<string>> ();
  372. files.Sort (lcString);
  373. Array.Sort (filePaths, lcString);
  374. string tmp;
  375. foreach (string s in filePaths) {
  376. tmp = Path.GetExtension (s);
  377. if (tmp == null)
  378. continue;
  379. tmp = tmp.ToLower ();
  380. if (tmp != ".resx")
  381. continue;
  382. string basename = Path.GetFileNameWithoutExtension (s);
  383. uint basedots = CountChars ('.', basename);
  384. uint filedots;
  385. bool gotdefault = false;
  386. // If there are any files that start with this baseName, we have a default file
  387. for (int i = 0; i < files.Count; i++) {
  388. string s2 = files [i];
  389. if (s2 == null || s == s2)
  390. continue;
  391. tmp = Path.GetFileNameWithoutExtension (s2);
  392. filedots = CountChars ('.', tmp);
  393. if (filedots == basedots + 1 && tmp.StartsWith (basename)) {
  394. gotdefault = true;
  395. break;
  396. }
  397. }
  398. if (gotdefault) {
  399. List<string> al = new List<string> ();
  400. al.Add (s);
  401. int idx = files.IndexOf (s);
  402. if (idx != -1)
  403. files [idx] = null;
  404. groups.Add (al);
  405. }
  406. }
  407. groups.Sort (lcList);
  408. string tmp2;
  409. // Now find their translated counterparts
  410. foreach (List<string> al in groups) {
  411. string s = al [0];
  412. tmp = Path.GetFileNameWithoutExtension (s);
  413. for (int i = 0; i < files.Count; i++) {
  414. s = files [i];
  415. if (s == null)
  416. continue;
  417. tmp2 = Path.GetFileName (s);
  418. if (tmp2.StartsWith (tmp)) {
  419. al.Add (s);
  420. files [i] = null;
  421. }
  422. }
  423. }
  424. // Anything that's left here might be orphans or lone default files.
  425. // For those files we check the part following the last dot
  426. // before the .resx extension and test whether it's a registered
  427. // culture or not. If it is not a culture, then we have a
  428. // default file that doesn't have any translations. Otherwise,
  429. // the file is ignored (it's the same thing MS.NET does)
  430. CultureInfo ci;
  431. foreach (string s in files) {
  432. if (s == null)
  433. continue;
  434. tmp = Path.GetFileNameWithoutExtension (s);
  435. tmp = Path.GetExtension (tmp);
  436. if (tmp == null || tmp.Length == 0)
  437. continue;
  438. tmp = tmp.Substring (1);
  439. try {
  440. ci = CultureInfo.GetCultureInfo (tmp);
  441. continue; // Culture found, we reject the file
  442. } catch {
  443. }
  444. // A single default file, create a group
  445. List<string> al = new List<string> ();
  446. al.Add (s);
  447. groups.Add (al);
  448. }
  449. groups.Sort (lcList);
  450. resxFiles = groups.ToArray ();
  451. }
  452. private IResourceReader GetReader (Stream stream, string path)
  453. {
  454. string ext = Path.GetExtension (path);
  455. if (ext == null)
  456. throw new Exception ("Unknown resource type.");
  457. switch (ext.ToLower ()) {
  458. case ".resx":
  459. return new ResXResourceReader (stream);
  460. default:
  461. throw new Exception ("Unknown resource type.");
  462. }
  463. }
  464. private string CompileFile (string destdir, string path)
  465. {
  466. string resfile = String.Format ("{1}{0}{2}.resources",
  467. Path.DirectorySeparatorChar,
  468. destdir,
  469. Path.GetFileNameWithoutExtension (path));
  470. FileStream source = null, dest = null;
  471. IResourceReader reader = null;
  472. ResourceWriter writer = null;
  473. try {
  474. source = new FileStream (path, FileMode.Open, FileAccess.Read);
  475. dest = new FileStream (resfile, FileMode.Create, FileAccess.Write);
  476. reader = GetReader (source, path);
  477. writer = new ResourceWriter (dest);
  478. foreach (DictionaryEntry de in reader) {
  479. object val = de.Value;
  480. if (val is string)
  481. writer.AddResource ((string)de.Key, (string)val);
  482. else
  483. writer.AddResource ((string)de.Key, val);
  484. }
  485. } catch (Exception ex) {
  486. Console.WriteLine ("Resource compiler error: {0}", ex.Message);
  487. Exception inner = ex.InnerException;
  488. if (inner != null)
  489. Console.WriteLine ("Inner exception: {0}", inner.Message);
  490. return null;
  491. } finally {
  492. if (reader != null)
  493. reader.Close ();
  494. else if (source != null)
  495. source.Close ();
  496. if (writer != null)
  497. writer.Close ();
  498. else if (dest != null)
  499. dest.Close ();
  500. }
  501. return resfile;
  502. }
  503. object OnCreateRandomFile (string path)
  504. {
  505. FileStream f = new FileStream (path, FileMode.CreateNew);
  506. f.Close ();
  507. return path;
  508. }
  509. protected string GenRandomFileName (string basepath)
  510. {
  511. return GenRandomFileName (basepath, null);
  512. }
  513. protected string GenRandomFileName (string basepath, string ext)
  514. {
  515. return (string)FileUtils.CreateTemporaryFile (basepath, ext, OnCreateRandomFile);
  516. }
  517. object OnCreateRandomDir (string path)
  518. {
  519. DirectoryInfo di = Directory.CreateDirectory (path);
  520. return di.FullName;
  521. }
  522. protected string GenTempDir (string basepath)
  523. {
  524. return (string)FileUtils.CreateTemporaryFile (basepath, OnCreateRandomDir);
  525. }
  526. }
  527. }
  528. #endif