AppResourceFilesCompiler.cs 18 KB

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