WebAssert HTML & CSS validation testing library v0.1 released

A while back I posted about automating the checking of HTML validity of your ASP.NET site using unit tests that leverage the W3C Markup Validation Service. I’ve showed the technique in a number of presentations since then and used it on a number of projects to good effect.

In an effort to make it easier to consume in your own project and allow for future expansion with new features, I’ve refactored it and rolled it into a new open-source library called WebAssert, up on CodePlex.

Thanks to some scripting help from the ever talented Tatham Oddie, I’m happy to announce the release of WebAssert v0.1 (beta).

This initial release supports checking for markup and CSS validity of URLs using the W3C hosted validators, or your own hosted instances. This release supports the MSTest framework in Visual Studio but there is already a fork containing a wrapper for NUnit which I plan to integrate soon. You can also test sites hosted using the AspNetDevelopmentServer attribute under MSTest.

Any feedback please let me know.

Set the CSS class of ASP.NET invalid controls using jQuery

The ASP.NET validation controls are a very quick and effective way to add client-side & server-side validation to your web forms but they lack one very important feature out of the box: the ability to change the CSS class of the controls that are invalid. Changing the class of the invalid controls will allow you to style them in such a way that they help bring attention to the fact that the user needs to do something more to complete the form successfully.

It is quite simple to add this functionality (for clients with JavaScript enabled at least) using a little bit of JavaScript and everybody’s favourite JavaScript library, jQuery!

First of all, set the CssClass property of all your validator controls to “validation-error”. The easiest way to achieve this is by using a skin file. See this post for more details on how to do this.

Then add the following to your site’s JavaScript file (assuming you’re already using jQuery):

/// <reference path="jquery-1.3.1.js" />

$(document).ready(function(e) {
        .bind("DOMAttrModified propertychange", function(e) {
            // Exit early if IE because it throws this event lots more
            if (e.originalEvent.propertyName && e.originalEvent.propertyName != "isvalid") return;

            var controlToValidate = $("#" + this.controltovalidate);
            var validators = controlToValidate.attr("Validators");
            if (validators == null) return;

            var isValid = true;
            $(validators).each(function() {
                if (this.isvalid !== true) {
                    isValid = false;

            if (isValid) {
            } else {

And there you have it. Now when any validator on your form has the isValid property tripped to false on the client side, the CSS class of the offending control will be changed to “error”.

New release of Visual Studio 2008 XHTML 1.1 Templates available now

I’ve uploaded a new release that now includes item templates for C# & VB Web Application Projects and Web Site Projects. Plus, there is now a Project Template for creating C# Web Application Projects pre-configured to be XHTML 1.1 compliant, use a master page & theme, and the CSS Friendly Control Adapters. It has some other goodies in it too (e.g. support for print specific CSS files in themes).


Feedback always appreciated.

Suggested improvements for CSS editor in Visual Web Developer and Expression Web

People who know me will know that I love CSS and that I can often be found with my head deep in a CSS file in Visual Web Developer (the web tools in Visual Studio). Recently I’ve been thinking about how Microsoft could make the support for editing CSS files directly in these tools more conducive to discovering features of CSS you don’t know about, improving productivity through better contextual awareness, and offering insight as to real world issues such as browser compatibilities.

So I’ve put together a series of mock-ups that illustrate some of the ideas I have for improving the support for CSS file editing:

  • Inline RGB colour picker
  • Ability to define colour swatches in XML comments including name, RGB and category
  • Inline colour swatch picker with $ keyboard shortcut that replaces name with hex RGB value on completion
  • Inline named colour picker with preview of named colour in pick list
  • Ability to choose browsers to warn of incompatibilities with when schema checking CSS
  • Green “squigglies” under CSS selectors and properties know to be unsupported or have issues in chosen warning browsers
  • ToolTips for CSS properties showing description and browser compatibility summary with hyperlinks to further information
  • ToolTips for CSS selectors showing description of what elements it will select, browser compatibility summary and specificity score with hyperlinks to further information on each
  • ToolTip preview of url resources (images) showing file size and image dimensions
  • ToolTip preview of font-family showing font source (TrueType, W3C, etc.) and font rendering preview
  • Support for automatic indenting of style declarations based on descendant or child selectors if they appear after each other

Hopefully somebody on the appropriate teams in Microsoft will here me 🙂

ASP.NET & CSS: Using skins to “zero out” default style and set default CSS class names

ASP.NET includes a feature called “Themes” that allows you to organise styling artifacts including CSS stylesheets and images into logical units that can be easily applied to a page or entire site through configuration. Part of this feature is the ability to create .skin files that set default values for certain properties of ASP.NET server controls as part of a theme.

Not all properties of ASP.NET controls are skinnable. Indeed the initial intention of .skin files was to enable the setting of default values for properties such as FontColor and BorderWidth, which when serving to CSS supporting browsers ASP.NET will render as inline style attributes on the emitted HTML controls. So what place do they have when we apply all of our style rules via way of attached CSS stylesheets and selectors (the way we should)?

Despite their evil initial purpose we can put .skin files to good use for two purposes:

  1. Assigning CSS classes to all instances of particular ASP.NET server controls; and
  2. Zeroing out the default inline style that ASP.NET sets on some controls.

So how does this work?

In your theme folder add a new .skin file called Controls.skin:

Add a skin file to your theme folder

Now we want to add some declarations to the file to:

  1. Zero out the inline style of the ASP.NET validator controls; and
  2. Assign a default CSS class name to the Button, LinkButton, TextBox and validator controls.
<asp:RequiredFieldValidator runat="server" ForeColor="" CssClass="validation-error" />
<asp:RangeValidator runat="server" ForeColor="" CssClass="validation-error" />
<asp:CompareValidator runat="server" ForeColor="" CssClass="validation-error" />
<asp:RegularExpressionValidator runat="server" ForeColor="" CssClass="validation-error" />
<asp:CustomValidator runat="server" ForeColor="" CssClass="validation-error" />

<asp:LinkButton runat="server" CssClass="button" />
<asp:Button runat="server" CssClass="button" />
<asp:TextBox runat="server" CssClass="text-box" />

And that’s it! Now when ASP.NET renders these controls when they appear on a page (or in a site) with your theme configured, they’ll automatically pick up properties defined in this .skin file.

ASP.NET & CSS: Styling sortable columns in the GridView using CSS

UPDATE: The modification to the CSS Friendly Control Adapters outlined in this article was recently applied to the CodePlex source code so you can now simply get the latest source code from CodePlex.

The following is an article describing one of the techniques I spoke about during my recent RDN topic, CSS Layout with ASP.NET & Visual Studio 2008.

A common user interface requirement for applications is to visually indicate when:

  1. a column in a grid is sortable;
  2. which column in a grid is currently the sort column; and
  3. which direction the sort is being applied in (ascending or descending).

In ASP.NET, we generally use the GridView control to display tabular data and provide the user with the ability to sort and page through that data. There are many examples on the web of techniques you can use to programmatically insert an image to indicate the currently sorted column and its sort direction (including the MSDN documentation). There are a number of problems with this approach:

  1. It mixes functional code with presentation logic. The code behind for our pages and user controls is complicated enough without having to trawl through formatting and layout logic;
  2. It requires you to add this code on every GridView (or sub-class the GridView and use the new version instead); and
  3. It dilutes the semantic meaning of the resultant HTML mark-up, thus affecting the page’s usability (IMG tags have no place in the header of a TABLE).

So what’s a better solution I hear you say? The following solution uses ASP.NET, the CSS Friendly Control Adapters and CSS styling to:

  1. add sorting information to a GridView in a semantic and accessible fashion; and
  2. apply visual effects relating to sorting behaviour.

The CSS Friendly Control Adapters alter the HTML mark-up produced by ASP.NET for many of the included server controls so that it is more accessible, standards compliant and, importantly, easier to style using CSS. You can grab the latest source code for the adapters from CodePlex (be sure to download from the source code section, not the release section), however the technique shown here requires a small change to the included GridView adapter (further details about incorporating the CSS Friendly Control Adapters into your web project are included in the download). So, once you’ve downloaded the source, open up the solution and find the GridViewAdapter.cs file:


Replace its contents with this modified version. This adds a new function that sets the CSS class of the GridView’s header cells based on which column the GridView is currently sorted by. So for example if I have a GridView defined as such:

<asp:GridView ID="gvExample" runat="server" DataSourceID="pdsExample" DataKeyNames="Id"
    AllowPaging="true" AllowSorting="true" PageSize="10" AutoGenerateColumns="false" CssClass="customers-grid">
        <asp:BoundField HeaderText="First Name" DataField="FirstName" SortExpression="FirstName"
            HeaderStyle-CssClass="first-name" ItemStyle-CssClass="first-name" />
        <asp:BoundField HeaderText="Last Name" DataField="LastName" SortExpression="LastName"
            HeaderStyle-CssClass="last-name" ItemStyle-CssClass="last-name" />
        <asp:BoundField HeaderText="Age" DataField="Age" SortExpression="Age"
            HeaderStyle-CssClass="age" ItemStyle-CssClass="age" />
        <asp:BoundField HeaderText="Member for" DataField="YearsAsMember" SortExpression="YearsAsMember"
            HeaderStyle-CssClass="years-as-member" ItemStyle-CssClass="years-as-member" />

Then when the GridView is rendered sorted by the First name column, the HTML mark-up emitted will look like this:

<div class="AspNet-GridView" id="ctl00_main_gvExample">
<table cellpadding="0" cellspacing="0" summary="" class="customers-grid">
    <tr class="AspNet-GridView-Header">
        <th class="sortable sorted asc first-name" scope="col">
            <a href="javascript:__doPostBack('ctl00$main$gvExample','Sort$FirstName')">First Name</a></th>
        <th class="sortable last-name" scope="col">
            <a href="javascript:__doPostBack('ctl00$main$gvExample','Sort$LastName')">Last Name</a></th>
        <th class="sortable age" scope="col">
            <a href="javascript:__doPostBack('ctl00$main$gvExample','Sort$Age')">Age</a></th>
        <th class="sortable years-as-member" scope="col">
            <a href="javascript:__doPostBack('ctl00$main$gvExample','Sort$YearsAsMember')">Member for</a></th>
    <tbody><!-- Data rows here --></tbody>

Note how we now have CSS classes added to the <th> tags to describe their sorting behaviour (sortable, sorted and asc). We can see that all columns are sortable, and that the First Name column is currently being sorted by in the ascending direction. And because the logic to apply these classes is in the control adapter, it is automatically applied to all GridViews in the application.

There is a caveat to this approach however. The adapter relies on two properties of the GridView to determine the current sort column and direction: SortExpression and SortDirection. These are read only properties that are only populated when you provide data to the GridView by way of one of the data source controls introduced in ASP.NET 2.0, e.g. ObjectDataSource, SqlDataSource, etc., and the DataSourceID property. If you provide data to your GridView by setting its DataSource property directly from code behind (and calling DataBind()) the sort properties are not set and thus the adapter cannot insert the required CSS class names. You must also initially call the Sort() method on the GridView from the Page_Load() method in order to force the setting of these properties the first time the page is rendered:

protected void Page_Load(object sender, EventArgs e)
    if (!IsPostBack)
        // Set default sort expression
        gvExample.Sort("FirstName", SortDirection.Ascending);

If you are not using the data source controls (the ObjectDataSource in particular) I thoroughly recommended you take a look as they provide you with “free” sorting and paging functionality out of the box without the need to manually handle events on the GridView. If you don’t like the way the ObjectDataSource requires a separate business logic class to provide its data access functionality, for instance if you are implementing a MVP pattern in the “Passive View” flavour, then you can sub-class the OjectDataSource and force it to look on the instance of the class for the hosting page (or user control) for its methods instead (this is the method I used in the RDN sample solution and I will post an article on this technique shortly).

Now that we have our CSS classes set we can attach some CSS rules that provide some visual indicators on the sorting behaviour. The following CSS rules do just that (I’ve placed these in a common Grid.css file in the sample project):

div.AspNet-GridView {
    border: 1px solid #828790;
    font-size: 0.8em;
    min-height: 1px;
    font-family: "Lucida Sans";

    div.AspNet-GridView table {
        width: 100%;
        border-collapse: collapse;

        div.AspNet-GridView table thead tr th {
            padding: 3px 3px 2px 2px;
            background: url('grid-header-back.gif') top left repeat-x;
            font-weight: normal;
            border-bottom: 1px solid #d5d5d5;
            border-right: 1px solid #e3e4e6;

            div.AspNet-GridView table thead tr th.sortable {
                padding: 0px;
                div.AspNet-GridView table thead tr th.sortable:hover {
                    background: #b7e7fb url('grid-header-sortable-back-hover.gif') top left repeat-x;
                    border: 1px solid #96d9f9;
                    border-top: none;
                    border-left: none;

                div.AspNet-GridView table thead tr th.sortable a {
                    display: block;
                    padding: 3px 3px 2px 2px;
                    color: Black;
                    min-height: 1px; /* Force layout in IE7 to prevent rendering issues */
                    div.AspNet-GridView table thead tr th.sortable a:hover {
                        text-decoration: none;

            div.AspNet-GridView table thead tr th.sorted {
                background: #d8ecf6 url('grid-header-sorted-back.gif') top left repeat-x;
                border: 1px solid #96d9f9;
                border-top: none;
                border-left: none;

                div.AspNet-GridView table thead tr th.asc a {
                    background: transparent url('grid-header-asc-glyph.gif') center 1px no-repeat;

                div.AspNet-GridView table thead tr th.desc a {
                    background: transparent url('grid-header-desc-glyph.gif') center 1px no-repeat;

        div.AspNet-GridView table tbody tr td {
            padding: 2px 6px 2px 4px;
            border: 1px solid #efefef;

        div.AspNet-GridView table thead tr th.action,
        div.AspNet-GridView table tbody tr td.action {

            border-left: none;
            border-right: none;
        div.AspNet-GridView table tbody tr td.action {
            padding: 2px 2px 2px 2px;
            width: 40px;
            text-align: center;

    div.AspNet-GridView table tbody tr.AspNet-GridView-Alternate td {
        background: #f2f9fc;

    div.AspNet-GridView-Pagination {
        background: #e6e9ee;
        text-align: center;
        padding: 2px 3px 2px 3px;
        font-size: 0.9em;
        min-height: 1px; /* Force layout in IE7 to prevent rendering issues */
        div.AspNet-GridView-Pagination span {
            padding: 0px 3px;
            background: #d8ecf6;
            border: 1px solid #96d9f9;

div.grid-row-count {
    color: #666666;
    padding: 2px 0px 2px 6px;
    font-size: 0.8em;

These style rules use a small number of background images to give our GridView a nice Vista-like look:


You can immediately see that the First Name column is currently the sort column in the ascending direction. Hovering over other sortable columns provides feedback by way of a :hover background image, here I’ve hovered my mouse over the Last Name column:


I’ve also added some formatting to the pager section of the GridView to highlight the current page.

To apply styles that are specific to this particular GridView, e.g. column widths, we can add some style rules like thus:

table.customers-grid {


    table.customers-grid th.first-name,
    table.customers-grid td.first-name {
        width: 35%;    }

    table.customers-grid th.last-name,
    table.customers-grid td.last-name {


    table.customers-grid th.age,
    table.customers-grid td.age {
        text-align: center;
        width: 10%;

    table.customers-grid th.years-as-member,
    table.customers-grid td.years-as-member {
        width: 15%;
        text-align: center;

Note: I’ve tested the included CSS here with IE7 and Firefox. There is a small issue with the Firefox rendering which I haven’t bothered to fix (the left-most border is not displayed due to the different ways IE7 and Firefox collapse borders) and you will definitely need to make some changes to properly support IE6 (e.g. adding support for the :hover pseudo class on elements other than <a> using an .htc file) but they are outside the scope of this article.

So there you have it. Using this method we have freed our code-behind of nasty image injection code and made our GridViews more accessible and stylable to boot.

Download the sample project for this article here

Getting Internet Explorer 6 to render transparent PNGs with minimal fuss

So you’re creating a great looking website and embracing the latest techniques like transparent PNG images to get good looking effects. Everything looks great in IE7 and Firefox but then you fire it up in IE6. Oh no!! What are all these gray backgrounds in my transparent PNGs? Well IE6 doesn’t support transparent PNGs as simply as other browsers but it does support them with a little tweaking.

You can make IE6 render transparent PNGs just fine using the a combination of two of IE’s proprietary features: DirectX Filters and DHTML Behaviors. Filters allow IE to apply all types of visual effects to HTML, pretty pointless usually when creating “standards” compliant websites but one filter in particular is useful in our situation; AlphaImageLoader. This filter will load an image, including a transparent PNG, into the element between the background and the content and even resize the element to fit the image in (there are other options to clip the image but we want the default behaviour). Great, now all we need is a way to do this easily for any PNG image in our site, and only in IE6. That’s where DHTML Behaviors come in.

A behavior is basically a javascript file that encapsulates DHTML manipulating code so that it can be re-used. You can attach to any event on the element the behavior is applied to and run the script when the event is fired. The really good bit is that DHTML Behaviors are applied by CSS rules so we can include them in our standard site stylesheet. Perfect!

Create a blank transparent GIF image 16 x 16 pixels in size and call it blank.gif and place it in the Images folder of your website.

Then create a file in your website called PNGImage.htc and paste the following code into it (or get it from the link at end of this post):

<public:attach onevent="RenderPNG();" event="oncontentready"> <script language="javascript" type="text/javascript"> function RenderPNG() { var img = element; var src; // check that behavior hasn't already been applied if (img.tagName.toLowerCase() == "img" && img.style.filter.indexOf("AlphaImageLoader") < 0 && img.src.toLowerCase().indexOf(".png") > 0) { src = img.src; img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'" + src + "\')"; img.src = "Images/blank.gif"; } } </script>

This behavior will be attached to our IMG tags. As you can see the behavior attaches to the element’s oncontentready event. When the event is raised once the element is ready for scripting, the behavior check’s to see if it has already been applied to this element, and if not, applies the filter and sets the element’s src property to a transparent gif file. This way the IMG tag still contains a vaild image so will honour its normal rendering duties but now has the transparent PNG image loaded into it behind the transparent GIF.

Now, in your site’s stylesheet file add this class descriptor:

IMG.PNGImage { _behavior: url('PNGImage.htc'); /* IE6 Only */ }

This will cause the behavior to be loaded for any IMG tag with its class set to include PNGImage. The underscore at the beginning of the behavior property makes it invisible to IE7 which ignores CSS properties prefixed with underscores, as will all other browsers. Make sure the path to the .htc file is relative to the page the class is applied to, not the CSS file itself which is usually the case for urls in stylesheets, such as for loading background images.

Now in your HTML assign the PNGImage class to any IMG tag with a PNG file:

<img alt="A transparent icon" src="Images/my-icon.png" class="PNGImage" />

And that’s it! If you wanted to, you could attach the behavior directly to the IMG element via an element descriptor in your stylesheet, saving you adding the class to each IMG tag, but this will obviously result in a few more CPU cycles being chewed up on the client in IE6 when loading pages:

IMG { _behavior: url('PNGImage.htc'); /* IE6 Only */ }