ScriptResourceHandler.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. //
  2. // ScriptResourceHandler.cs
  3. //
  4. // Authors:
  5. // Igor Zelmanovich <[email protected]>
  6. // Marek Habersack <[email protected]>
  7. //
  8. // (C) 2007 Mainsoft, Inc. http://www.mainsoft.com
  9. // (C) 2011 Novell, Inc. http://novell.com
  10. //
  11. //
  12. // Permission is hereby granted, free of charge, to any person obtaining
  13. // a copy of this software and associated documentation files (the
  14. // "Software"), to deal in the Software without restriction, including
  15. // without limitation the rights to use, copy, modify, merge, publish,
  16. // distribute, sublicense, and/or sell copies of the Software, and to
  17. // permit persons to whom the Software is furnished to do so, subject to
  18. // the following conditions:
  19. //
  20. // The above copyright notice and this permission notice shall be
  21. // included in all copies or substantial portions of the Software.
  22. //
  23. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  24. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  26. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  27. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  28. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  29. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. //
  31. using System;
  32. using System.Collections;
  33. using System.Collections.Generic;
  34. using System.IO;
  35. using System.Security.Cryptography;
  36. using System.Reflection;
  37. using System.Resources;
  38. using System.Text;
  39. using System.Threading;
  40. using System.Web.Configuration;
  41. using System.Web.Hosting;
  42. using System.Web.UI;
  43. using System.Web.Util;
  44. namespace System.Web.Handlers
  45. {
  46. public partial class ScriptResourceHandler : IHttpHandler
  47. {
  48. protected virtual bool IsReusable {
  49. get { return true; }
  50. }
  51. #region IHttpHandler Members
  52. bool IHttpHandler.IsReusable {
  53. get { return IsReusable; }
  54. }
  55. void IHttpHandler.ProcessRequest (HttpContext context) {
  56. ProcessRequest (context);
  57. }
  58. #endregion
  59. #if NET_3_5
  60. void AppendResourceScriptContents (StringWriter sw, CompositeEntry entry)
  61. {
  62. if (entry.Assembly == null || entry.Attribute == null || String.IsNullOrEmpty (entry.NameOrPath))
  63. return;
  64. using (Stream s = entry.Assembly.GetManifestResourceStream (entry.NameOrPath)) {
  65. if (s == null)
  66. throw new HttpException (404, "Resource '" + entry.NameOrPath + "' not found");
  67. if (entry.Attribute.PerformSubstitution) {
  68. using (var r = new StreamReader (s)) {
  69. new PerformSubstitutionHelper (entry.Assembly).PerformSubstitution (r, sw);
  70. }
  71. } else {
  72. using (var r = new StreamReader (s)) {
  73. string line = r.ReadLine ();
  74. while (line != null) {
  75. sw.WriteLine (line);
  76. line = r.ReadLine ();
  77. }
  78. }
  79. }
  80. }
  81. }
  82. void AppendFileScriptContents (StringWriter sw, CompositeEntry entry)
  83. {
  84. // FIXME: should we limit the script size in any way?
  85. if (String.IsNullOrEmpty (entry.NameOrPath))
  86. return;
  87. string mappedPath;
  88. if (!HostingEnvironment.HaveCustomVPP) {
  89. // We'll take a shortcut here by bypassing the default VPP layers
  90. mappedPath = HostingEnvironment.MapPath (entry.NameOrPath);
  91. if (!File.Exists (mappedPath))
  92. return;
  93. sw.Write (File.ReadAllText (mappedPath));
  94. return;
  95. }
  96. VirtualPathProvider vpp = HostingEnvironment.VirtualPathProvider;
  97. if (!vpp.FileExists (entry.NameOrPath))
  98. return;
  99. VirtualFile file = vpp.GetFile (entry.NameOrPath);
  100. if (file == null)
  101. return;
  102. using (Stream s = file.Open ()) {
  103. using (var r = new StreamReader (s)) {
  104. string line = r.ReadLine ();
  105. while (line != null) {
  106. sw.WriteLine (line);
  107. line = r.ReadLine ();
  108. }
  109. }
  110. }
  111. }
  112. void AppendScriptContents (StringWriter sw, CompositeEntry entry)
  113. {
  114. if (entry.Assembly != null)
  115. AppendResourceScriptContents (sw, entry);
  116. else
  117. AppendFileScriptContents (sw, entry);
  118. }
  119. void SendCompositeScript (HttpContext context, HttpRequest request, bool notifyScriptLoaded, List <CompositeEntry> entries)
  120. {
  121. if (entries.Count == 0)
  122. throw new HttpException (404, "Resource not found");
  123. long atime;
  124. DateTime modifiedSince;
  125. bool hasCacheControl = HasCacheControl (request, request.QueryString, out atime);
  126. bool hasIfModifiedSince = HasIfModifiedSince (context.Request, out modifiedSince);
  127. if (hasCacheControl || hasIfModifiedSince) {
  128. bool notModified = true;
  129. foreach (CompositeEntry entry in entries) {
  130. if (entry == null)
  131. continue;
  132. if (notModified) {
  133. if ((hasCacheControl && entry.IsModifiedSince (atime)) || (hasIfModifiedSince && entry.IsModifiedSince (modifiedSince)))
  134. notModified = false;
  135. }
  136. }
  137. if (notModified) {
  138. RespondWithNotModified (context);
  139. return;
  140. }
  141. }
  142. StringBuilder contents = new StringBuilder ();
  143. using (var sw = new StringWriter (contents)) {
  144. foreach (CompositeEntry entry in entries) {
  145. if (entry == null)
  146. continue;
  147. AppendScriptContents (sw, entry);
  148. }
  149. }
  150. if (contents.Length == 0)
  151. throw new HttpException (404, "Resource not found");
  152. HttpResponse response = context.Response;
  153. DateTime utcnow = DateTime.UtcNow;
  154. response.ContentType = "text/javascript";
  155. response.Headers.Add ("Last-Modified", utcnow.ToString ("r"));
  156. response.ExpiresAbsolute = utcnow.AddYears (1);
  157. response.CacheControl = "public";
  158. response.Output.Write (contents.ToString ());
  159. if (notifyScriptLoaded)
  160. OutputScriptLoadedNotification (response.Output);
  161. }
  162. #endif
  163. void OutputScriptLoadedNotification (TextWriter writer)
  164. {
  165. writer.WriteLine ();
  166. writer.WriteLine ("if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();");
  167. }
  168. protected virtual void ProcessRequest (HttpContext context)
  169. {
  170. HttpRequest request = context.Request;
  171. bool notifyScriptLoaded = request.QueryString ["n"] == "t";
  172. #if NET_3_5
  173. List <CompositeEntry> compositeEntries = CompositeScriptReference.GetCompositeScriptEntries (request.RawUrl);
  174. if (compositeEntries != null) {
  175. SendCompositeScript (context, request, notifyScriptLoaded, compositeEntries);
  176. return;
  177. }
  178. #endif
  179. EmbeddedResource res;
  180. Assembly assembly;
  181. SendEmbeddedResource (context, out res, out assembly);
  182. HttpResponse response = context.Response;
  183. TextWriter writer = response.Output;
  184. foreach (ScriptResourceAttribute sra in assembly.GetCustomAttributes (typeof (ScriptResourceAttribute), false)) {
  185. if (String.Compare (sra.ScriptName, res.Name, StringComparison.Ordinal) == 0) {
  186. string scriptResourceName = sra.ScriptResourceName;
  187. ResourceSet rset = null;
  188. try {
  189. rset = new ResourceManager (scriptResourceName, assembly).GetResourceSet (Threading.Thread.CurrentThread.CurrentUICulture, true, true);
  190. }
  191. catch (MissingManifestResourceException) {
  192. #if TARGET_JVM // GetResourceSet does not throw MissingManifestResourceException if ressource is not exists
  193. }
  194. if (rset == null) {
  195. #endif
  196. if (scriptResourceName.EndsWith (".resources", RuntimeHelpers.StringComparison)) {
  197. scriptResourceName = scriptResourceName.Substring (0, scriptResourceName.Length - 10);
  198. rset = new ResourceManager (scriptResourceName, assembly).GetResourceSet (Threading.Thread.CurrentThread.CurrentUICulture, true, true);
  199. }
  200. #if !TARGET_JVM
  201. else
  202. throw;
  203. #endif
  204. }
  205. if (rset == null)
  206. break;
  207. writer.WriteLine ();
  208. string ns = sra.TypeName;
  209. int indx = ns.LastIndexOf ('.');
  210. if (indx > 0)
  211. writer.WriteLine ("Type.registerNamespace('" + ns.Substring (0, indx) + "')");
  212. writer.Write ("{0}={{", sra.TypeName);
  213. bool first = true;
  214. foreach (DictionaryEntry de in rset) {
  215. string value = de.Value as string;
  216. if (value != null) {
  217. if (first)
  218. first = false;
  219. else
  220. writer.Write (',');
  221. writer.WriteLine ();
  222. writer.Write ("{0}:{1}", GetScriptStringLiteral ((string) de.Key), GetScriptStringLiteral (value));
  223. }
  224. }
  225. writer.WriteLine ();
  226. writer.WriteLine ("};");
  227. break;
  228. }
  229. }
  230. if (notifyScriptLoaded)
  231. OutputScriptLoadedNotification (writer);
  232. }
  233. #if NET_3_5
  234. static void CheckIfResourceIsCompositeScript (string resourceName, ref bool includeTimeStamp)
  235. {
  236. bool isCompositeScript = resourceName.StartsWith (CompositeScriptReference.COMPOSITE_SCRIPT_REFERENCE_PREFIX, StringComparison.Ordinal);
  237. if (!isCompositeScript)
  238. return;
  239. includeTimeStamp = false;
  240. }
  241. bool HandleCompositeScriptRequest (HttpContext context, HttpRequest request, string d)
  242. {
  243. return false;
  244. }
  245. #endif
  246. // TODO: add value cache?
  247. static string GetScriptStringLiteral (string value)
  248. {
  249. if (String.IsNullOrEmpty (value))
  250. return "\"" + value + "\"";
  251. var sb = new StringBuilder ("\"");
  252. for (int i = 0; i < value.Length; i++) {
  253. char ch = value [i];
  254. switch (ch) {
  255. case '\'':
  256. sb.Append ("\\u0027");
  257. break;
  258. case '"':
  259. sb.Append ("\\\"");
  260. break;
  261. case '\\':
  262. sb.Append ("\\\\");
  263. break;
  264. case '\n':
  265. sb.Append ("\\n");
  266. break;
  267. case '\r':
  268. sb.Append ("\\r");
  269. break;
  270. default:
  271. sb.Append (ch);
  272. break;
  273. }
  274. }
  275. sb.Append ("\"");
  276. return sb.ToString ();
  277. }
  278. }
  279. }