ScriptResourceHandler.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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. void AppendResourceScriptContents (StringWriter sw, CompositeEntry entry)
  60. {
  61. if (entry.Assembly == null || entry.Attribute == null || String.IsNullOrEmpty (entry.NameOrPath))
  62. return;
  63. using (Stream s = entry.Assembly.GetManifestResourceStream (entry.NameOrPath)) {
  64. if (s == null)
  65. throw new HttpException (404, "Resource '" + entry.NameOrPath + "' not found");
  66. if (entry.Attribute.PerformSubstitution) {
  67. using (var r = new StreamReader (s)) {
  68. new PerformSubstitutionHelper (entry.Assembly).PerformSubstitution (r, sw);
  69. }
  70. } else {
  71. using (var r = new StreamReader (s)) {
  72. string line = r.ReadLine ();
  73. while (line != null) {
  74. sw.WriteLine (line);
  75. line = r.ReadLine ();
  76. }
  77. }
  78. }
  79. }
  80. }
  81. void AppendFileScriptContents (StringWriter sw, CompositeEntry entry)
  82. {
  83. // FIXME: should we limit the script size in any way?
  84. if (String.IsNullOrEmpty (entry.NameOrPath))
  85. return;
  86. string mappedPath;
  87. if (!HostingEnvironment.HaveCustomVPP) {
  88. // We'll take a shortcut here by bypassing the default VPP layers
  89. mappedPath = HostingEnvironment.MapPath (entry.NameOrPath);
  90. if (!File.Exists (mappedPath))
  91. return;
  92. sw.Write (File.ReadAllText (mappedPath));
  93. return;
  94. }
  95. VirtualPathProvider vpp = HostingEnvironment.VirtualPathProvider;
  96. if (!vpp.FileExists (entry.NameOrPath))
  97. return;
  98. VirtualFile file = vpp.GetFile (entry.NameOrPath);
  99. if (file == null)
  100. return;
  101. using (Stream s = file.Open ()) {
  102. using (var r = new StreamReader (s)) {
  103. string line = r.ReadLine ();
  104. while (line != null) {
  105. sw.WriteLine (line);
  106. line = r.ReadLine ();
  107. }
  108. }
  109. }
  110. }
  111. void AppendScriptContents (StringWriter sw, CompositeEntry entry)
  112. {
  113. if (entry.Assembly != null)
  114. AppendResourceScriptContents (sw, entry);
  115. else
  116. AppendFileScriptContents (sw, entry);
  117. }
  118. void SendCompositeScript (HttpContext context, HttpRequest request, bool notifyScriptLoaded, List <CompositeEntry> entries)
  119. {
  120. if (entries.Count == 0)
  121. throw new HttpException (404, "Resource not found");
  122. long atime;
  123. DateTime modifiedSince;
  124. bool hasIfModifiedSince = HasIfModifiedSince (context.Request, out modifiedSince);
  125. if (hasIfModifiedSince) {
  126. bool notModified = true;
  127. foreach (CompositeEntry entry in entries) {
  128. if (entry == null)
  129. continue;
  130. if (notModified) {
  131. if (hasIfModifiedSince && entry.IsModifiedSince (modifiedSince))
  132. notModified = false;
  133. }
  134. }
  135. if (notModified) {
  136. RespondWithNotModified (context);
  137. return;
  138. }
  139. }
  140. StringBuilder contents = new StringBuilder ();
  141. using (var sw = new StringWriter (contents)) {
  142. foreach (CompositeEntry entry in entries) {
  143. if (entry == null)
  144. continue;
  145. AppendScriptContents (sw, entry);
  146. }
  147. }
  148. if (contents.Length == 0)
  149. throw new HttpException (404, "Resource not found");
  150. HttpResponse response = context.Response;
  151. DateTime utcnow = DateTime.UtcNow;
  152. response.ContentType = "text/javascript";
  153. response.Headers.Add ("Last-Modified", utcnow.ToString ("r"));
  154. response.ExpiresAbsolute = utcnow.AddYears (1);
  155. response.CacheControl = "public";
  156. response.Output.Write (contents.ToString ());
  157. if (notifyScriptLoaded)
  158. OutputScriptLoadedNotification (response.Output);
  159. }
  160. void OutputScriptLoadedNotification (TextWriter writer)
  161. {
  162. writer.WriteLine ();
  163. writer.WriteLine ("if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();");
  164. }
  165. protected virtual void ProcessRequest (HttpContext context)
  166. {
  167. HttpRequest request = context.Request;
  168. bool notifyScriptLoaded = request.QueryString ["n"] == "t";
  169. List <CompositeEntry> compositeEntries = CompositeScriptReference.GetCompositeScriptEntries (request.RawUrl);
  170. if (compositeEntries != null) {
  171. SendCompositeScript (context, request, notifyScriptLoaded, compositeEntries);
  172. return;
  173. }
  174. EmbeddedResource res;
  175. Assembly assembly;
  176. SendEmbeddedResource (context, out res, out assembly);
  177. HttpResponse response = context.Response;
  178. TextWriter writer = response.Output;
  179. foreach (ScriptResourceAttribute sra in assembly.GetCustomAttributes (typeof (ScriptResourceAttribute), false)) {
  180. if (String.Compare (sra.ScriptName, res.Name, StringComparison.Ordinal) == 0) {
  181. string scriptResourceName = sra.ScriptResourceName;
  182. ResourceSet rset = null;
  183. try {
  184. rset = new ResourceManager (scriptResourceName, assembly).GetResourceSet (Threading.Thread.CurrentThread.CurrentUICulture, true, true);
  185. }
  186. catch (MissingManifestResourceException) {
  187. if (scriptResourceName.EndsWith (".resources", RuntimeHelpers.StringComparison)) {
  188. scriptResourceName = scriptResourceName.Substring (0, scriptResourceName.Length - 10);
  189. rset = new ResourceManager (scriptResourceName, assembly).GetResourceSet (Threading.Thread.CurrentThread.CurrentUICulture, true, true);
  190. }
  191. else
  192. throw;
  193. }
  194. if (rset == null)
  195. break;
  196. writer.WriteLine ();
  197. string ns = sra.TypeName;
  198. int indx = ns.LastIndexOf ('.');
  199. if (indx > 0)
  200. writer.WriteLine ("Type.registerNamespace('" + ns.Substring (0, indx) + "')");
  201. writer.Write ("{0}={{", sra.TypeName);
  202. bool first = true;
  203. foreach (DictionaryEntry de in rset) {
  204. string value = de.Value as string;
  205. if (value != null) {
  206. if (first)
  207. first = false;
  208. else
  209. writer.Write (',');
  210. writer.WriteLine ();
  211. writer.Write ("{0}:{1}", GetScriptStringLiteral ((string) de.Key), GetScriptStringLiteral (value));
  212. }
  213. }
  214. writer.WriteLine ();
  215. writer.WriteLine ("};");
  216. break;
  217. }
  218. }
  219. if (notifyScriptLoaded)
  220. OutputScriptLoadedNotification (writer);
  221. }
  222. static void CheckIfResourceIsCompositeScript (string resourceName, ref bool includeTimeStamp)
  223. {
  224. bool isCompositeScript = resourceName.StartsWith (CompositeScriptReference.COMPOSITE_SCRIPT_REFERENCE_PREFIX, StringComparison.Ordinal);
  225. if (!isCompositeScript)
  226. return;
  227. includeTimeStamp = false;
  228. }
  229. bool HandleCompositeScriptRequest (HttpContext context, HttpRequest request, string d)
  230. {
  231. return false;
  232. }
  233. // TODO: add value cache?
  234. static string GetScriptStringLiteral (string value)
  235. {
  236. if (String.IsNullOrEmpty (value))
  237. return "\"" + value + "\"";
  238. var sb = new StringBuilder ("\"");
  239. for (int i = 0; i < value.Length; i++) {
  240. char ch = value [i];
  241. switch (ch) {
  242. case '\'':
  243. sb.Append ("\\u0027");
  244. break;
  245. case '"':
  246. sb.Append ("\\\"");
  247. break;
  248. case '\\':
  249. sb.Append ("\\\\");
  250. break;
  251. case '\n':
  252. sb.Append ("\\n");
  253. break;
  254. case '\r':
  255. sb.Append ("\\r");
  256. break;
  257. default:
  258. sb.Append (ch);
  259. break;
  260. }
  261. }
  262. sb.Append ("\"");
  263. return sb.ToString ();
  264. }
  265. }
  266. }