ScriptResourceHandler.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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 hasIfModifiedSince = HasIfModifiedSince (context.Request, out modifiedSince);
  126. if (hasIfModifiedSince) {
  127. bool notModified = true;
  128. foreach (CompositeEntry entry in entries) {
  129. if (entry == null)
  130. continue;
  131. if (notModified) {
  132. if (hasIfModifiedSince && entry.IsModifiedSince (modifiedSince))
  133. notModified = false;
  134. }
  135. }
  136. if (notModified) {
  137. RespondWithNotModified (context);
  138. return;
  139. }
  140. }
  141. StringBuilder contents = new StringBuilder ();
  142. using (var sw = new StringWriter (contents)) {
  143. foreach (CompositeEntry entry in entries) {
  144. if (entry == null)
  145. continue;
  146. AppendScriptContents (sw, entry);
  147. }
  148. }
  149. if (contents.Length == 0)
  150. throw new HttpException (404, "Resource not found");
  151. HttpResponse response = context.Response;
  152. DateTime utcnow = DateTime.UtcNow;
  153. response.ContentType = "text/javascript";
  154. response.Headers.Add ("Last-Modified", utcnow.ToString ("r"));
  155. response.ExpiresAbsolute = utcnow.AddYears (1);
  156. response.CacheControl = "public";
  157. response.Output.Write (contents.ToString ());
  158. if (notifyScriptLoaded)
  159. OutputScriptLoadedNotification (response.Output);
  160. }
  161. #endif
  162. void OutputScriptLoadedNotification (TextWriter writer)
  163. {
  164. writer.WriteLine ();
  165. writer.WriteLine ("if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();");
  166. }
  167. protected virtual void ProcessRequest (HttpContext context)
  168. {
  169. HttpRequest request = context.Request;
  170. bool notifyScriptLoaded = request.QueryString ["n"] == "t";
  171. #if NET_3_5
  172. List <CompositeEntry> compositeEntries = CompositeScriptReference.GetCompositeScriptEntries (request.RawUrl);
  173. if (compositeEntries != null) {
  174. SendCompositeScript (context, request, notifyScriptLoaded, compositeEntries);
  175. return;
  176. }
  177. #endif
  178. EmbeddedResource res;
  179. Assembly assembly;
  180. SendEmbeddedResource (context, out res, out assembly);
  181. HttpResponse response = context.Response;
  182. TextWriter writer = response.Output;
  183. foreach (ScriptResourceAttribute sra in assembly.GetCustomAttributes (typeof (ScriptResourceAttribute), false)) {
  184. if (String.Compare (sra.ScriptName, res.Name, StringComparison.Ordinal) == 0) {
  185. string scriptResourceName = sra.ScriptResourceName;
  186. ResourceSet rset = null;
  187. try {
  188. rset = new ResourceManager (scriptResourceName, assembly).GetResourceSet (Threading.Thread.CurrentThread.CurrentUICulture, true, true);
  189. }
  190. catch (MissingManifestResourceException) {
  191. #if TARGET_JVM // GetResourceSet does not throw MissingManifestResourceException if ressource is not exists
  192. }
  193. if (rset == null) {
  194. #endif
  195. if (scriptResourceName.EndsWith (".resources", RuntimeHelpers.StringComparison)) {
  196. scriptResourceName = scriptResourceName.Substring (0, scriptResourceName.Length - 10);
  197. rset = new ResourceManager (scriptResourceName, assembly).GetResourceSet (Threading.Thread.CurrentThread.CurrentUICulture, true, true);
  198. }
  199. #if !TARGET_JVM
  200. else
  201. throw;
  202. #endif
  203. }
  204. if (rset == null)
  205. break;
  206. writer.WriteLine ();
  207. string ns = sra.TypeName;
  208. int indx = ns.LastIndexOf ('.');
  209. if (indx > 0)
  210. writer.WriteLine ("Type.registerNamespace('" + ns.Substring (0, indx) + "')");
  211. writer.Write ("{0}={{", sra.TypeName);
  212. bool first = true;
  213. foreach (DictionaryEntry de in rset) {
  214. string value = de.Value as string;
  215. if (value != null) {
  216. if (first)
  217. first = false;
  218. else
  219. writer.Write (',');
  220. writer.WriteLine ();
  221. writer.Write ("{0}:{1}", GetScriptStringLiteral ((string) de.Key), GetScriptStringLiteral (value));
  222. }
  223. }
  224. writer.WriteLine ();
  225. writer.WriteLine ("};");
  226. break;
  227. }
  228. }
  229. if (notifyScriptLoaded)
  230. OutputScriptLoadedNotification (writer);
  231. }
  232. #if NET_3_5
  233. static void CheckIfResourceIsCompositeScript (string resourceName, ref bool includeTimeStamp)
  234. {
  235. bool isCompositeScript = resourceName.StartsWith (CompositeScriptReference.COMPOSITE_SCRIPT_REFERENCE_PREFIX, StringComparison.Ordinal);
  236. if (!isCompositeScript)
  237. return;
  238. includeTimeStamp = false;
  239. }
  240. bool HandleCompositeScriptRequest (HttpContext context, HttpRequest request, string d)
  241. {
  242. return false;
  243. }
  244. #endif
  245. // TODO: add value cache?
  246. static string GetScriptStringLiteral (string value)
  247. {
  248. if (String.IsNullOrEmpty (value))
  249. return "\"" + value + "\"";
  250. var sb = new StringBuilder ("\"");
  251. for (int i = 0; i < value.Length; i++) {
  252. char ch = value [i];
  253. switch (ch) {
  254. case '\'':
  255. sb.Append ("\\u0027");
  256. break;
  257. case '"':
  258. sb.Append ("\\\"");
  259. break;
  260. case '\\':
  261. sb.Append ("\\\\");
  262. break;
  263. case '\n':
  264. sb.Append ("\\n");
  265. break;
  266. case '\r':
  267. sb.Append ("\\r");
  268. break;
  269. default:
  270. sb.Append (ch);
  271. break;
  272. }
  273. }
  274. sb.Append ("\"");
  275. return sb.ToString ();
  276. }
  277. }
  278. }