ASP.NET MVC3 Razor view engine – some initial observations

Over the last couple of days I’ve started playing around with the razor view engine that comes with ASP.NET MVC 3. The first thing you notice is how much cleaner your markup pages look. It’s a real pleasure to code your markup without having to pollute it with masses of special code nuggets to demarcate your C# code. If you haven’t seen any examples yet check out Scottgu’s intro to Razor.

The error reporting still looks like it could do with a little work though. For example yesterday I put code very similar to this in my view:

@for(int i = 0; i < 5; i++) {

And I got an error message like this:


Humm… “No overload for method ‘Write’ takes 0 arguments” – what does that mean? Well the answer is that the @ symbol before the closing curly brace isn’t needed. So the fix was simply to make the following change:

@for(int i = 0; i < 5; i++) {

I guess once you’ve used razor for even a short while things like this will become second nature, but it had me stumped for a short time and it’d be nice if the error messages due to view engine parser failures were slightly more helpful in identifiying the exact problem.

A:Hover and IE – a trap for young players

If you’re having trouble getting your a:hover effect to work in IE you might want to make sure you have an href attribute on the anchor element. The hover effect won’t work in IE unless it does.

I had something like the following:

<a onclick="somejavascriptfunction()">Anchor text</a>

Changing to this solved the issue:

<a onclick="somejavascriptfunction()" href='#'>Anchor text</a>

It’s a bit embarrassing and I should know better. I hope this post helps other people avoid wasting time like I did.

IIS gzip compression: the missing link

I’ve been wanting to enable gzip compression for our static content (javascript and css files) for a while but just haven’t been able to get IIS 7 to comply. Apparently static compression is enabled by default in IIS 7 but when inspecting traffic using fiddler I wasn’t seeing my static content compressed.

Solution at last

After several hours of googling and trying various unsuccessful solutions I finally found the answer! Buried in the comments of a post on Rick Strahl’s blog, Imad Jureidini had pointed out the following:

I’ve been running into the same issues. Ultimately, the solution was to change the following config setting:

<serverruntime frequenthitthreshold=”1″>

The default value here is “2”, which means that even static content does not get compressed if it isn’t requested twice within a 10 seconds period (frequentHitTimePeriod). Switching to “1” means that the file gets compressed right away.

Hopefully this will fix your problems too 🙂

– Imad

To confirm that this was in fact the problem I was experiencing I did a control refresh of my website several times in very quick succession. Sure enough the css and javascript files suddenly started coming through compressed.

I then used the following command to change the setting in my servers config:

%windir%system32inetsrvappcmd.exe set config
-section:system.webServer/serverRuntime -frequentHitThreshold:1

After restarting IIS I tried a control refresh of the website again. As expected the css and javascript files were delivered compressed on the first request.


This begs the question – why would Microsoft do such a thing? Surely the point of compression of static resources is to reduce delivery time to the browser. Why should my users care if anyone else has recently requested the particular resource they are interested in? They aren’t and shouldn’t be. These static resources should be compressed first, time everytime. (The only exception to this would be where compression is straining the servers ability to serve content).

Where is the documentation?

I’ve got to say my experiences with IIS 7 to date have been one frustration after the next. Microsoft appears to have put a lot of work into this product and at first glance a lot of the new features look to offer real value. What I don’t understand is why there is so little documentation on this new product. So much has changed from IIS 6 there really needs to be a comprehensive set of documentation available somewhere – if it does exist I have yet to find it…

MooTools slide effect and Internet Explorer CSS

Have you struck a problem with MooTools slide transition and CSS styles not appearing correctly in IE? I ran into this exact issue the other day where I was trying to slide a DIV element up and down based on a click event elsewhere on the page. The CSS style applied to the DIV looked something like this:

#slidingDiv {
    padding-bottom: 10px;
    background: white url(../images/box_bottom.gif) bottom no-repeat;

The problem seems to be that IE can’t calculate the height of content in the dynamically resized DIV correctly and thus the padding-bottom and hence my background image (nice rounded corners in this case) wasn’ showing.

The solution

The fix turned out to be simple enough, I just made the height of the DIV fixed in the CSS. Once IE knew how big the inner content was supposed to be everything started working correctly.

RowUpdating event and UpdateRow method of a GridView not firing

We struck a bit of an odd problem today. We had an older ASP.NET 2.0 website we were migrating to ASP.NET 3.5 and one of the pages has a GridView on it. As we use Spring.NET and NHibernated Microsofts new objectdatasource approach for binding the GridView won’t fly so we were using old school databinding. This meant we needed to be able to handle the RowUpdating event in order to persist our changes. The problem was that the RowUpdating event just wasn’t firing.

Eventually we tracked it down to a weird interaction between Spring.NET and the GridView where if we wrapped the GridView in a spring:panel and suppressed dependency injection the event started firing. Of course the new and old values that are supposed to be available in that event handler were still null…

There is obviously a bug with the databinding in the GridView somewhere and it seems Microsoft is aware of the issue, however I wouldn’t hold my breath for a fix to be forthcoming.

Personally I think the new objectdatasource model has some serious drawbacks and the fact that Microsoft haven’t made the effort to ensure that custom databinding still works is a real shame to say the very least!

MooTools ASP.NET Webservice Ajax calls.

I had some trouble trying to find an example of how to call an ASP.NET webservice from MooTools. I eventually pieced the bits together from a couple of forum posts and thought I’d post an example here in case anyone else was having the same problems.

If I have an ASP.NET webservice that has a GetById method that takes a single int parameter and returns an object I can call it with the following code:

function doAjaxWebServiceRequest (id) {
var completeDelegate = Function.createDelegate(this, this.callback);
var failureDelegate = Function.createDelegate(this, this.error);
var request = new Request.JSON({url: ‘http://hostname/MyWebService.asmx/GetById&#8217;,
onComplete: completeDelegate,
onFailure: failureDelegate,
urlEncoded: false,
headers: {“Content-type”: “application/json”}
request.send(JSON.encode({‘id’: id}));

The returned object will be in JSON format. The lines where I create my callback delegates using the Function.createDelegate method allow me to set the scope of ‘this’ in my call backs to be the object I making the request from.

Hope that helps someone out!

Mootools differences in IE and Firefox

We’re using the MooTools scripting framework on our site and today I discovered a strange difference between Firefox and IE. I was creating an element and injecting it into the DOM and then trying to change its CSS class and styles.

addClass and setStyle
MooTools provides methods on it’s Element class that allow you to manipulate the CSS styling of an element. You can do things like:

// Add a css class to the element with the id foo

// Set the width of the foo element
$(‘foo’).setStyle(‘width’, ‘100px’);

Unfortunately when viewing an ASP.NET page in IE that includes a script that uses these functions you get a script error saying that the “Object doesn’t support this property or method”

At first I thought the solution was to go back to basics:

// Add a css class to the element with the id foo
$(‘foo’).className = ‘fooStyle’;

// Set the width of the foo element
$(‘foo’).style.width = ‘100px’;

However I then realised that I was trying to call the MooTools Element methods on a vanilla element object rather than a MooTools one. The second line below solved the problems in IE and meant I could go back to the first way of applying the styling.

var myelement = document.createElement(“a”);
myelement = $(myelement);

IE vs Firefox
In retrospect it seems strange that this worked in Firefox, I guess Firefox must be able to do some sort of implicit conversion to a MooTools element in order to resolve the method call.

MooTools seems really great, it’s lightweight and easy to use. The learning curve seems much lower than some of the other more complicated offering available.

The only reservation I have at this point is that from what I’ve read on the forums it doesn’t play nicely with any other scripting framework due to it’s lack of namespaces and the maintainers seem quite hostile to anyone who suggests that would be a good thing.

Book Review: CSS Mastery

var country_code = geoip_country_code();if (country_code != “GB”){document.write(“”);}else{document.write(“”);}
As a web developer I’ve had to do a certain amount of CSS development over the years but never really felt like I understood it. CSS can be a bit of an esoteric beast and I wanted something to clear the fuzz away.

CSS Mastery was the solution I had been looking for. Andy Budd writes in a clear and engaging manner and the book is extremely readable for a technical text. Andy starts by getting right back to basics covering the Cascade and the Box model in the first two chapters.

The book covers most aspects of CSS with concise and easy to understand examples used through out. Andy also spends a good amount of time on cross browser compatibility issues where appropriate, as well as including a whole chapter of hints and hacks on this topic at the end.

If you are just starting out with CSS, or like me have used it for years but never really understood it at a visceral level then I urge you to give CSS Mastery a try.

Why new website startups fail?

I’ve been under an enormous amount of self induced stress lately due to the fact that my startup business still isn’t online. This is due to a number of contributing factors of course, but it got me thinking about some of the reasons why it’s taken so long.

Manage Scope: Trying to do to much too soon

It would be my guess that a large number of failed business (particularly online ventures) are guilty of this one. If nothing else this experience has taught me that you need ensure your initial offering constitutes a realistic amount of work. You can then build on that by making small incremental improvements adding features and new offerings to your business over time with much less effort than trying to do it all in one go.

By all means, have a grand all encompassing vision, in fact I’d almost consider this a prerequisite, but break it down into realistic bite size deliverables. To make a software analogy; you want to take a rapid iterative development approach rather than attempt a huge waterfall model project.

It doesn’t have to be perfect

There is always a tendency with geeks (myself included) to try and engineer the best, most flexible, and high performance solution first time round. Unfortunately this flies in the face of getting a new business off the ground. As a new start up you have limited time and money and you can’t afford to waste either trying to come up with the “ultimate solution”.

Any coder worth their salt is going to try and anticipate performance bottle necks and design and develop their software to avoid potential pitfalls. However you’ve got to keep your focus on the goal of delivery at all times and not get trapped in refining and improving your product without delivering. It doesn’t matter if you have the best website in the world if no-one can use it because it isn’t online yet!

Don’t forget the business

Project planning, it’s not fun and certainly not something most geeks enjoy. Unfortunately it is absolutely necessary to make your new business a success. You need to have a clear idea of what your deliverables and deadlines are, and what your outstanding tasks are at all times. There isn’t much point getting to the end of development, having built an outstanding best of breed product and suddenly realising you don’t have a company set up, bank accounts, tax registration, contracts, lawyers, accountants and all the other mundane things that are prerequisites to running a business.

Are you trying to get a tech startup off the ground? Do you have any advice for other would be entrepreneurs?

Mono bugs fixed; Spring.Net support coming soon!

I’ve managed to get all my Mono patches committed in time for 2.0 which be released very soon. Bugs I’ve fixed are:

#325128 ConfigurationSection.GetRuntimeObject
#395209 Fix incompatibility in the HierarchicaDataBoundControl
#397612 Mutually exclusive behaviour between Mono and MS.NET for xs:import

As well as a couple of other fixes I didn’t create bugzilla bugs for:
The TypeDescriptor bug which I blogged about a while ago, and another XmlSchema bug where Uri.OriginalString wasn’t being returned in the correct case.

Hopefully with these Mono bugs fixed in the latest release the major barriers to getting Spring.Net support finished and committed in will be removed. I’m in the process of working through my patch with Mark Pollack, so all going well we may see some Mono support in the next Spring.Net release.