Rickard Nilsson

  • Blog
  • Archive
  • About
  • Contact

Welcome to rickardnilsson.net

Rickard Nilsson is a software architect, developer, craftsman, agile enthusiast, and father of three... More

Rickard blogs about crafting software using .NET tooling and solid, development practices.

Follow @rickardn

Top Posts

  • Applying stylesheets dynamically with jQuery
  • My customized Son of Obsidian Visual Studio color scheme for ReSharper
  • .NET Development with Visual Studio on MacBook Pro
  • Code Kata Cast
  • ReSharper User tip #2: Refactor rename namespace
  • Combining and minifying JavaScript and CSS files with Ajax Minifier
  • Dependency injection in ASP.NET MVC with Unity IoC Container
  • C# REPL and Interactive interpreter

Categories

  • .NET
  • Agile
  • ASP.NET 2.0
  • ASP.NET 3.5
  • ASP.NET 4
  • ASP.NET MVC
  • BlogEngine.NET
  • C# 2.0
  • C# 3.0
  • C# 4.0
  • Continuous Integration
  • CSS
  • Design by Contract
  • Design Patterns
  • iPhone
  • JavaScript
  • Kata
  • Moles
  • Open source
  • Personal
  • Review
  • Social media
  • Software development
  • TDD
  • Testing
  • Umbraco
  • Unit testing
  • Unity
  • User tip
  • Web development

Five most recent posts

  • How to unit test your database code when using ServiceStack OrmLite
  • Extract class - ReSharper Ninja tricks
  • ASP.NET MVC 3 Template with built in JavaScript and CSS merging and minification
  • ReSharper Ninja tricks - Generate code from usage
  • Unit testing continuously

Tag cloud

  • agile
  • blogengine.net
  • c#
  • code kata
  • codegarden11
  • continuous integration
  • css
  • dependency injection
  • fakes
  • iso 8601
  • javascript
  • jquery
  • refactoring
  • resharper
  • resharper usertip
  • tdd
  • testing
  • umbraco
  • unit test
  • unit testing
  • visual studio

Recent comments

ASP.NET MVC 3 Template with built in JavaScript and CSS merging and minification

Monday, 3 September 2012 07:28 by Rickard Nilsson

In a previous post I described the importance of optimizing your web site resources and how you can do it using the open source tool Ajax Minifier. I’ve received a few questions about how to automate this process and now I want to share a ASP.NET MVC 3 template with the combining and minification built in as a post compile step.

Since my last post Ajax Minifier is now available as a NuGet package and is easily installed in your solution either via NuGet Package Manager or using the NuGet Package Manager Console command:

PM> Install-Package AjaxMin

However, to get the AjaxMin.exe you’ll have to download it manually from Codeplex. My MVC 3 template is build on a simple Internet Application MVC 3 template with Razor and HTML5 semantic markup. My additions to automate resource optimizations consists of the following:


After the web project is built a custom target is called:

<Import Project="$(MSBuildProjectDirectory)\AfterBuild.tasks" />
<Target Name="AfterBuild">
    <CallTarget Targets="Minify"></CallTarget>
</Target>


The after build target executes the AjaxMin executable:

<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <PropertyGroup>
        <BuildLibPath>$(MSBuildProjectDirectory)\..\packages</BuildLibPath>
        <Ajaxmin>$(BuildLibPath)\AjaxMin.4.62.4618.15628\bin\Ajaxmin.exe</Ajaxmin>
    </PropertyGroup>
    <Target Name="Minify">
        <Exec Command='"$(Ajaxmin)" -js -xml minify.js.xml -clobber' Condition="'$(Configuration)' == 'Release'" />
        <Exec Command='"$(Ajaxmin) -css -xml minify.css.xml -clobber' Condition="'$(Configuration)' == 'Release'" />
    </Target>
</Project>


The xml files minify.js.xml and minify.css.xml are used to define which resources should be merged together, minified and where to output the result.

<root>
  <output path="Scripts/Mvc3Application.min.js">
    <input path="Scripts/myplugin.js"/>
    <input path="Scripts/viewModel.js"/>
    <input path="Scripts/foobar.js"/>
  </output>
</root>


Download ASP.NET MVC 3 Template

Target: .NET 4.0

Tags:   optimization, javascript, css, front end, minification
Categories:   JavaScript | CSS | User tip | Web development
Actions:   | Ping backs (1)

jQuery plugin for switching stylesheets

Thursday, 19 May 2011 19:08 by Rickard Nilsson

It has been almost three years since I wrote my top ranking post on this blog: Applying stylesheets dynamically with jQuery. It was a quick and dirty example of a testing scenario pulled together for a colleague but it has become my number one linked post. It is still the post that gets the most hits every month because it is the first hit on Google for jquery add stylesheet which seems to be a lot of people has trouble with.

So, I felt it was time to do another post on the subject considering I’ve been using jQuery more or less every day these last three years.

jQuery Plugin

I’ve created a simple jQuery plugin for adding or switching out stylesheets dynamically and interactively and it can be used like this:

Loading...
  • HTML
  • jQuery hookup
  • jQuery Plugin
<ul>
    <li><a href="#" rel="1.css">Apply Stylesheet 1</a></li>
    <li><a href="#" rel="2.css">Apply Stylesheet 2</a></li>
    <li><a href="#" rel="3.css">Apply Stylesheet 3</a></li>
</ul>

 

$('a').click(function () {
    $.stylesheets.clear().add($(this).attr('rel'));
    return false;
});
$.stylesheets = (function () {
    var stylesheets,
        add,
        clear;
 
    add = function (cssfile) {
        $('head').append('<link href="' + cssfile + '" rel="stylesheet" />');
        return stylesheets;
    };
 
    clear = function () {
        $('head link[rel=stylesheet]').remove();
        return stylesheets;
    };
 
    return stylesheets = {
        add: add,
        clear: clear
    };
} ());

Download source / demo

Tags:   jquery, css, javascript, jquery plugin
Categories:   JavaScript | CSS
Actions:   | Ping backs (1)

Combining and minifying JavaScript and CSS files with Ajax Minifier

Saturday, 26 March 2011 22:05 by Rickard Nilsson

Update! Download ASP.NET MVC 3 Template with built in JavaScript and CSS merging and minification

Why should you bother with combing and minifying JavaScript and CSS files? If you are a web developer working with sites with any significant traffic, you simply should because of the impact it will have on the load time of your site and how your visitors will perceive the page loading faster.

In the field of web site optimization, pioneered by Yahoo, there are many rules or guidelines which you should try to follow in hunt for milliseconds on the client side. In fact, it’s on the client that you will get the most value for your optimization work rather than on the server side [SOUDERS]. This is a subset of the rules regarding JavaScript and CSS.

Guidelines for web site optimization

  • Put all your CSS in separate .css files
  • Put your CSS links as early in the header section of the page as possible
  • Minify your CSS files, i.e. remove whitespace etc.
  • Try combining all of your CSS files into one

  • Put all your JavaScript code in separate .js files
  • Put your JavaScript imports as close to the </body> tag as possible
  • Minify your JavaScript files
  • Try combing all of your JavaScript files into one
  • If possible try loading large scripts asynchronously

  • Enable GZIP compression on all your static content, e.g. CSS and JavaScript files
  • Set far future expire headers on your static content

Microsoft Ajax Minifier

I have searched for a tool that could help me implement many of the optimization guidelines and found a few worth taking a closer look at, one of these is the Google Closure Compiler. It has loads of features including file combining, minification, “compiling” your JavaScript into better JavaScript, as well as an API for loading your scripts asynchronously.

However, being a pragmatic .NET developer, I chose the most easily accessible tool available for me, which is Microsoft’s Ajax Minifier. It’s a free tool available on Codeplex and documentation is provided on the www.asp.net site.

Ajax Minifier comes as a command-line application and after you have installed it you can use it through it’s own command prompt.

Minifying JavaScript

Minifying a single JavaScript file is pretty straight forward. Simply type in the command prompt:

  • ajaxmin inputfile.js –out outputfile.js

then add –clobber if you wish to override the outputfile.js if it exists, as in:

  • ajaxmin inputfile.js –out outputfile.js –clobber

Minifying CSS

Minifying a single CSS file is equally simplistic as follows:

  • ajaxmin inputfile.css –out outputfile.css –clobber

As before, add –clobber to override any existing output file.

Combining files

Unfortunately there are no documentation on the asp.net site about how to combine multiple files into one, however, the ajaxmin command itself provides a hint given the /? parameter:

As an alternative to the input file parameter you can use the –xml parameter and supplying it with the path to an xml file of the following format:

<?xml version="1.0" encoding="utf-8"?> 
<root> 
    <output path="outputfile.js"> 
        <input path="inputfile1.js"/> 
        <input path="inputfile2.js"/> 
        <!-… -> 
    </output> 
</root> 

The Ajax Minifier will combine all of your input files into one, minify it, and produce the result in the output file. Using this approach you can also control in what order the files are loaded into the page and sort out any dependency issues, just as you would, had you listed includes in the regular html file (or .master or whatever).

The Ajax Minifier does not seem to have the smarts to deduce that this is JavaScript files so you need to supply it with a –js parameter like so:

  • ajaxmin –js –xml jsxmlfile.xml –clobber

I haven’t found a way to combine JavaScript and CSS in the same xml file so you need to make a separate file for you CSS files with the same format as above and instead of the –js parameter, use the –css dito:

  • ajaxmin –css –xml cssxmlfile.xml –clobber
Tags:   javascript, css, optimization, front end, web developement
Categories:   JavaScript | CSS | User tip
Actions:   | Ping backs (1)

Building a Photo Album widget for BlogEngine.NET

Thursday, 14 August 2008 01:07 by Rickard Nilsson

BlogEngine.NET has a widget framework from version 1.4 which are web part like components that can be added and removed, configured and dragged around directly in the page. Simple widgets are very easy to create and plug in to your blog and there are several blog posts explaining how to do that. In this post I'm gonna go through a more advanced example featuring Web services and Ajax.

The Photo Album Widget
The Photo Album Widget

Download: PhotoAlbumWidget-0.1.zip (7,96 kb)
Unzip to ~/widget/ folder. Requires jQuery library.


First we start with some requirements for the widget we're creating.

  1. BlogEngine.NET 1.4+ Widget
  2. Show thumbnail pictures
  3. Get pictures from Picasa web album
  4. Ajax style asynchronous loading
  5. Configurable number of pictures
  6. Clickable pictures to show full size picture 
  7. Picture repository provider model
  8. Flickr repository provider
  9. Folder repository provider
  10. Configurable picture count
  11. Provider specific configuration
  12. Configurable choice of provider
  13. Full size picture pops up in Lightbox
  14. Web 2.0 style controls for scrolling
  15. Larger preview on mouse over picture

The list above is a prioritized backlog and the first version should include items 1 - 4.

Widget 

We start off with number one, a BlogEngine Widget. To create a widget we add a new folder to the /widget/ folder and we call it PhotoAlbum. Then we create two user controls, one for widget presentation and one for configuration UI. They must be named, by convention, widget.ascx and edit.ascx respectively and should derive from WidgetBase and WidgetEditBase respectively. See more on basic widgetry here by Rtur and here by Mads as well as this, that and whatnot.

That was the easy part.

Picasa web album

With the next requirement we first need to get the pictures from somewhere so we skip to the next requirement. Picasa is Google's web album and it has its own REST API as well as a .NET client library. Conveniently there is also a public feed which contains all public photos uploaded to Picasa. (You can of course use your own Picasa album, see the Data API docs for more information). All we need to do is provide a query tag/tags to limit the search or we'll get an error message. The following code retrieves a couple of photos picturing cats:

PicasaService service =
    new PicasaService("exampleCo-exampleApp-1");

PhotoQuery query = 
    new PhotoQuery("http://picasaweb.google.com/data/feed/api/all");
query.Query = "cat";
query.NumberToRetrieve = 5;
PicasaFeed feed = service.Query(query);

foreach (PicasaEntry entry in feed.Entries) {
    string firstThumbUrl = entry.Media.Thumbnails[0].Attributes["url"] as string;
    writer.Write("<img src=\"{0}\" alt=\"{1}\" />",
                 firstThumbUrl, entry.Title.Text);
}

If we drop the code above into the widget.ascx.cs we affectivally fullfills both requirements 2 and 3 so lets get on with number 4.

Ajax

Requirement number four implies the Incremental Page Display pattern where the main part of the page is shown quickly and portions of the page that takes longer to load are fetched and displayed asynchronously. To give the user feedback of the loading we place an animated gif image in the widget which is later swapped out when the real pictures arrive. To accomplish this we're using the jQuery JavaScript library which let us get away with very little code for pretty advanced stuff.

First we need to do a little refactoring since the widget needs to do an asynchronous call somewhere to get its content, i.e. the pictures to display. We're gonna go with the simplest possible solution here, just enough to satisfy the requirement. The simplest thing from the widget's point of view is to have the html containing a number of <img> elements returned from the call. Then it's very simple to insert the html into the widget using jQuery. Given that the widget contains a div with the id "photoalbum" this is all it takes:

$("#photoalbum").html(the_html_to_insert);

As it is now, the widget codebehind is rendering the requested html and this is not god. We need to move the code to some place which we can make a http request to and get the html in response. This can be done with a regular aspx page. All we need to do is to put a simple Repeater control on a page and bind it to a list of image URLs which we get from Picasa web album. So, we add a new aspx page to the /widgets/Photo Album/ folder and call it PhotoService.aspx. All we want in response is the <img> tags which should be inserted into the widget so we clear the page from html and put a single Repeater on it like this:

<asp:Repeater ID="pictureRepeater" runat="server">     <ItemTemplate>         <asp:Image ID="image" runat="server"             ImageUrl="<%# Container.DataItem.ToString() %>" />     </ItemTemplate> </asp:Repeater>

In the codebehind we insert something like before and makes sure we bind to the Repeater control.

// Error checking is omitted for clarity
List<string> pictures = new List<string>();
PicasaService service = new PicasaService("exampleCo-testApp-1");

string picasaUri = "http://picasaweb.google.com/data/feed/api/all";
PhotoQuery query = new PhotoQuery(picasaUri);
query.Query = "cat";
query.NumberToRetrieve = 6;
PicasaFeed feed = service.Query(query);

foreach (PicasaEntry entry in feed.Entries) {
    string firstThumbUrl = entry.Media.Thumbnails[0]
                               .Attributes["url"] as string;
    pictures.Add(firstThumbUrl);
}

pictureRepeater.DataSource = pictures;
pictureRepeater.DataBind();

To test the service we point a web browser to /widgets/Photo Album/PhotoService.aspx which should show a bunch of cats! Everything looks good and all we need to do to get the pictures into the widget are two things. First we need to register the jQuery JavaScript file, either localy or a referer to the jQuery official site. Last we need to add some custom JavaScript that makes the Ajax call and puts the html at the right place.

JavaScript blocks should allways, if possible, be placed as close to the </body> tag as possible. The reason is that the browser won't continue to load the remainder of the page when it hits a JavaScript block but rather wait until it is fully loaded. This is not a problem if we're dealing with short scripts but the jQuery library is relatively large in this context so we need to put it as far down the page as possible. Our own script that does the actual work depends on jQuery, thus it must be loaded last. The problem is that we need to do this in a User control in the middle of the page. To our help to solve this we have the ClientScriptManager that every aspx page has. With the method RegisterStartupScript we get to insert arbitrary scripts just before the </form> tag (which is close enough) of the surrounding page. We make the registrations when the widget is loaded, i.e. in the LoadWidget() method.

With this final step done we have our first version of the Photo Album Widget which is ready for demo.

Problems with the solution

Before the second iteration I'd like to summarize a couple of things with version one that are not of production quality.

  1. PhotoService mimics the behavior of a Web service (kind of) but is really a simple aspx page
    - We could have done a Generic handler (ashx) instead but then we couldn't have used a Repeater
    - We could have done a custom HttpHandler but that need to go into App_Code and edit web.config which is harder to install
  2. The requirements maybe fullfilled but no one cares for a widget that only display cats!
    - We need to be able to configure the feed as well as the query.
Tags:   widget, photo album, web service, ajax, jquery, picasa
Categories:   BlogEngine.NET | JavaScript
Actions:   | Ping backs (11)

Applying stylesheets dynamically with jQuery

Saturday, 2 August 2008 21:58 by Rickard Nilsson

Update follow up: jQuery plugin for switching stylesheets

A colleague of mine asked me how to apply a stylesheet to a web page dynamically using jQuery and I had never done such a thing but my first thought was that is must be pretty simple. I've spent a lot of time thinking of so many things other than web et. al. so it was nice to delve into some of that stuff again. Check out the live demo

As we know stylesheets are defined in the head section of an html file like this

<html>
    <head>
        <link rel="stylesheet" href="stylesheet.css" type="text/css" />
    </head>
    <body>
    ...
</html>

Now, say that we want to apply another stylesheet dynamically after the fact, so to speak, triggered by some event. This could be a button click or some other arbitrary event that is triggered. So, what we want to do is simply insert a new <link/> element into the head section of the page DOM. This can be done in a couple of lines of jQuery:

$(document).ready(function () {
    $("a").click(function () {
        $('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');
    });
});

The key is at what time we add the link to the style sheet. The first line in the code above repeated here asserts that the DOM is ready for manipulation.

$(document).ready(function () {
    //...
});

The second part repeated here adds a click event to all hyperlinks in the page.

$("a").click(function() { //...

And the very task is performed by the last piece of code where the head element is appended with a new link element.

$('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');
Tags:   jquery, css
Categories:   CSS | JavaScript
Actions:   | Ping backs (4)

JavaScript resources

Thursday, 20 March 2008 10:55 by Rickard Nilsson

I thought that I should do a post about the JavaScript resources I've found most useful. There are an endless amount of JavaScript resources out there and and there is only so much time you can spend going through them to find what you need. This is my attempt at gathering some of the best I know. So here goes.

JavaScript basics
Tools
  • JSLint
  • JS Minifier
  • JS Beautifier
  • JavaScript reference
    • by W3School
    • nice comparison between browsers
  • JScript language reference
    • by Microsoft
    • JScript 8.0
  • HTML DOM reference
    • by W3School
    • support comparison between browsers
  • JavaScript tips and tricks
    • by PPK at Quirksmode
    • everything including core features, event handling, DOM, CSS modification and Data retrieval
  • Douglas Crockford's JavaScript resource collection
    • Chief JavaScript architect at Yahoo!
    • Papers, tools, videos, links
    • A must see
  • The JavaScript Programming Language
    • 4-part lecture course with Douglas Crockford
    • The basics of JavaScript by the man who architected YUI
  • An Inconvenient API: The Theory of the DOM
    • 3-part lecture course with Douglas Crockford
    • Browser DOM talk by the man who invented JSON
  • Advanced JavaScript
    • 3-part lecture course with Douglas Crockford
    • Advanced topics by the man who wrote JSLint and JSMin
  • Yahoo! YUI Theater
    • Endless of hours of video content

This list became long enough so I will do another post on Ajax resources later on.

What have I missed?

Tags:   javascript, jscript, html, dom, douglas crockford, yahoo, yui
Categories:   JavaScript
Actions:  
 
Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© 2008-2011 rickardnilsson.net
Creative Commons-licens