5,427,303 members and growing! (20,541 online)
Email Password   helpLost your password?
Web Development » ASP.NET » General     Intermediate License: The Common Development and Distribution License (CDDL)

CSS Variables

By Mark Nischalke

Using HTTPHandlers to support dynamic CSS
Windows, .NET, Visual Studio, ASP.NET, Dev

Posted: 17 Dec 2006
Updated: 17 Dec 2006
Views: 30,756
Bookmarked: 22 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
9 votes for this Article.
Popularity: 2.74 Rating: 2.87 out of 5
4 votes, 44.4%
1
1 vote, 11.1%
2
0 votes, 0.0%
3
2 votes, 22.2%
4
2 votes, 22.2%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Introduction

User want flexibility in the websites they visit, they want to define what content they see and how it is shown. Website developers want to give them that ability but need to balance it against maintainability. Using Cascading Style Sheet (CSS) the developer can specify certain base layouts, or themes, and allow the user to change these at runtime. However, creating separate files for all possibilities is just not reasonable. A better way would be to change certain CSS values at runtime based on settings specified by the user, yet CSS does not have variables that can be evaluated at runtime.

Solution

To get around the problem of not having variables in CSS one must read the CSS file and replace the given values at runtime. The good news is that in ASP.NET this is a relatively easy task.

body
{
   background-color:#BG_COLOR#
}

Generic HTTPHandler

Using Visual Studio 2005 you can easily add a Generic HTTPHandler.

Add New Item

This will create an ashx file and add it to you project. This file implements the IHTTPHandler interface, with its one and only method, ProcessRequest and includes the WebHandler page directive.

<%@ WebHandler Language="C#" Class="Handler" %>

The .NET Framework treats these files as HTPPHandlers without the need to register them in the <httpHandlers> section of the web.config file.

<%@ WebHandler Language="C#" Class="CSSHandler" %>
using System;
using System.Web;
using System.Configuration;

public class CSSHandler : IHttpHandler 
{
    public void ProcessRequest (HttpContext context) 
    {
        context.Response.ContentType = "text/css";
        
        // Get the file from the query stirng

        string File = context.Request.QueryString["file"];
        
        // Find the actual path

        string Path = context.Server.MapPath(File);
        
        //Limit to only css files

        if(System.IO.Path.GetExtension(Path) != ".css")
           context.Response.End();

        //Make sure file exists

        if(!System.IO.File.Exists(Path))
           context.Response.End();

        // Open the file, read the contents and replace the variables

        using( System.IO.StreamReader css = new System.IO.StreamReader(Path) )
        {
            string CSS = css.ReadToEnd();
            CSS = CSS.Replace("#BG_COLOR#", ConfigurationManager.AppSettings["BGColor"]);
            context.Response.Write(CSS);
        }
    }
    
    public bool IsReusable 
    {
        get { return false; }
    }
}

As we can see the ProcessRequest method simply opens the file specified on the query string, reads it and using string replace to add the value for the variable that has been specified in the web.config file. Not much to it.

<link rel="Stylesheet" href="CSSHandler.ashx?file=default.css" />
<appSettings>

    <add key="BGColor" value="Red"/>

</appSettings>

Limitations

Using a generic webhandler has a disadvantage in that you must specify the style sheet to parse. This breaks down when using ASP.NET 2.0 Themes however because any style sheet placed in the theme folder will automatically be linked, no need manually add it to your web pages. Although you can manually add each one it isn’t a very maintainable model.

Better solution

A better solution is to create a custom HTTPHandler and add it to the httpHandlers section of the web.config file.

<httpHandlers>
    <add verb="*" path="*.css" type="CustomHandler.CSSHandler, CustomHandler"/>
</httpHandlers>
public class CSSHandler : IHttpHandler 
{
#region IHttpHandler Members

    public bool IsReusable
    {
        get { return false; }
    }

    public void ProcessRequest(System.Web.HttpContext context)
    {
        // Get the physical path of the file being processed

        string File = context.Request.PhysicalPath;

        // Open the file, read the contents and replace the variables

        using(System.IO.StreamReader reader = new System.IO.StreamReader(File))
        {
            string CSS = reader.ReadToEnd();
            CSS = CSS.Replace("#BG_COLOR#", ConfigurationManager.AppSettings["BGColor"]);
            context.Response.Write(CSS);
        }
    }

    #endregion
}

 

The only difference from the previous example is that the CSS file to parse is obtained from the context.Request.PhysicalPath property. Since the handler is registered for css files it will process any stylesheet file regardless of its location in the web project.

Conclusion

This article has hopefully shown a method that can be used to provide dynamic settings to an otherwise static file and give website uses a more positive experience.

License

This article, along with any associated source code and files, is licensed under The Common Development and Distribution License (CDDL)

About the Author

Mark Nischalke


Supporter
My first job was coding COBOL on Mainframes but I soon progressed to DOS, then to Windows. I've been a consultant for a number of years and have been involved in a variety of projects, from Finite Element Analysis systems to train control systems to large e-commerce websites to one page static websites. I attained my MCSD status in 1998 with the WOSA exams, updated it with VC++ and transitioned to MCSD.NET, grabbing MCAD.NET along the way. I've been working almost exclusively with C# and .NET since it was in beta.
Occupation: Other
Location: United States United States

Other popular ASP.NET articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 34 (Total in Forum: 34) (Refresh)FirstPrevNext
Subject  Author Date 
Generalperformancememberliorgold23:25 31 Jul '07  
GeneralRe: performancesupporterMark Nischalke2:43 1 Aug '07  
GeneralRe: performancememberEvyatar Ben-Shitrit9:24 1 Aug '07  
Generalare there other versions??membernilskyone0:13 19 Jun '07  
GeneralRe: are there other versions??supporterMark Nischalke3:03 19 Jun '07  
GeneralRe: are there other versions??membernilskyone15:37 9 Jul '07  
GeneralRe: are there other versions??membermolebrain4:52 13 Jul '07  
Questionthis is working for localhost but not for online..memberrakesh_csit19:54 24 May '07  
AnswerRe: this is working for localhost but not for online..supporterMark Nischalke3:12 25 May '07  
QuestionNot working for mememberSaumin13:05 24 May '07  
AnswerRe: Not working for mesupporterMark Nischalke16:46 24 May '07  
GeneralRe: Not working for mememberSaumin5:52 25 May '07  
GeneralRe: Not working for mesupporterMark Nischalke6:03 25 May '07  
GeneralRe: Not working for mememberSaumin6:23 29 May '07  
GeneralGreat Workmemberdbeard9:10 10 May '07  
GeneralVariable SourcememberJoeReynolds7:56 1 Apr '07  
GeneralRe: Variable SourcesupporterMark Nischalke14:53 1 Apr '07  
GeneralLots of praise [modified]memberjokva7:58 14 Feb '07  
GeneralRe: Lots of praisesupporterMark Nischalke9:03 14 Feb '07  
GeneralSecurity & PerformancememberEvyatar Ben-Shitrit20:54 18 Dec '06  
GeneralRe: Security & PerformancesupporterMark Nischalke3:10 19 Dec '06  
GeneralDangerousmemberThe .NET Junkie8:40 18 Dec '06  
GeneralRe: DangeroussupporterMark Nischalke8:51 18 Dec '06  
GeneralRe: DangerousmemberThe .NET Junkie9:31 18 Dec '06  
GeneralRe: DangeroussupporterMark Nischalke9:56 18 Dec '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 17 Dec 2006
Editor:
Copyright 2006 by Mark Nischalke
Everything else Copyright © CodeProject, 1999-2008
Web11 | Advertise on the Code Project