AppResourcesCompiler.cs 21 KB

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