/// <summary> /// Excute the request and response the needes content /// <para>Save the response in the Output cach for next requests</para> /// </summary> /// <param name="context"></param> /// <param name="absoluteFiles"></param> /// <param name="minify"></param> /// <param name="versionHash"></param> /// <param name="encodingMgr"></param> public void Excute(HttpContext context, string[] absoluteFiles, Minifier minify, int versionHash, EncodingManager encodingMgr) { context.Response.Write(SR.GetString(SR.CREDIT_STRING)); List<string> exsitingFiles = new List<string>(); for (int i = 0; i < absoluteFiles.Length; i++) { WriteContent(context, GetFileContent(absoluteFiles[i], minify, exsitingFiles)); } SetResponseCacheSettings(context, exsitingFiles.ToArray()); if (encodingMgr.IsEncodingEnabled) { encodingMgr.CompressResponse(); encodingMgr.SetResponseEncodingType(); } }
/// <summary> /// Process the request /// </summary> /// <param name="context"></param> public virtual void ProcessRequest(HttpContext context) { int versionHash; DateTime lastUpdate; string[] relativeFiles = context.Request.QueryString["d"].Split(','); string[] absoluteFiles = GetFilesInfo(relativeFiles,context, out versionHash,out lastUpdate); context.Response.Clear(); SetHeaders(context, lastUpdate, versionHash); CheckETag(context, versionHash); Minifier currentMinifier = new Minifier(Minify); EncodingManager encodingMgr = new EncodingManager(context); if (!IsCompressContent()) { encodingMgr.PreferredEncodingType = EncodingManager.EncodingType.None; } Settings.Instance.CurrentStorage.Excute(context, absoluteFiles, currentMinifier, versionHash, encodingMgr); }
/// <summary> /// Handles the PostReleaseRequestState event. /// </summary> /// <param name="sender">The object that raised the event (HttpApplication)</param> /// <param name="e">The event data</param> void OnPostReleaseRequestState(object sender, EventArgs e) { HttpApplication app = sender as HttpApplication; if (app.Context == null) return; // This part of the module compress only handlers from type System.Web.UI.Page // Other types such JavaScript or CSS files will be compressed in an httpHandelr. // Here we check if the current handler if a Page, if so, we compress it. if (app.Context.CurrentHandler is System.Web.UI.Page && app.Context.Response != null && Util.IsUIPageContentType(app.Context.Response.ContentType)) { // Check if the path is not excluded. if (!settings.IsValidPath(app.Request.AppRelativeCurrentExecutionFilePath)) return; // Check if the mime type is not ecluded. (Use to exclude pages that generate specific mime type (such image or Excel...)) if (!settings.IsValidType(app.Response.ContentType)) return; // Because there is a problem with async postbacks compression, we check here if the current request if an 'MS AJAX' call. // If so, we will not compress it. if (settings.CompressPage && !(Util.IsMsAjaxRequest(app.Context) && settings.MSAjaxVersion < 3.5)) { EncodingManager encodingMgr = new EncodingManager(app.Context); if (encodingMgr.IsEncodingEnabled) { encodingMgr.CompressResponse(); encodingMgr.SetResponseEncodingType(); } } if (settings.AutoMode) { bool processCss = settings.CompressCSS || settings.MinifyContent; bool processJs = settings.CompressJavaScript || settings.MinifyContent; app.Response.Filter = new AutoModeFilterStream(app.Response.Filter,app.Response.ContentEncoding, processJs,processCss); } } }
/// <summary> /// Handles the PreRequestHandlerExecute event. /// The compression moved to this step to catch Server.Transfer operation /// </summary> /// <param name="sender">The object that raised the event (HttpApplication)</param> /// <param name="e">The event data</param> void context_PreRequestHandlerExecute(object sender, EventArgs e) { HttpApplication app = sender as HttpApplication; if (app.Context == null || app.Context.Response == null) return; // This part of the module compress only handlers from type System.Web.UI.Page // Other types such JavaScript or CSS files will be compressed in an httpHandelr. // Here we check if the current handler if a Page handler, if so, we compress it. if (app.Context.CurrentHandler is System.Web.UI.Page && app.Context.Response != null) { // Check if the path is not excluded. if (!settings.IsValidPath(app.Request.AppRelativeCurrentExecutionFilePath)) return; if (Util.IsToolkitScriptManagerCombiner(app.Request)) return; if (settings.CompressPage && !Util.IsContainExcludedParamValue(app.Context) && !(Util.IsMsAjaxRequest(app.Context) && settings.MSAjaxVersion < 3.5)) { EncodingManager encodingMgr = new EncodingManager(app.Context); if (encodingMgr.IsEncodingEnabled) { // Add preferredEncoding to the context.items for use later in the pipeline app.Context.Items.Add("preferredEncoding", encodingMgr.PreferredEncoding); //Add the compression filter encodingMgr.CompressResponse(); } } if (settings.AutoMode && !Util.IsMsAjaxRequest(app.Context)) { bool processCss = settings.CompressCSS || settings.MinifyContent || settings.CombineCSS; bool processJs = settings.CompressJavaScript || settings.MinifyContent; app.Response.Filter = new AutoModeFilterStream(app.Response.Filter, app.Response.ContentEncoding, processJs, processCss, settings.CombineCSS, settings.CombineHeaderScripts); } } }
private void OnPreRequestHandlerExecute(object sender, EventArgs e) { HttpApplication app = sender as HttpApplication; // Check if the current request is Webresource.axd if (app.Context.CurrentHandler is AssemblyResourceLoader) { HttpResponse response = app.Context.Response; int queryHash = (app.Context.Request.QueryString.ToString()).GetHashCode(); // Check if the ETag is match. If so, we don't send nothing to the client, and stop here. CheckETag(app, queryHash); try { // Parse the QueryString into parts Quadruplet<Char, String, String, String> urlInfo = GetDataFromQuery(app.Context.Request.QueryString); // Load the assembly Assembly assembly = GetAssembly(urlInfo.First, urlInfo.Second); if (assembly == null) ThrowHttpException(404, SR.WebResourceCompressionModule_AssemblyNotFound, urlInfo.Forth); // Get the resource info from assembly. Quadruplet<bool, bool, string, bool> resourceInfo = GetResourceInfo(assembly, urlInfo.Third); if (!resourceInfo.First) ThrowHttpException(404, SR.WebResourceCompressionModule_AssemblyNotFound, urlInfo.Forth); // If the WebResource needs to perform substitution (WebResource inside WebResource), we leave it to the original AssemblyResourceLoader handler ;-) if (resourceInfo.Second) return; response.Clear(); // Set the response cache headers SetCachingHeadersForWebResource(response.Cache, queryHash); // Set the response content type response.ContentType = resourceInfo.Third; EncodingManager encodingMgr = new EncodingManager(app.Context); // Write content with compression if (resourceInfo.Forth && (Settings.Instance.CompressWebResource || Settings.Instance.MinifyContent)) { using (StreamReader resourceStream = new StreamReader(assembly.GetManifestResourceStream(urlInfo.Third), true)) { ProcessAndWriteToStream(resourceStream, app.Context, encodingMgr); } } // Write content without compression or minify else { using (Stream resourceStream = assembly.GetManifestResourceStream(urlInfo.Third)) { WriteToStream(resourceStream, response.OutputStream); } } response.OutputStream.Flush(); app.CompleteRequest(); } catch (ArgumentNullException) { return; } catch (TargetInvocationException) { return; } catch (System.Security.Cryptography.CryptographicException) { return; } } }
/// <summary> /// Process & Write a StreamReader to an output stream /// </summary> /// <param name="reader"></param> /// <param name="context"></param> /// <param name="encodingMgr"></param> private static void ProcessAndWriteToStream(StreamReader reader, HttpContext context, EncodingManager encodingMgr) { string content = SR.GetString(SR.CREDIT_STRING); if (Settings.Instance.MinifyContent) { if (context.Response.ContentType.Contains("javascript")) { JavaScriptMinifier _Minifier = new JavaScriptMinifier(); content += _Minifier.Minify(reader); } else if (context.Response.ContentType.Contains("css")) { CssMinifier _Minifier = new CssMinifier(); content += _Minifier.Minify(reader); } else { content += reader.ReadToEnd(); } } else { content += reader.ReadToEnd(); } if (encodingMgr.IsEncodingEnabled && Settings.Instance.CompressWebResource) { encodingMgr.SetResponseEncodingType(); byte[] compressed = encodingMgr.CompressString(content); context.Response.OutputStream.Write(compressed, 0, compressed.Length); } else { context.Response.Write(content); } }
/// <summary> /// Excute the request and response the needes content /// <para>Save the response in the file system for next requests</para> /// </summary> /// <param name="context"></param> /// <param name="filesInfo"></param> /// <param name="minify"></param> /// <param name="versionHash"></param> /// <param name="encodingMgr"></param> public void Excute(HttpContext context, string[] filesInfo, Minifier minify, int versionHash, EncodingManager encodingMgr) { string phisicalRoot = context.Server.MapPath("~/") + cReferencesCache; string fullPath; if (encodingMgr.IsEncodingEnabled) { fullPath = phisicalRoot + "comp_" + encodingMgr.PreferredEncoding + "_" + versionHash + (minify.Target is JavaScriptCompressionHandler ? ".js" : ".css"); encodingMgr.SetResponseEncodingType(); } else { fullPath = phisicalRoot + versionHash + (minify.Target is JavaScriptCompressionHandler ? ".js" : ".css"); } SetResponseCacheSettings(context, null); if (!File.Exists(fullPath)) { lock (_syncObject) { if (!File.Exists(fullPath)) { if (!Directory.Exists(phisicalRoot)) { Directory.CreateDirectory(phisicalRoot); } if (encodingMgr.IsEncodingEnabled) { StringBuilder contentSb = new StringBuilder(SR.GetString(SR.CREDIT_STRING)); foreach (string fileName in filesInfo) { if (fileName.StartsWith("NOT_FOUND", StringComparison.Ordinal)) { contentSb.AppendFormat(SR.File_FileNotFound + Environment.NewLine, Path.GetFileName(fileName.Split('|')[1])); } else { using (StreamReader reader = new StreamReader(fileName, context.Response.ContentEncoding)) { if (Settings.Instance.IsValidPathForMinify(fileName)) { contentSb.AppendLine(minify(reader)); } else { contentSb.AppendLine(reader.ReadToEnd()); } } } } using (FileStream fs = new FileStream(fullPath, FileMode.Create)) { byte[] compressedContent = encodingMgr.CompressString(contentSb.ToString()); fs.Write(compressedContent, 0, compressedContent.Length); } // Release the StringBuilder contentSb.Length = 0; } else { using (FileStream fs = new FileStream(fullPath, FileMode.Create)) using (StreamWriter sw = new StreamWriter(fs,context.Response.ContentEncoding)) { string content = SR.GetString(SR.CREDIT_STRING); sw.WriteLine(content); foreach (string fileName in filesInfo) { if (fileName.Length == 0) { content = string.Format(CultureInfo.CurrentCulture, SR.File_FileNotFound, Path.GetFileName(fileName)); } else { using (StreamReader reader = new StreamReader(fileName, context.Response.ContentEncoding)) { if (Settings.Instance.IsValidPathForMinify(fileName)) { content = minify(reader); } else { content = reader.ReadToEnd(); } } } sw.WriteLine(content); } } } } } } context.Response.TransmitFile(fullPath); }