<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>BeaverBlog &#187; css</title>
	<atom:link href="http://blog.crazybeavers.se/index.php/archive/tag/css/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.crazybeavers.se</link>
	<description>A beaver bloging about webdevelopment, XML and .Net</description>
	<lastBuildDate>Tue, 26 Jul 2011 10:59:50 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.1</generator>
		<item>
		<title>Compacting CSS on-the-fly</title>
		<link>http://blog.crazybeavers.se/index.php/archive/compacting-css-on-the-fly/</link>
		<comments>http://blog.crazybeavers.se/index.php/archive/compacting-css-on-the-fly/#comments</comments>
		<pubDate>Thu, 02 Jul 2009 10:34:08 +0000</pubDate>
		<dc:creator>Karl</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[.Net]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[css]]></category>
		<category><![CDATA[htthandler]]></category>
		<category><![CDATA[imagergallery]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[optimization]]></category>
		<category><![CDATA[sample]]></category>

		<guid isPermaLink="false">http://blog.crazybeavers.se/?p=95</guid>
		<description><![CDATA[I&#8217;m currently doing quite a lot of work on my ny MVC-version of Imager Gallery. I still have a lot to do before I have anything to release (or even use myself) though but I thought I could release a few snippets that I&#8217;ve found useful. First out is a HttpHandler that will process .css-files [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m currently doing quite a lot of work on my ny MVC-version of Imager Gallery. I still have a lot to do before I have anything to release (or even use myself) though but I thought I could release a few snippets that I&#8217;ve found useful.</p>
<p>First out is a HttpHandler that will process .css-files and remove any unused whitespace from the file before sending it to the client. I&#8217;ve been meaning to write this for a long time but never really had the time until someone posted a link about it over at <a href="http://www.aspsidan.se/default.asp?page=forum&#038;fp=showPost&#038;fId=31&#038;pId=584376">ASPSidan.se</a> showing their own implementation. Reading up on his post about it I found that it was based on <a href="http://webdevel.blogspot.com/2007/09/csscompact-webhandler-for-shrinking-css.html">a solution by Sam Collett</a>. Both implementations lacked a few things that I wanted to have so I sat down with Sams code and started improving it, mainly making it a work as a handler for .css-files instead of a Generic Handler wanting a querystring but also adding caching and compiling the regular expression as a static member.</p>
<p>To use this, just pop it in a .cs-file in your your App_Code folder and add it to your web.config (as described in the comments for the class). You also need to configure your IIS to route .css-files through the asp.net process to make it run (not needed under IIS7 or IIS6 configured for MVC). Hope you find it useful!</p>
<pre class="brush: csharp; title: ;">
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Caching;

namespace HttpHandlers
{
    /// &lt;summary&gt;
    /// Handler for compacting css-files on the fly
    /// Based on solution by Sam Collett found at
    /// http://webdevel.blogspot.com/2007/09/csscompact-webhandler-for-shrinking-css.html
    ///
    /// Needs to be added to web.config under System.Web/httpHandlers like this
    /// &lt;add verb=&quot;GET,HEAD&quot; path=&quot;*.css&quot; type=&quot;HttpHandlers.CssCompactHandler&quot;/&gt;
    ///
    /// For debuing purposes you can append a querystring whenbrowsing to your .css-file
    /// to skip the compacting. It would look like this:
    /// http://mySite/Content/Site.css?noCompact=1
    /// &lt;/summary&gt;
    public class CssCompactHandler : IHttpHandler
    {
        // Staticly compiled regex to avoid compiling it each request
        private static Regex RegexRemoval = new Regex(@&quot;^\s+|/\*([^*\\\\]|\*(?!/))+\*/|\r|\n|\t&quot;, RegexOptions.Multiline | RegexOptions.Compiled);

        public void ProcessRequest(HttpContext context)
        {
            HttpResponse Response = context.Response;
            HttpRequest Request = context.Request;
            Cache Cache = context.Cache;

            FileInfo fileInfo = new FileInfo(Request.PhysicalPath);
            if (!fileInfo.Exists)
            {
                Response.StatusDescription = &quot;The server has not found anything that matches the requested URI.&quot;;
                Response.StatusCode = 404;
                Response.End();
            }

            Response.ContentType = &quot;text/css&quot;;
            Response.Cache.SetLastModified(fileInfo.LastWriteTime);

            // If we are in debugmode (set in web.config) then
            // we dont want to cache the css since we are probably
            // still in development
            if (context.IsDebuggingEnabled)
            {
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
            }
            else
            {
                Response.Cache.SetCacheability(HttpCacheability.Public);
                Response.Cache.SetExpires(DateTime.Now.AddDays(1));
            }

            // HEAD requests only need the headers so we skip the
            // content here
            if (Request.HttpMethod != &quot;HEAD&quot;)
            {
                string cacheName = string.Format(&quot;CssCompactHandlerCache_{0}&quot;, fileInfo.FullName);
                string cacheValue = Cache[cacheName] as string;
                if (cacheValue != null &amp;&amp; Request.QueryString[&quot;noCompact&quot;] == null)
                {
                    Response.Write(cacheValue);
                    Response.End();
                }

                using (StreamReader cssStream = fileInfo.OpenText())
                {
                    string cssContent = cssStream.ReadToEnd();
                    if (Request.QueryString[&quot;noCompact&quot;] == null)
                    {
                        cssContent = RegexRemoval.Replace(cssContent, &quot;&quot;);

                        // Set up a CacheDependency on the css-file,
                        // this way the cache will be invalidated if
                        // we change the file
                        CacheDependency dependency = new CacheDependency(fileInfo.FullName);
                        Cache.Add(string.Format(&quot;CssCompactHandlerCache_{0}&quot;, fileInfo.FullName), cssContent, dependency, DateTime.Now.AddYears(1), Cache.NoSlidingExpiration, CacheItemPriority.AboveNormal, null);
                    }
                    Response.Write(cssContent);
                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.crazybeavers.se/index.php/archive/compacting-css-on-the-fly/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

