AppResourcesCompiler.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. //
  2. // System.Web.Compilation.AppResourceFilesCollection
  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;
  40. using System.Web.Caching;
  41. using System.Web.Configuration;
  42. using System.Web.Util;
  43. namespace System.Web.Compilation
  44. {
  45. internal class AppResourcesCompiler
  46. {
  47. const string cachePrefix = "@@LocalResourcesAssemblies";
  48. public const string DefaultCultureKey = ".:!DefaultCulture!:.";
  49. bool isGlobal;
  50. HttpContext context;
  51. AppResourceFilesCollection files;
  52. string tempDirectory;
  53. string virtualPath;
  54. Dictionary <string, List <string>> cultureFiles;
  55. string TempDirectory {
  56. get {
  57. if (tempDirectory != null)
  58. return tempDirectory;
  59. return (tempDirectory = AppDomain.CurrentDomain.SetupInformation.DynamicBase);
  60. }
  61. }
  62. public Dictionary <string, List <string>> CultureFiles {
  63. get { return cultureFiles; }
  64. }
  65. public AppResourcesCompiler (HttpContext context)
  66. {
  67. this.context = context;
  68. this.isGlobal = true;
  69. this.files = new AppResourceFilesCollection (context);
  70. this.cultureFiles = new Dictionary <string, List <string>> ();
  71. }
  72. public AppResourcesCompiler (string virtualPath)
  73. {
  74. this.virtualPath = virtualPath;
  75. this.isGlobal = false;
  76. this.files = new AppResourceFilesCollection (HttpContext.Current.Request.MapPath (virtualPath));
  77. this.cultureFiles = new Dictionary <string, List <string>> ();
  78. }
  79. public Assembly Compile ()
  80. {
  81. files.Collect ();
  82. if (!files.HasFiles)
  83. return null;
  84. if (isGlobal)
  85. return CompileGlobal ();
  86. else
  87. return CompileLocal ();
  88. }
  89. Assembly CompileGlobal ()
  90. {
  91. string assemblyPath = FileUtils.CreateTemporaryFile (TempDirectory,
  92. "App_GlobalResources",
  93. "dll",
  94. OnCreateRandomFile) as string;
  95. if (assemblyPath == null)
  96. throw new ApplicationException ("Failed to create global resources assembly");
  97. List <string>[] fileGroups = GroupGlobalFiles ();
  98. if (fileGroups == null || fileGroups.Length == 0)
  99. return null;
  100. CodeCompileUnit unit = new CodeCompileUnit ();
  101. CodeNamespace ns = new CodeNamespace (null);
  102. ns.Imports.Add (new CodeNamespaceImport ("System"));
  103. ns.Imports.Add (new CodeNamespaceImport ("System.Globalization"));
  104. ns.Imports.Add (new CodeNamespaceImport ("System.Reflection"));
  105. ns.Imports.Add (new CodeNamespaceImport ("System.Resources"));
  106. unit.Namespaces.Add (ns);
  107. AppResourcesAssemblyBuilder builder = new AppResourcesAssemblyBuilder ("App_GlobalResources", assemblyPath,
  108. this);
  109. CodeDomProvider provider = builder.Provider;
  110. Dictionary <string,bool> assemblies = new Dictionary<string,bool> ();
  111. foreach (List<string> ls in fileGroups)
  112. DomFromResource (ls [0], unit, assemblies, provider);
  113. foreach (KeyValuePair<string,bool> de in assemblies)
  114. unit.ReferencedAssemblies.Add (de.Key);
  115. builder.Build (unit);
  116. HttpContext.AppGlobalResourcesAssembly = builder.MainAssembly;
  117. return builder.MainAssembly;
  118. }
  119. Assembly CompileLocal ()
  120. {
  121. if (String.IsNullOrEmpty (virtualPath))
  122. return null;
  123. Assembly cached = GetCachedLocalResourcesAssembly (virtualPath);
  124. if (cached != null)
  125. return cached;
  126. string prefix;
  127. if (virtualPath == "/")
  128. prefix = "App_LocalResources.root";
  129. else
  130. prefix = "App_LocalResources" + virtualPath.Replace ('/', '.');
  131. string assemblyPath = FileUtils.CreateTemporaryFile (TempDirectory,
  132. prefix,
  133. "dll",
  134. OnCreateRandomFile) as string;
  135. if (assemblyPath == null)
  136. throw new ApplicationException ("Failed to create local resources assembly");
  137. List<AppResourceFileInfo> files = this.files.Files;
  138. foreach (AppResourceFileInfo arfi in files)
  139. GetResourceFile (arfi, true);
  140. AppResourcesAssemblyBuilder builder = new AppResourcesAssemblyBuilder ("App_LocalResources", assemblyPath,
  141. this);
  142. builder.Build ();
  143. Assembly ret = builder.MainAssembly;
  144. if (ret != null)
  145. AddAssemblyToCache (virtualPath, ret);
  146. return ret;
  147. }
  148. internal static Assembly GetCachedLocalResourcesAssembly (string path)
  149. {
  150. Dictionary <string, Assembly> cache;
  151. cache = HttpRuntime.InternalCache[cachePrefix] as Dictionary <string, Assembly>;
  152. if (cache == null || !cache.ContainsKey (path))
  153. return null;
  154. return cache [path];
  155. }
  156. void AddAssemblyToCache (string path, Assembly asm)
  157. {
  158. Cache runtimeCache = HttpRuntime.InternalCache;
  159. Dictionary <string, Assembly> cache;
  160. cache = runtimeCache[cachePrefix] as Dictionary <string, Assembly>;
  161. if (cache == null)
  162. cache = new Dictionary <string, Assembly> ();
  163. cache [path] = asm;
  164. runtimeCache.Insert (cachePrefix, cache);
  165. }
  166. uint CountChars (char c, string s)
  167. {
  168. uint ret = 0;
  169. foreach (char ch in s) {
  170. if (ch == c)
  171. ret++;
  172. }
  173. return ret;
  174. }
  175. string IsFileCultureValid (string fileName)
  176. {
  177. string tmp = Path.GetFileNameWithoutExtension (fileName);
  178. tmp = Path.GetExtension (tmp);
  179. if (tmp != null && tmp.Length > 0) {
  180. tmp = tmp.Substring (1);
  181. try {
  182. CultureInfo.GetCultureInfo (tmp);
  183. return tmp;
  184. } catch {
  185. return null;
  186. }
  187. }
  188. return null;
  189. }
  190. string GetResourceFile (AppResourceFileInfo arfi, bool local)
  191. {
  192. string resfile;
  193. if (arfi.Kind == AppResourceFileKind.ResX)
  194. resfile = CompileResource (arfi, local);
  195. else
  196. resfile = arfi.Info.FullName;
  197. if (!String.IsNullOrEmpty (resfile)) {
  198. string culture = IsFileCultureValid (resfile);
  199. if (culture == null)
  200. culture = DefaultCultureKey;
  201. List <string> cfiles;
  202. if (cultureFiles.ContainsKey (culture))
  203. cfiles = cultureFiles [culture];
  204. else {
  205. cfiles = new List <string> (1);
  206. cultureFiles [culture] = cfiles;
  207. }
  208. cfiles.Add (resfile);
  209. }
  210. return resfile;
  211. }
  212. List <string>[] GroupGlobalFiles ()
  213. {
  214. List<AppResourceFileInfo> files = this.files.Files;
  215. List<List<string>> groups = new List<List<string>> ();
  216. AppResourcesLengthComparer<List<string>> lcList = new AppResourcesLengthComparer<List<string>> ();
  217. string tmp, s, basename;
  218. uint basedots, filedots;
  219. AppResourceFileInfo defaultFile;
  220. foreach (AppResourceFileInfo arfi in files) {
  221. if (arfi.Kind != AppResourceFileKind.ResX && arfi.Kind != AppResourceFileKind.Resource)
  222. continue;
  223. s = arfi.Info.FullName;
  224. basename = Path.GetFileNameWithoutExtension (s);
  225. basedots = CountChars ('.', basename);
  226. defaultFile = null;
  227. // If there are any files that start with this baseName, we have a default file
  228. foreach (AppResourceFileInfo fi in files) {
  229. if (fi.Seen)
  230. continue;
  231. string s2 = fi.Info.FullName;
  232. if (s2 == null || s == s2)
  233. continue;
  234. tmp = Path.GetFileNameWithoutExtension (s2);
  235. filedots = CountChars ('.', tmp);
  236. if (filedots == basedots + 1 && tmp.StartsWith (basename)) {
  237. if (IsFileCultureValid (s2) != null) {
  238. // A valid translated file for this name
  239. defaultFile = arfi;
  240. break;
  241. } else {
  242. // This file shares the base name, but the culture is invalid - we must
  243. // ignore it since the name of the generated strongly typed class for this
  244. // resource will clash with the one generated from the default file with
  245. // the given basename.
  246. fi.Seen = true;
  247. }
  248. }
  249. }
  250. if (defaultFile != null) {
  251. List<string> al = new List<string> ();
  252. al.Add (GetResourceFile (arfi, false));
  253. arfi.Seen = true;
  254. groups.Add (al);
  255. }
  256. }
  257. groups.Sort (lcList);
  258. string tmp2;
  259. // Now find their translated counterparts
  260. foreach (List<string> al in groups) {
  261. s = al [0];
  262. tmp = Path.GetFileNameWithoutExtension (s);
  263. if (tmp.StartsWith ("Resources."))
  264. tmp = tmp.Substring (10);
  265. foreach (AppResourceFileInfo arfi in files) {
  266. if (arfi.Seen)
  267. continue;
  268. s = arfi.Info.FullName;
  269. if (s == null)
  270. continue;
  271. tmp2 = arfi.Info.Name;
  272. if (tmp2.StartsWith (tmp)) {
  273. al.Add (GetResourceFile (arfi, false));
  274. arfi.Seen = true;
  275. }
  276. }
  277. }
  278. // Anything that's left here might be orphans or lone default files.
  279. // For those files we check the part following the last dot
  280. // before the .resx/.resource extensions and test whether it's a registered
  281. // culture or not. If it is not a culture, then we have a
  282. // default file that doesn't have any translations. Otherwise,
  283. // the file is ignored (it's the same thing MS.NET does)
  284. foreach (AppResourceFileInfo arfi in files) {
  285. if (arfi.Seen)
  286. continue;
  287. if (IsFileCultureValid (arfi.Info.FullName) != null)
  288. continue; // Culture found, we reject the file
  289. // A single default file, create a group
  290. List<string> al = new List<string> ();
  291. al.Add (GetResourceFile (arfi, false));
  292. groups.Add (al);
  293. }
  294. groups.Sort (lcList);
  295. return groups.ToArray ();
  296. }
  297. // CodeDOM generation
  298. void DomFromResource (string resfile, CodeCompileUnit unit, Dictionary <string,bool> assemblies,
  299. CodeDomProvider provider)
  300. {
  301. if (String.IsNullOrEmpty (resfile))
  302. return;
  303. string fname, nsname, classname;
  304. fname = Path.GetFileNameWithoutExtension (resfile);
  305. nsname = Path.GetFileNameWithoutExtension (fname);
  306. classname = Path.GetExtension (fname);
  307. if (classname == null || classname.Length == 0) {
  308. classname = nsname;
  309. nsname = "Resources";
  310. } else {
  311. if (!nsname.StartsWith ("Resources", StringComparison.InvariantCulture))
  312. nsname = String.Concat ("Resources.", nsname);
  313. classname = classname.Substring(1);
  314. }
  315. if (!String.IsNullOrEmpty (classname))
  316. classname = classname.Replace ('.', '_');
  317. if (!String.IsNullOrEmpty (nsname))
  318. nsname = nsname.Replace ('.', '_');
  319. if (!provider.IsValidIdentifier (nsname) || !provider.IsValidIdentifier (classname))
  320. throw new ApplicationException ("Invalid resource file name.");
  321. ResourceReader res;
  322. try {
  323. res = new ResourceReader (resfile);
  324. } catch (ArgumentException) {
  325. // invalid stream, probably empty - ignore silently and abort
  326. return;
  327. }
  328. CodeNamespace ns = new CodeNamespace (nsname);
  329. CodeTypeDeclaration cls = new CodeTypeDeclaration (classname);
  330. cls.IsClass = true;
  331. cls.TypeAttributes = TypeAttributes.Public | TypeAttributes.Sealed;
  332. CodeMemberField cmf = new CodeMemberField (typeof(CultureInfo), "_culture");
  333. cmf.InitExpression = new CodePrimitiveExpression (null);
  334. cmf.Attributes = MemberAttributes.Private | MemberAttributes.Final | MemberAttributes.Static;
  335. cls.Members.Add (cmf);
  336. cmf = new CodeMemberField (typeof(ResourceManager), "_resourceManager");
  337. cmf.InitExpression = new CodePrimitiveExpression (null);
  338. cmf.Attributes = MemberAttributes.Private | MemberAttributes.Final | MemberAttributes.Static;
  339. cls.Members.Add (cmf);
  340. // Property: ResourceManager
  341. CodeMemberProperty cmp = new CodeMemberProperty ();
  342. cmp.Attributes = MemberAttributes.Public | MemberAttributes.Final | MemberAttributes.Static;
  343. cmp.Name = "ResourceManager";
  344. cmp.HasGet = true;
  345. cmp.Type = new CodeTypeReference (typeof(ResourceManager));
  346. CodePropertyResourceManagerGet (cmp.GetStatements, resfile, classname);
  347. cls.Members.Add (cmp);
  348. // Property: Culture
  349. cmp = new CodeMemberProperty ();
  350. cmp.Attributes = MemberAttributes.Public | MemberAttributes.Final;
  351. cmp.Attributes = MemberAttributes.Public | MemberAttributes.Final | MemberAttributes.Static;
  352. cmp.Name = "Culture";
  353. cmp.HasGet = true;
  354. cmp.HasSet = true;
  355. cmp.Type = new CodeTypeReference (typeof(CultureInfo));
  356. CodePropertyGenericGet (cmp.GetStatements, "_culture", classname);
  357. CodePropertyGenericSet (cmp.SetStatements, "_culture", classname);
  358. cls.Members.Add (cmp);
  359. // Add the resource properties
  360. Dictionary<string,bool> imports = new Dictionary<string,bool> ();
  361. try {
  362. foreach (DictionaryEntry de in res) {
  363. Type type = de.Value.GetType ();
  364. if (!imports.ContainsKey (type.Namespace))
  365. imports [type.Namespace] = true;
  366. string asname = new AssemblyName (type.Assembly.FullName).Name;
  367. if (!assemblies.ContainsKey (asname))
  368. assemblies [asname] = true;
  369. cmp = new CodeMemberProperty ();
  370. cmp.Attributes = MemberAttributes.Public | MemberAttributes.Final | MemberAttributes.Static;
  371. cmp.Name = SanitizeResourceName ((string)de.Key);
  372. cmp.HasGet = true;
  373. CodePropertyResourceGet (cmp.GetStatements, (string)de.Key, type, classname);
  374. cmp.Type = new CodeTypeReference (type);
  375. cls.Members.Add (cmp);
  376. }
  377. } catch (Exception ex) {
  378. throw new ApplicationException ("Failed to compile global resources.", ex);
  379. }
  380. foreach (KeyValuePair<string,bool> de in imports)
  381. ns.Imports.Add (new CodeNamespaceImport(de.Key));
  382. ns.Types.Add (cls);
  383. unit.Namespaces.Add (ns);
  384. }
  385. string SanitizeResourceName (string name)
  386. {
  387. return name.Replace (' ', '_').Replace ('-', '_').Replace ('.', '_');
  388. }
  389. CodeObjectCreateExpression NewResourceManager (string name, string typename)
  390. {
  391. CodeExpression resname = new CodePrimitiveExpression (name);
  392. CodePropertyReferenceExpression asm = new CodePropertyReferenceExpression (
  393. new CodeTypeOfExpression (new CodeTypeReference (typename)),
  394. "Assembly");
  395. return new CodeObjectCreateExpression ("System.Resources.ResourceManager",
  396. new CodeExpression [] {resname, asm});
  397. }
  398. void CodePropertyResourceManagerGet (CodeStatementCollection csc, string resfile, string typename)
  399. {
  400. string name = Path.GetFileNameWithoutExtension (resfile);
  401. CodeStatement st;
  402. CodeExpression exp;
  403. exp = new CodeFieldReferenceExpression (new CodeTypeReferenceExpression (typename), "_resourceManager");
  404. st = new CodeConditionStatement (
  405. new CodeBinaryOperatorExpression (
  406. exp,
  407. CodeBinaryOperatorType.IdentityInequality,
  408. new CodePrimitiveExpression (null)),
  409. new CodeStatement [] { new CodeMethodReturnStatement (exp) });
  410. csc.Add (st);
  411. st = new CodeAssignStatement (exp, NewResourceManager (name, typename));
  412. csc.Add (st);
  413. csc.Add (new CodeMethodReturnStatement (exp));
  414. }
  415. void CodePropertyResourceGet (CodeStatementCollection csc, string resname, Type restype, string typename)
  416. {
  417. CodeStatement st = new CodeVariableDeclarationStatement (
  418. typeof (ResourceManager),
  419. "rm",
  420. new CodePropertyReferenceExpression (
  421. new CodeTypeReferenceExpression (typename), "ResourceManager"));
  422. csc.Add (st);
  423. st = new CodeConditionStatement (
  424. new CodeBinaryOperatorExpression (
  425. new CodeVariableReferenceExpression ("rm"),
  426. CodeBinaryOperatorType.IdentityEquality,
  427. new CodePrimitiveExpression (null)),
  428. new CodeStatement [] { new CodeMethodReturnStatement (new CodePrimitiveExpression (null)) });
  429. csc.Add (st);
  430. bool gotstr = (restype == typeof (string));
  431. CodeExpression exp = new CodeMethodInvokeExpression (
  432. new CodeVariableReferenceExpression ("rm"),
  433. gotstr ? "GetString" : "GetObject",
  434. new CodeExpression [] { new CodePrimitiveExpression (resname),
  435. new CodeFieldReferenceExpression (
  436. new CodeTypeReferenceExpression (typename), "_culture") });
  437. st = new CodeVariableDeclarationStatement (
  438. restype,
  439. "obj",
  440. gotstr ? exp : new CodeCastExpression (restype, exp));
  441. csc.Add (st);
  442. csc.Add (new CodeMethodReturnStatement (new CodeVariableReferenceExpression ("obj")));
  443. }
  444. void CodePropertyGenericGet (CodeStatementCollection csc, string field, string typename)
  445. {
  446. csc.Add(new CodeMethodReturnStatement (
  447. new CodeFieldReferenceExpression (
  448. new CodeTypeReferenceExpression (typename), field)));
  449. }
  450. void CodePropertyGenericSet (CodeStatementCollection csc, string field, string typename)
  451. {
  452. csc.Add(new CodeAssignStatement (
  453. new CodeFieldReferenceExpression (new CodeTypeReferenceExpression (typename), field),
  454. new CodeVariableReferenceExpression ("value")));
  455. }
  456. string CompileResource (AppResourceFileInfo arfi, bool local)
  457. {
  458. string path = arfi.Info.FullName;
  459. string rname = Path.GetFileNameWithoutExtension (path) + ".resources";
  460. if (!local)
  461. rname = "Resources." + rname;
  462. string resource = Path.Combine (TempDirectory, rname);
  463. FileStream source = null, destination = null;
  464. IResourceReader reader = null;
  465. ResourceWriter writer = null;
  466. try {
  467. source = new FileStream (path, FileMode.Open, FileAccess.Read);
  468. destination = new FileStream (resource, FileMode.Create, FileAccess.Write);
  469. reader = GetReaderForKind (arfi.Kind, source);
  470. writer = new ResourceWriter (destination);
  471. foreach (DictionaryEntry de in reader) {
  472. object val = de.Value;
  473. if (val is string)
  474. writer.AddResource ((string)de.Key, (string)val);
  475. else
  476. writer.AddResource ((string)de.Key, val);
  477. }
  478. } catch (Exception ex) {
  479. throw new HttpException ("Failed to compile resource file", ex);
  480. } finally {
  481. if (reader != null)
  482. reader.Close ();
  483. else if (source != null)
  484. source.Close ();
  485. if (writer != null)
  486. writer.Close ();
  487. else if (destination != null)
  488. destination.Close ();
  489. }
  490. return resource;
  491. }
  492. IResourceReader GetReaderForKind (AppResourceFileKind kind, Stream stream)
  493. {
  494. switch (kind) {
  495. case AppResourceFileKind.ResX:
  496. return new ResXResourceReader (stream);
  497. case AppResourceFileKind.Resource:
  498. return new ResourceReader (stream);
  499. default:
  500. return null;
  501. }
  502. }
  503. object OnCreateRandomFile (string path)
  504. {
  505. FileStream f = new FileStream (path, FileMode.CreateNew);
  506. f.Close ();
  507. return path;
  508. }
  509. };
  510. };
  511. #endif