public
Created

CSS parsing

  • Download Gist
gistfile1.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Caching;
 
namespace UmgCommon.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="UmgCommon.CDN.CssRewriteHandler, UmgCommon" />
* 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;
 
//remove the X
if (filename.EndsWith("x"))
{
filename = filename.Substring(0, filename.Length - 1);
}
if (!File.Exists(filename))
{
context.Response.StatusCode = 404;
return;
}
 
string css = File.ReadAllText(filename);
string suffix = "";
if (CDNHelper.IsCDNEnabled)
{
 
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();
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);
}
}
 
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.