We run more private classes than public classes, and we have different ticket options based on purchasing power globally. Take advantage of our Retraining Programs and Advocate Programs!

Reformat your CSS on the fly

Audience

No items found

Table of Contents

Have you ever, when developing a website, been frustrated when you get a different result when you deploy your application to http://site/ and http://site/app/.

iStock_000001095647XSmall

I don’t know about you, but it annoys the hell out of me. All that work in CSS and none of your images work when you run it in a different location. This would be especially frustrating when you are running multiple feature branches and need Kerberos interaction. The amount of work required to get Kerberos to work (SPN’s, URL’s, Delegation and AD) limits the number of sites you can have in an enterprise environment.

I have just two. I have a site for the latest candidate release and one to host all of my feature branches. As I am using TFS I identify my Feature with either a Requirement or Change Request Id and name everything after this.

Thus I have http://site/ and http://site-dev/1345. This makes it easy to find and test, and my CI build at the ends of the day just overwrites the previous version.

This means that all of your css like this…

.down {  
   padding-right:14px;  
   background: url('/UI/Resources/Images/arrow_down.gif') no-repeat 100% 50%;   
}

…will not work in one of your locations 🙁 This makes me sad…

So, in order to cheer up your CSS, you can give it a little bit of .NET Omph…

The first thing you need to do is get .NET to handle ALL of your requests, and not just for the ASP.NET pages.

image

Add a “Wildcard application mapping” to the “aspnet_isapi.dll” and you are good to go…

To process the css we need an HttpHandler, this is dead easy to implement and action so:

Imports System.Web
Imports System.Text.RegularExpressions


Public Class CssHttpHandler
    Implements IHttpHandler

    Public ReadOnly Property IsReusable() As Boolean Implements System.Web.IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

    Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest
        context.Response.ContentType = "text/css"

        'Get the file from the query stirng
        Dim File As String = context.Request.FilePath

        ' Find the actual path
        Dim Path As String = context.Server.MapPath(File)

        'Limit to only css files
        If Not System.IO.Path.GetExtension(Path) = ".css" Then
            context.Response.End()
        End If

        'Make sure file exists
        If Not System.IO.File.Exists(Path) Then
            context.Response.End()
        End If


        ' Open the file, read the contents and replace the variables
        Using css As System.IO.StreamReader = New System.IO.StreamReader(Path)
            Dim cssText As String = css.ReadToEnd()

            ' Replace url's
            Dim rximg As New Regex("url('*(.+?)'*)")
            For Each m As Match In rximg.Matches(cssText)
                cssText = cssText.Replace(m.Groups(1).Value, HandleRootOperator(m.Groups(1).Value))
            Next

            context.Response.Write("/* Please use the ~ operator in front of all URL's. e.g. url('~/UI/Resources/Images/Image.gif') will be converted at runtime to point at the root of the application. */" & vbCrLf & cssText)
        End Using

    End Sub

    ' Methods
    Public Function HandleRootOperator(ByVal virtualUrl As String) As String
        If Not String.IsNullOrEmpty(virtualUrl) Then
            If virtualUrl.StartsWith("^~/", StringComparison.OrdinalIgnoreCase) Then
                Return ("^" & Me.applicationPath & virtualUrl.Substring(2))
            End If
            If virtualUrl.StartsWith("~/", StringComparison.OrdinalIgnoreCase) Then
                Return (Me.applicationPath & virtualUrl.Substring(1))
            End If
        End If
        Return virtualUrl
    End Function




    ' Fields
    Private applicationPath As String = IIf((HttpRuntime.AppDomainAppVirtualPath.Length > 1), HttpRuntime.AppDomainAppVirtualPath, String.Empty)


End Class

Now add the Handler to you web.config

<httpHandlers>
  <add verb="*" path="*.css" type="Company.System.Product.CssHttpHandler, Company.System.Product" />
</httpHandlers>

 

And you are done 🙂

Technorati Tags:    

Create a conversation around this article

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Want to learn more?

Check out the many training classes that we have.

No items found

OUR TEAM

We believe that every company deserves high quality software delivered on a regular cadence that meets its customers needs. Our goal is to help you reduce your cycle time, improve your time to market, and minimise any organisational friction in achieving your goals.

naked Agility Limited is a professional company that offers training, coaching, mentoring, and facilitation to help people and teams evolve, integrate, and continuously improve.

We recognise the positive impact that a happy AND motivated workforce, that has purpose, has on client experience. We help change mindsets towards a people-first culture where everyone encourages others to learn and grow. The resulting divergent thinking leads to many different ideas and opportunities for the success of the organisation.