AssemblyResourceLoader.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. //
  2. // System.Web.Handlers.AssemblyResourceLoader
  3. //
  4. // Authors:
  5. // Ben Maurer ([email protected])
  6. //
  7. // (C) 2003 Ben Maurer
  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. using System.Web.UI;
  30. using System.Reflection;
  31. using System.IO;
  32. using System.Resources;
  33. using System.Collections;
  34. using System.Text.RegularExpressions;
  35. namespace System.Web.Handlers {
  36. #if SYSTEM_WEB_EXTENSIONS
  37. partial class ScriptResourceHandler
  38. {
  39. const string HandlerFileName = "ScriptResource.axd";
  40. #else
  41. #if NET_2_0
  42. public sealed
  43. #else
  44. internal // since this is in the .config file, we need to support it, since we dont have versoned support.
  45. #endif
  46. class AssemblyResourceLoader : IHttpHandler {
  47. const string HandlerFileName = "WebResource.axd";
  48. #endif
  49. #if NET_2_0
  50. const char QueryParamSeparator = ';';
  51. #else
  52. const char QueryParamSeparator = '&';
  53. #endif
  54. static readonly Hashtable _embeddedResources;
  55. #if SYSTEM_WEB_EXTENSIONS
  56. static ScriptResourceHandler()
  57. #else
  58. static AssemblyResourceLoader()
  59. #endif
  60. {
  61. _embeddedResources = new Hashtable ();
  62. InitEmbeddedResourcesUrls ();
  63. }
  64. static void InitEmbeddedResourcesUrls ()
  65. {
  66. Assembly currAsm = typeof (AssemblyResourceLoader).Assembly;
  67. WebResourceAttribute [] attrs = (WebResourceAttribute []) currAsm.GetCustomAttributes (typeof (WebResourceAttribute), false);
  68. for (int i = 0; i < attrs.Length; i++) {
  69. string resourceName = attrs [i].WebResource;
  70. if (resourceName != null && resourceName.Length > 0)
  71. _embeddedResources.Add (resourceName, GetResourceUrl (currAsm, resourceName, false));
  72. }
  73. }
  74. internal static string GetResourceUrl (Type type, string resourceName)
  75. {
  76. string url = null;
  77. Assembly assembly = type.Assembly;
  78. if (assembly == typeof (AssemblyResourceLoader).Assembly)
  79. url = (string) _embeddedResources [resourceName];
  80. return (url != null) ? url : GetResourceUrl (assembly, resourceName, false);
  81. }
  82. internal static string GetResourceUrl (Assembly assembly, string resourceName, bool notifyScriptLoaded)
  83. {
  84. string aname = assembly == typeof (AssemblyResourceLoader).Assembly ? "s" : HttpUtility.UrlEncode (assembly.GetName ().FullName);
  85. string apath = assembly.Location;
  86. string atime = String.Empty;
  87. string extra = String.Empty;
  88. #if SYSTEM_WEB_EXTENSIONS
  89. extra = String.Format ("{0}n={1}", QueryParamSeparator, notifyScriptLoaded ? "t" : "f");
  90. #endif
  91. #if TARGET_JVM
  92. atime = String.Format ("{0}t={1}", QueryParamSeparator, assembly.GetHashCode ());
  93. #else
  94. if (apath != String.Empty)
  95. atime = String.Format ("{0}t={1}", QueryParamSeparator, File.GetLastWriteTimeUtc (apath).Ticks);
  96. #endif
  97. string href = String.Format ("{0}?a={2}{1}r={3}{4}{5}", HandlerFileName,
  98. QueryParamSeparator, aname,
  99. HttpUtility.UrlEncode (resourceName), atime, extra);
  100. HttpContext ctx = HttpContext.Current;
  101. if (ctx != null && ctx.Request != null) {
  102. string appPath = VirtualPathUtility.AppendTrailingSlash (ctx.Request.ApplicationPath);
  103. href = appPath + href;
  104. }
  105. return href;
  106. }
  107. #if SYSTEM_WEB_EXTENSIONS
  108. protected virtual void ProcessRequest (HttpContext context)
  109. #else
  110. [MonoTODO ("Substitution not implemented")]
  111. void System.Web.IHttpHandler.ProcessRequest (HttpContext context)
  112. #endif
  113. {
  114. string resourceName = context.Request.QueryString ["r"];
  115. string asmName = context.Request.QueryString ["a"];
  116. Assembly assembly;
  117. if (asmName == null || asmName == "s")
  118. assembly = typeof (AssemblyResourceLoader).Assembly;
  119. else
  120. assembly = Assembly.Load (asmName);
  121. WebResourceAttribute wra = null;
  122. WebResourceAttribute [] attrs = (WebResourceAttribute []) assembly.GetCustomAttributes (typeof (WebResourceAttribute), false);
  123. for (int i = 0; i < attrs.Length; i++) {
  124. if (attrs [i].WebResource == resourceName) {
  125. wra = attrs [i];
  126. break;
  127. }
  128. }
  129. #if SYSTEM_WEB_EXTENSIONS
  130. if (wra == null && resourceName.Length > 9 && resourceName.EndsWith (".debug.js", StringComparison.OrdinalIgnoreCase)) {
  131. resourceName = String.Concat (resourceName.Substring (0, resourceName.Length - 9), ".js");
  132. for (int i = 0; i < attrs.Length; i++) {
  133. if (attrs [i].WebResource == resourceName) {
  134. wra = attrs [i];
  135. break;
  136. }
  137. }
  138. }
  139. #endif
  140. if (wra == null)
  141. throw new HttpException (404, string.Format ("Resource {0} not found", resourceName));
  142. context.Response.ContentType = wra.ContentType;
  143. /* tell the client they can cache resources for 1 year */
  144. context.Response.ExpiresAbsolute = DateTime.Now.AddYears (1);
  145. context.Response.CacheControl = "private";
  146. context.Response.Cache.VaryByParams ["r"] = true;
  147. context.Response.Cache.VaryByParams ["t"] = true;
  148. Stream s = assembly.GetManifestResourceStream (resourceName);
  149. if (s == null)
  150. throw new HttpException (404, string.Format ("Resource {0} not found", resourceName));
  151. if (wra.PerformSubstitution) {
  152. StreamReader r = new StreamReader (s);
  153. TextWriter w = context.Response.Output;
  154. new PerformSubstitutionHelper (assembly).PerformSubstitution (r, w);
  155. }
  156. else {
  157. byte [] buf = new byte [1024];
  158. Stream output = context.Response.OutputStream;
  159. int c;
  160. do {
  161. c = s.Read (buf, 0, 1024);
  162. output.Write (buf, 0, c);
  163. } while (c > 0);
  164. }
  165. #if SYSTEM_WEB_EXTENSIONS
  166. TextWriter writer = context.Response.Output;
  167. foreach (ScriptResourceAttribute sra in assembly.GetCustomAttributes (typeof (ScriptResourceAttribute), false)) {
  168. if (sra.ScriptName == resourceName) {
  169. string scriptResourceName = sra.ScriptResourceName;
  170. ResourceSet rset = null;
  171. try {
  172. rset = new ResourceManager (scriptResourceName, assembly).GetResourceSet (Threading.Thread.CurrentThread.CurrentUICulture, true, true);
  173. }
  174. catch (MissingManifestResourceException) {
  175. #if TARGET_JVM // GetResourceSet does not throw MissingManifestResourceException if ressource is not exists
  176. }
  177. if (rset == null) {
  178. #endif
  179. if (scriptResourceName.EndsWith (".resources")) {
  180. scriptResourceName = scriptResourceName.Substring (0, scriptResourceName.Length - 10);
  181. rset = new ResourceManager (scriptResourceName, assembly).GetResourceSet (Threading.Thread.CurrentThread.CurrentUICulture, true, true);
  182. }
  183. #if !TARGET_JVM
  184. else
  185. throw;
  186. #endif
  187. }
  188. if (rset == null)
  189. break;
  190. writer.WriteLine ();
  191. writer.WriteLine ("{0}={{", sra.TypeName);
  192. foreach (DictionaryEntry entry in rset) {
  193. string value = entry.Value as string;
  194. if (value != null)
  195. writer.WriteLine ("{0}:{1},", GetScriptStringLiteral ((string) entry.Key), GetScriptStringLiteral (value));
  196. }
  197. writer.WriteLine ("};");
  198. break;
  199. }
  200. }
  201. bool notifyScriptLoaded = context.Request.QueryString ["n"] == "t";
  202. if (notifyScriptLoaded) {
  203. writer.WriteLine ();
  204. writer.WriteLine ("if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();");
  205. }
  206. #endif
  207. }
  208. sealed class PerformSubstitutionHelper
  209. {
  210. readonly Assembly _assembly;
  211. static readonly Regex _regex = new Regex (@"\<%=[ ]*WebResource[ ]*\([ ]*""([^""]+)""[ ]*\)[ ]*%\>");
  212. public PerformSubstitutionHelper (Assembly assembly) {
  213. _assembly = assembly;
  214. }
  215. public void PerformSubstitution (TextReader reader, TextWriter writer) {
  216. string line = reader.ReadLine ();
  217. while (line != null) {
  218. if (line.Length > 0 && _regex.IsMatch (line))
  219. line = _regex.Replace (line, new MatchEvaluator (PerformSubstitutionReplace));
  220. writer.WriteLine (line);
  221. line = reader.ReadLine ();
  222. }
  223. }
  224. string PerformSubstitutionReplace (Match m) {
  225. string resourceName = m.Groups [1].Value;
  226. #if SYSTEM_WEB_EXTENSIONS
  227. return ScriptResourceHandler.GetResourceUrl (_assembly, resourceName, false);
  228. #else
  229. return AssemblyResourceLoader.GetResourceUrl (_assembly, resourceName, false);
  230. #endif
  231. }
  232. }
  233. #if !SYSTEM_WEB_EXTENSIONS
  234. bool System.Web.IHttpHandler.IsReusable { get { return true; } }
  235. #endif
  236. }
  237. }