Skip to content

Instantly share code, notes, and snippets.

@nicwise
Created December 22, 2011 15:24
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save nicwise/1510675 to your computer and use it in GitHub Desktop.
CSS parsing
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using System.Web;
using System.Web.Caching;
namespace Common.CDN
{
/*
*
* Re parses the CSS to add in the cache key
*
* add this into the web.config
*
* <add name="CssRewriter" verb="*" path="*.css" preCondition="integratedMode" type="Common.CDN.CssRewriteHandler, Common" />
* add it in system.webServer -> handlers
*
* */
public class CssRewriteHandler : IHttpHandler
{
public bool IsReusable { get { return true; } }
public void ProcessRequest(HttpContext context)
{
string filename = context.Request.PhysicalPath;
if (!File.Exists(filename))
{
context.Response.StatusCode = 404;
return;
}
string css = File.ReadAllText(filename);
string suffix = "";
if (CDNHelper.IsCDNEnabled) //generic on/off switch for the whole CDN thing
{
object res = context.Cache["csscache|" + filename];
if (res != null)
{
css = res.ToString();
context.Response.Write("/* Processed by the CDN CSS rewriter from cache */\n");
}
else
{
Stopwatch sw = new Stopwatch();
sw.Start();
//our unique cache id. usually the time, rounded down to 15 mins, eg 0115 or 0245.
// means our cache is wiped out every 15 mins, but thats ok in this case.
// goes on the end of the URLs eg foo.jpg?0115
suffix = CDNHelper.UniqueId;
css = css.Replace(".jpg", ".jpg" + suffix)
.Replace(".png", ".png" + suffix)
.Replace(".gif", ".gif" + suffix);
sw.Stop();
context.Cache.Add("csscache|" + filename, css, new CacheDependency(filename), DateTime.Now.AddMinutes(60), Cache.NoSlidingExpiration, CacheItemPriority.Normal,null);
context.Response.Write(string.Format("/* Processed by the CDN CSS rewriter in {0}ms */\n", sw.ElapsedMilliseconds));
}
}
context.Response.Write(css);
context.Response.ContentType = "text/css";
context.Response.AddFileDependency(filename);
HttpCachePolicy cache = context.Response.Cache;
cache.SetCacheability(HttpCacheability.Public);
if (CDNHelper.IsCDNEnabled)
{
cache.SetETag(suffix);
}
cache.SetLastModifiedFromFileDependencies();
cache.SetMaxAge(TimeSpan.FromMinutes(60));
cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment