2
0

AppResourcesCompiler.cs 20 KB

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