@ayende You ought to try Mercurial. in reply to ayende 1 week ago
01
Oct

ASP.NET MVC + jQuery – can things get any better for web developers?

Microsoft’s recent decision to include jQuery in the ASP.NET development stack is pretty exciting news. I’ve been using jQuery for a while now, and all I can say about it is that it makes JavaScript fun. You can use it to add some pretty impressive effects to your web pages with only a couple of lines of code, and you have less to worry about as far as the idiosyncrasies of cross-browser detection are concerned. In the past year or so it’s become pretty popular and even something of a de facto standard in many ways, probably best described as JavaScript’s answer to Linq. If you’re a web developer and you haven’t yet come across it, I really would encourage you to check it out — you’ll love it, even if you hate JavaScript.

Hopefully this will attract some more talent back to the .NET platform. It’s been the case for a while now that the best, most passionate web developers — the ones who come up with the all-singing, all-dancing Ajax-y websites and eye candy — have generally been shunning the Microsoft stack in favour of PHP, Django and Ruby on Rails. You can easily understand why — the web forms postback model may be good for simple, fairly generic things, but if you really want to make your website sing, it has restrictions and leaky abstractions that get in the way a lot, such as the limitation of one server-side form per page, or the convoluted id attributes that it sticks in all over the place making CSS and DOM manipulation a major headache, or the monster that is view state.

However, with the ASP.NET MVC framework on the go, we have finally got back the control over our HTML that we need, and now with jQuery forming an official part of it, ASP.NET is becoming an even more exciting prospect again. It’s especially so since in many ways you can really push the boundaries with .NET a lot further than with most other frameworks. Languages such as PHP or Ruby are good in themselves, but they do have their limitations, and it’s not a good idea to try to use them for image manipulation, or genetic algorithms, or Bayesian spam filtering, for instance — they are just too slow for computationally intensive stuff such as that, and in those cases you would need to drop down to C++. On the other hand, in C#, you can do it all in one integrated end-to-end framework, and with Visual Studio, you have what is probably the best IDE on the market to help you on your way.

I’m looking forward to seeing a lot more all-singing, all-dancing websites written in ASP.NET.

18
Aug

Internet Explorer painkillers

Approximately 25% or so of the general population still use IE6, and can’t or won’t upgrade to IE7 for various reasons such as slow Internet connections, old computers, corporate security policies etc. For those of us who build websites that still have to support them, here are a couple of essential downloads that can make life much easier for us:

IE7-js is a JavaScript library that makes IE6 and IE5.5 behave like IE7, fixing most of the HTML and CSS issues that stand in the way of standards compliance. There is also a script that makes IE7 behave like IE8. Should make it much easier to support those older browsers, though I doubt if it will eliminate the need for testing altogether. For that, you will need…

Multiple IE which allows you to run multiple versions of Internet Explorer side by side on the same Windows installation. It includes versions 3, 4.01, 5.01, 5.5 and 6 in a single installation package and it is very easy to set up. Unfortunately, it only works on Windows XP: trying to get IE6 to run in Windows Vista is, apparently, very painful.

05
May

Code syntax highlighting in WordPress – take two

It turns out that the WordPress Syntax Highlighter plugin that I mentioned a couple of weeks ago has some rather nasty artifacts. One in particular is that when you try to display HTML — or any code containing HTML — WordPress tries to “fix” this by adding extra tags that you may not want to make it valid XHTML, and it b0rks your nice tidily formatted source code in the process. Another problem was that it converted emoticons to images — a big no-no when you’re writing source code.

Yeah, maybe I should have been using the rich text editor, but that caused other problems. Rich text editors generally wreak havoc with source code, so it’s best to turn them off when you’re doing anything of that nature.

This was the reason why I stuck with Code Auto Escape for so long. Entering source code is awkward, to be sure, but nevertheless the plugin is pretty robust and does a good job. I did try a few proper syntax highlighter plugins way back, but I didn’t find any of them all that satisfactory. However, Code Auto Escape is a plugin that Just Works™.

It also turns out that Alex Gorbatchev’s Syntax Highlighter JavaScript code allows you to set various options for your code blocks, such as hiding the toolbar or the line numbers, or starting numbering at a number other than 1. The WordPress Syntax Highlighter plugin does not expose these options.

Sooo… why not combine the two approaches?

Over the Bank Holiday I’ve spent a few hours writing a new plugin that does precisely that. I took Code Auto Escape as the baseline, and added a whole bunch of extra code to plug in the syntax highlighter scripts.

Interested? Get Coder 1.0 alpha 1 here.

04
May

How to match any character (including newlines) in a JavaScript regular expression

There is a little gotcha with JavaScript regular expressions. The . (dot) character, which supposedly matches any character, does not match newlines.

Now this is actually standard (if somewhat counter-intuitive) behaviour in regular expressions in most languages, but it can be changed, for example, by setting the RegexOptions.Singleline option in .NET, the /s modifier in Perl, or the PCRE_DOTALL option in PHP.

Unfortunately, there doesn’t seem to be a corresponding option in JavaScript.

However, there is a workaround. The \s character class matches any white space character (including carriage returns and line feeds), whereas the \S character class matches any non-whitespace character, i.e., anything not included in \s. So… if you want to match any character in JavaScript, including newlines, using [\s\S] instead of the dot should do the trick.

For example, to extract the contents of the <body> section of an HTML document:

/<body[^>]*?>([\s\S]*)<\\/body>/.exec(html)
16
Feb

Pro JavaScript Techniques

Since I started taking JavaScript seriously just over a year ago, I’ve found myself a bit disappointed with most of the online resources for it that are knocking around. The main ones seem to concentrate solely on the basics, and tend to be aimed at beginners — people who are happy to write code in a purely procedural manner and just want the basic information needed to get the job done, even if it does mean writing gratuitous amounts of copy and paste code.

Personally, I’ve felt a bit disappointed by this. I’ve said before that I think of JavaScript as the new Scheme — so with that in mind, anything that treats it as if it were merely client-side PHP will naturally be something of a disappointment. Perhaps this is a case of quidquid latine dictum sit, altum viditur on my part, but I like to use closures, lambdas, iterators, generics, Linq and so on in my code to maximum effect. I am also firmly of the opinion that every professional developer needs to be familiar with these concepts too — after all, they show that you have the kind of mind that can handle the complexities of software development, and won’t stumble over the FizzBuzz problem.

pro-jsSo when I came across Pro JavaScript Techniques by John Resig on Thursday, I thought it sounded like a breath of fresh air. Resig is something of a JavaScript guru: he is the lead developer of jQuery, and really knows his stuff, so I expected it to hit the mark in this respect. I promptly ordered it through Amazon.co.uk, and it arrived pleasingly promptly yesterday lunchtime.

The book certainly does not disappoint. Following a short introductory chapter, it gets right down to business with a chapter on the more advanced features of the language such as closures, currying, scoping rules, and how to make full use of JavaScript’s somewhat unorthodox, prototype-based approach to object oriented programming. This is followed by advice on how to write reusable code, unit tests for your scripts, and how to enforce good code conventions with tools such as JSLint. The rest of the book focuses on the practicalities of real world JavaScript as it works in the browser, with chapters on the DOM, events, CSS and forms, and Ajax, and ties it altogether with several practical examples including an image gallery, an Ajax search box, an Ajax wiki, and a Google Reader style "never ending" WordPress theme. He treats the subject in a fair amount of depth, about as thoroughly as you can in 350 pages, covering gotchas and issues with common browsers along the way, and points to resources on the web where you can find out further information.

This isn’t a book for complete JavaScript novices — it assumes a certain amount of familiarity with the language, and is written more from a perspective of adopting professional best practices and producing high quality code rather than from simply getting you up and running quickly, so at least some experience of JavaScript is necessary. However, it is not a difficult read, and a competent developer with at least some basic JavaScript experience should find it fairly accessible.

The only downside to it is that as it is now two years old, there are already one or two omissions that date it somewhat: it does not cover Internet Explorer 7 or Safari for Windows, for instance, and it still recommends testing your code against Internet Explorer 5.5, which has since pretty much fallen off the radar. However, all the content is still applicable today, and no doubt will remain so for quite some time to come. Personally, I would recommend it to any professional web developer who wants to improve their JavaScript skills. (And if you are a professional web developer, you jolly well should be improving your JavaScript skills.)

03
Feb

Published

My blog entry on Volta, GWT and leaky abstractions has been reproduced in the .NET Developers’ Journal.

This was a particularly interesting post because a lot of people are pretty impressed with Volta, and on the face of it, I was pointing out what I saw as its potential shortcomings. It has also attracted some comments from fairly accomplished developers — Bruce Johnson of Google’s GWT team, and Mats Helander, who wrote one of the first O/R mappers for the .net framework. However, while I may have come across a bit negatively, my opinion is not actually so much an anti-Volta/GWT/RJS one as a pro-JavaScript one. Since I started taking JavaScript seriously a year or so ago, I’ve really started to appreciate it, and to be honest, I think that developers who hide from it altogether behind abstraction layers of whatever nature are really losing out.

I’ve also had an e-mail from a journalist asking me for my opinion on MySpace for an article that she’s writing. I’m not sure I’m the best person to ask on that one to be honest: my experience of MySpace is pretty much limited to opening an account, discovering it doesn’t work with Windows Live Writer, closing it again, getting spammed, and experiencing all the yuk-that-is-gross reactions that any respectable, standards compliant, XHTML addicted web developer experiences on seeing your average profile page with gratuitous background images, animated GIFs, thrash metal background music, and broken rendering in Firefox.

It’s interesting where blogging can take you…

11
Dec

Volta, GWT and leaky abstractions

There’s been quite a bit of hype recently about Volta, the latest and greatest offering from Microsoft. It’s a bit like the Google Web Toolkit or RJS in Ruby on Rails, in that it allows you to write everything in C# and have it translated into JavaScript. You don’t even have to use C#—you could just as easily use VB, since it works on the compiled MSIL, converting that into JavaScript. It allows you to split your application at the lower tiers as well, automatically generating web services so that you can put, say, the user authentication part of your application on a different server to the main site.

It sounds like a good idea in theory, and no doubt it will attract quite a bit of attention from developers who do not want to have to learn yet another programming language. The main attraction of this kind of framework is for developers who are frightened off JavaScript by all the cross-browser insanities and the useless, bizarre and often totally misleading messages that Internet Explorer throws up when it encounters a JavaScript error. The old “Syntax error in line 0″ syndrome. There is also the issue of testing on multiple browsers on multiple operating systems. But hey, now we can write JavaScript without writing JavaScript!

But is it really necessary?

About a year ago, I would have given an emphatic “yes” in answer to that question. However, a lot has happened in the JavaScript world in the past year and a half. We now have free virtualisation software and Intel Macs, so you can run several different operating systems—Windows XP, Windows Vista, Windows Server 2003, Linux and Mac OS X—on the same machine if you are that way inclined, making cross browser testing a whole lot easier. Firebug turns Firefox from a humble browser into a powerful debugging tool. JavaScript frameworks such as Prototype, Scriptaculous, jQuery and Dojo abstract away all the nasty cross-browser stuff, allowing you to discover just how nice a language JavaScript really is. And on top of that, they give you transitions, drag and drop, thickboxes, fade anything techniques, and a whole lot of other eye candy and cool stuff as a bonus.

I’m also rather sceptical of the whole write-language-A-in-language-B business.

Admittedly, I’ve never actually tried the Google Web Toolkit or RJS, but my guess is that while there’s undoubtedly a lot that you can do with them, I doubt if they’re the most efficient. Writing JavaScript in C# or Java or Ruby will inevitably involve a layer of abstraction, and all abstractions are, to a greater or lesser extent, leaky.

Now before you shout me down on this one, yes, I know that Prototype and jQuery are abstraction layers, and therefore may well have plenty leaks of their own. However, the point that I am making is that the process of converting between languages adds a whole further abstraction layer in addition. Making the whole thing even leakier.

At present, Volta has a lot of leaks. Late binding is not supported, for instance, which means that languages such as IronPython, IronRuby or PHP (via Phalanger) are effectively ruled out, and Visual Basic requires you to use Option Strict. This seems a bit surreal given that JavaScript itself is also a dynamically typed language, but it is a consequence of the fact that it all goes through the statically typed MSIL intermediary, and support for reflection (which is needed to simulate dynamic typing on a statically typed platform) is severely limited.

I am also sceptical of the benefit of being able to move parts of your application between the client and the server. Far from making things simpler, this could introduce a whole new can of worms if it is not carefully thought out, partly in terms of performance, particularly if you end up with a very chatty interface between them, but much more seriously, in terms of security. Maintaining state across multiple tiers is also very difficult if not impossible to abstract completely transparently, and it will be interesting to see how they tackle this problem.

However, it is probably a little unfair to knock it too much at this stage. Volta is only a technology preview and pretty experimental, so obviously some of these leaks will be patched as it matures. On the other hand, undoubtedly other leaks will remain and may even prove impossible to patch—in particular, performance will never be the same as with pure vanilla JavaScript, and download sizes will still be greater. So by all means check it out if you like, but as far as I’m concerned, if a task calls for JavaScript, JavaScript is what I intend to use.

22
May

The functional beauty of JavaScript

I’m the kind of developer who tends to sit on the “coding” side rather than the “design” side of the fence. I’m at my happiest when I’m designing web services, database access and application architecture, and although I do enjoy the odd creative spurt with Photoshop and the like, I don’t find it as interesting as the former. Consequently, until a couple of years or so ago, I only gave JavaScript and client-side development the bare minimum of attention that I needed to do my job. What with all the lunatic inconsistencies that you needed to handle in order to cope with Netscape 4 and Internet Explorer 4, I always perceived it as a monstrosity that needed a lot of ugly hacks to get it to do anything more compelling than bring up a dialog box saying “Hello world”, and was content to merely download whatever scripts I could find off the Internet to make it do whatever I needed it to do.

These days, of course, the story is quite different: you have some nifty tools such as Firebug, and despite the myriad rendering bugs in Internet Explorer, standards such as CSS and XHTML make browsers are a lot more compatible with each other than they used to be, plus of course there is all the cool stuff that you can do with Ajax. All this makes learning JavaScript a much more attractive prospect, and not surprisingly I’ve had to do a lot more of it in the past couple of years than ever before.

It’s been a real eye-opener. Far from being the ugly, kludge-ridden monstrosity that I’d always thought of it as being, JavaScript is actually a beautiful, well designed language with some very nice constructs. I always thought of it as one of those linear, procedural languages much like VBScript or Fortran with some vaguely object-oriented bits and pieces thrown in as an afterthought like PHP 4, but in actual fact it has much more in common with functional languages such as Scheme, OCaml or Haskell. It has closures and first-class functions, for example, which means that you can express some things in very clever, succinct and beautiful ways.

One particular JavaScript framework that has gotten my attention in the past few months is jQuery, and it’s become my library of choice for DHTML and Ajax gee-whiz. It’s an increasingly popular and fully featured toolkit that enables you to do some pretty clever stuff with only a handful of lines of code. For a simple example of what you can do with it, here is a code snippet that will highlight rows in a table when you mouse over it:

var highlightColour = "#ffff00";
var normalColour = "#ffffff";

$(document).ready(function() {
  $("#my-table tr").hover(
    function() {
      $(this).css("background-color", highlightColour);
    },
    function() {
      $(this).css("background-color", normalColour);
    }
  );
});

I love the simplicity of this. As the WordPress guys say, code is poetry.

(Update: Jeff Attwood has an interesting take on the subject where he describes JavaScript as “the lingua franca of the web” with the likes of Flash and Silverlight as merely pretenders to the throne.)

20
Dec

Firebug – the best Firefox extension ever?

I came across Firebug this morning via Matt Mullenweg’s blog. It is without a doubt one Firefox extension that no web developer should do without.

It’s an awesome plugin. You can debug and profile your Javascript code, step through it line by line, set breakpoints, inspect objects and variables, and quickly find errors when they happen, with detailed and useful information. It has a command line that lets you execute Javascript on the fly. You can edit your HTML and CSS on the fly and have the changes show up immediately, explore the DOM, and monitor the network activity involved in each page request, showing you the HTTP request and response headers for each file that it fetches.

All in all, it has just about everything you need to develop client-side JavaScript effectively and easily. And best of all: like Firefox itself, it’s free and open source.

Just one thing I don’t understand though. Once it is installed, it is disabled by default and you have to enable it, either globally or on a site-by-site basis, before you can use it. I presume that there’s some rationale to this — possibly something to do with either security, performance or stability — but I’m not sure what it is. Can anyone enlighten me?

20
Apr

Eolas v Microsoft and FlashObject (continued)

Microsoft caused a furore earlier this month when they rolled out the update to Internet Explorer on the eleventh of April to implement some changes to the browser behaviour in the light of their legal defeat by Eolas. Not only was this earlier than anticipated (their court imposed deadline is the middle of June) but they also bundled it in with the latest round of security updates. Anyone who has updated Windows, either automatically or manually through Windows Update, will be affected.

The update does not result in any loss of functionality. ActiveX controls such as Flash animations, embedded Windows Media players and Java applets will still play as normal, but they will ignore all user interaction until you click on them to “activate” them.

If your Flash animation or embedded media player is merely cosmetic, you may not need to take any further action. However, if it has some interactive functionality such as navigation, less knowledgeable users may get confused and think that your site is broken. Rollovers will not work until the animation is activated, for instance.

As I mentioned in my previous blog entry, I have been using FlashObject to work round this issue. It is fairly easy to implement this with only a few lines of code. You can wrap your <object> tags in an HTML container tag such as <div>, <span> or <p>, and add just a couple of lines of extra code to load in the object:

<script language="javascript" src="/path/to/flashobject.js"></script>
<div id="myFlashContainer">
  <object width="400" height="200" clsid=blah blah blah blah blah...>
    <!-- and so on... -->
  </object>
</div>
<script language="javascript" type="text/javascript">
  var fo = new FlashObject("/path/to/flash/animation.swf",
        "myFlashObject", "400", "200", "7", "#ffffff");
  fo.write("myFlashContainer");
</script>

The script works by swapping out the Flash animation within the container, which does not automatically get activated, for a new, dynamically loaded, <object>, which, does, due to a loophole in the Eolas patent. The parameters are: the path to the Flash object; a unique ID which is assigned to the created <object> tag; the width; the height; the version of Flash which is required to view the animation; and the background colour.

Geoff Stearns gives fuller instructions and details about FlashObject on his website.

Open source browsers such as Firefox are not affected at this stage. Eolas founder Mike Doyle has stated that he intends to license the technology free of charge to open source projects, but what exactly comes out in the wash in that department remains to be seen.