Razor is sharp, but NHaml is still haiku for HTML 5 and JQuery

A colleague of mine told me recently about Razor, the view engine for ASP.NET MVC 3, and upon researching it and using it in a test project, I almost instantly came to compare it to NHaml since I’ve been using HAML for several years doing rails on the side. What I found is that though Razor is the best view engine I’ve seen from Microsoft (on top of a great version 3 of ASP.NET MVC – nice job guys), I still believe NHaml’s syntax is significantly better suited for HTML applications and even more so if they use JQuery.

Though Razor does a great job requiring minimal characters to insert executable code logic in between the markup it generates (and is basically equivalent in that respect to HAML), it does nothing for minimizing the amount of code you have to write to express the HTML outside of those logic statements. NHaml is simply superior here when you are generating HTML for this reason: it reduces markup to the minimal information needed to identify the JQuery or CSS selectors that elements have applied to them.

It does this because with NHaml normally you specify the name of an element without the angle brackets, but if the tag you want is a DIV element with an ID attribute, you can just specify the ID prefixed by a hash symbol and drop the DIV altogether.

<div id=”blah”></div>

becomes:

#blah

This also works for CSS classes. This dramatically increases code readability because lines of code begin with the JQuery selector or CSS style name used to access them. When writing Javascript or CSS, locating these elements in markup is much easier. This is already on top of the fact that NHaml drops the requirement for closing tags.

Here’s an example that I think illustrates the point. Let’s say I have a CSS style sheet with the following styles. Don’t worry about the attributes in the styles themselves just look over the list of CSS selector names (container, banner etc.) and think of looking at this file day to day:

#container { width: 100%; }
#banner { background-color: blue; } 
.topic { font-size: 14pt; }

Now here’s some HTML markup styled with selectors in the above sheet in HAML:

#container
  #banner

    .topic Hello

Here’s how you would generate the exact same markup using Razor:

<div id=”container”>
 
<div id=”banner”>
   
<div class=”topic”>Hello</div>
 
</div>
</div>

Building on this let’s say we wanted to override the .topic style inline with some other styles, and throw in some inline JavaScript. Here’s HAML again:

:css
  .topic { font-size: 14pt; }

:javascript
  alert(‘hello!’);
#container
  #banner

    .topic Hello

and here’s Razor:

<style type=”text/css”>
.topic { font-weight: bold }
</
style>
<javascript type=”text/javascript”>
alert(‘hello’);
</javascript>
<div id=”container”>
 
<div id=”banner”>
   
<div class=”topic”>Hello</div>
 
</div>
</div>

Hopefully you can see the HAML is much easier to read, and reduced in lines of code by about 15% in this example.

Here’s another great post from late last year that shows some comparisons of Razor and NHaml.

Using LABjs to get AJAX-loaded ready callbacks

I discussed in my previous post a function I’d came upon through searching that allows HTML that is appended to the DOM through AJAX which includes SCRIPT tags to wait until they have loaded before firing ready events. Upon testing it in Firefox, I found that it wasn’t working in some scenarios, so I began searching again and found LABjs. LABjs stands for Loading and Blocking JavaScript and allows you to chain loading of scripts together and end that chain with a function that gets called back. The nice thing is you can choose to use the word “wait” between load methods and it will block before loading the next, or if you omit the wait, the scripts will load in parallel, speeding up load time of your web application.

Here’s an example. Let’s say you have a site that loads a partial section of HTML from an AJAX request and you’re going to append it to the page, but it includes some scripts in it. Your script is dependent on two other publicly hosted scripts (twitter, Google maps for example) and can’t execute until those are finished loading. Rather than load them in your main page and increase startup time, LABjs handles it perfectly:

Old AJAX response HTML:

<script src=”http://publicwebservice1.com/script1.js” />
<
script src=”http://publicwebservice2.com/script2.js” />
<!– This can’t execute until the first two scripts have loaded, but not all browsers load these in order in a dynamic update to the DOM! –>
<script src=”myscript.js” />

Old myscript.js contents:

<script type=”text/javascript”>
$(document).ready(function() {
// This will fail if the first two scripts haven’t loaded yet
var script1Object = new PublicWebService1.APIObject();
var script2Object = new PublicWebService2.APIObject();
}):
</script> 

Replacing this with LABjs becomes:

<script type=”text/javascript”>
$LAB
.script(‘http://publicwebservice1.com/script1.js’)
.script(‘http://publicwebservice2.com/script2.js’).wait()
.script(‘myscript.js’).wait(function() {
var script1Object = new PublicWebService1.APIObject();
var script2Object = new PublicWebService2.APIObject();
});
</script>

Accessing dynamically loaded scripts with JQuery via AJAX

I’ve been working on a side project in rails that uses AJAX for all posts to the server with JQuery BBQ as state management (using the hashchanged event to provide bookmarkable views) and ran into a problem that can happen to anyone using JQuery. When AJAX calls are placed, they often retrieve HTML that contains script tags in it and then place this HTML into the calling page’s DOM. The problem is that usually one can use JQuery’s ready event to wait for the document to finish loading before accessing objects in those scripts. However when a Webkit based browser (such as Google Chrome) loads this content, it doesn’t wait for the scripts to load before firing the ready event. In my case I was implementing ReCaptcha for image verification of users signing up for my site and the JavaScript provided by them was getting inserted into my registration page via AJAX.

After massaging Google keywords to find the right query and paging through several results, I found a post with a great solution. Basically this code parses your HTML on the client for script tags and loads them separately before returning from the function. I’m now using it anywhere I inject code into the page that has SCRIPT tags via AJAX.

The state of Inductive User Interface (IUI): here to stay

Back in 2004 I left Rockwell Software (a subsidiary of Rockwell Automation) to join a small company that needed technical and design leadership for a potential touchscreen application for the pharmaceutical industry. As part of my design, I had to do research on usability of touchscreen interfaces. This led me to study panel designs in Japan and the manufacturing industry and eventually Inductive User Interface (IUI). IUI is a user interface design approach that emerged with Microsoft Money 2000 and has infiltrated many of the software applications we use today, most notably Windows itself.

IUI emerged as a realization that there are two different classes of use of software. The first is through deduction which is common to power users such as myself that are typically programmers, IT personnel, or other more technically sophisticated roles in an organization. When a new application is installed on our computer, we typically flip through the menus at the top of the window, or hover over the tooltips of the toolbar buttons to find out what was available. Sure there is online help, but we can usually deduce what to do simply by exploring these common controls. Deductive user interfaces are better for people who use the same application over and over again. Once a graphic artist has used Photoshop or Illustrator for a while, they want many actions available in the same place and in the same screen. An IT administrator also needs a single page they can use to administer a user account and modify anything about them.

Microsoft realized that the other way most use software is infrequently. The most common example of this is the control panel in Windows. Many home users of Windows rarely use the control panel and so when they go in to configure settings, they don’t remember anything at all about the screens. IUI makes the user interface’s purpose on each screen explicit – there is no exploration or guesswork involved. It also forces UI designers to break the software up into more steps or screens, and as a result will slow the process down some for power users. However Microsoft (correctly) determined that the 80/20 rule applies here – 20% of users of their OS are power users.

This screenshot from Microsoft’s IUI guidelines whitepaper (published 2001 but still very relevant as I’ll get to) illustrates the paradigm shift well:

ms997506.iuiguidelines02(en-us,MSDN.10)

Microsoft Money 99 “Account Manager” screen

The first thing a user thinks when reaching the page is “what can I do here?” The title says “Account Manager” but the primary purpose of the screen isn’t clear. There are buttons on the bottom of the screen that allow the user to do something, but they are disabled until an item from the list is selected. Additionally, there’s no easy way to get back to the previous page or a “home” screen of sorts.

Here’s Money 2000’s version of the same screen:

ms997506.iuiguidelines03(en-us,MSDN.10)

Microsoft Money 2000 “Pick an account to use” screen

Here the purpose of the screen is clear – “Pick an account to use”. Once the user selects an account from the hyperlinks on the right (which still show the rollup dollar information) they are then presented with a new page with links that allow them to do things with that account. Links are available allowing them to navigate back to the previous page. Additionally, IUI allows for a “task panel” of actions on the left or right side of the screen that are related to account management but not a single account itself.

Read the full whitepaper for more information about the background of IUI. Interestingly, Microsoft’s Windows Vista, and more recently Windows 7 User Experience Interaction Guidelines don’t mention IUI explicitly but the common controls of the operating system are designed for these exact types of user interfaces. Specifically, check out Silverlight and WPF’s navigation framework that allows you to create separate pages easily with built-in browser-like “back” and “forward” buttons. A look at any Windows control panel applet, many screens and dialogs in Visual Studio 2010, as well as the task panels in Office show that IUI is a powerful tool throughout Microsoft’s suite. Other vendors like Intuit, Apple, and Google regularly use IUI in store checkouts, configuration screens, and other infrequently used parts of their applications.

I’d encourage you to learn the IUI design principles and adopt them to the way you design software for your clients to give them more usable interfaces. Here are a few of the ones I use the most (and some I’ve come up with on my own).

  • Select a title that asks the user to do something.

    • Don’t use the words “and” or “or”. If this happens – you need to design two screens!
    • For screens that allow the user to review something, make the title “Review the details of this <object>”.
  • Include an instructions line below the title that gives additional information about what’s presented. For example in the Money 2000 screen above this line might state “Account totals are listed to the right of each account. To perform more actions on the account, click on its name.”.
  • Avoid horizontal scrolling (and vertical if on a mobile device or tablet/touchscreen!).

    • If you have a grid, show only the most important columns of info about an object being viewed.
    • Allow the user to select the items in the grid to get more information about them.
    • Alternatively, don’t use a grid and use custom XAML or HTML markup that creates rows of detail/header information.
  • Place “global” actions (like “Home” or “Logout”) in a dedicated panel at the top or bottom of the screen where they are always available.
  • Make mockups in Balsamiq, Sketchflow, or another low-fi mockup application of the main screens

    • Once you have the mockups go through the flow of the application and look for opportunities to connect related screens through related actions on the task panel.
    • Identify user roles that need access to each page and/or link and design your permission system around this.
  • Designs screens after domain objects in the business’ natural language e.g. Orders, User Accounts, Patients, Subscriptions etc. Then design the related screens for each domain object.
  • When you have more than 5 actions that can be taken on an object selected in a previous screen, break the actions up into categories and make the user select a category first. These are “category navigation pages” and I’ve found numerous cases where they make an application highly usable.

IUI is not a perfect fit for every application, but many product managers and power users at companies who are designing new versions of their applications, or new products altogether, do not have a background in modern UI design and are unaware of this approach. They can also be tainted by previous experience and knowledge, leading them to believe their user base doesn’t need things to be broken up into “so many screens”. Use the research Microsoft has provided and examples of modern applications as leverage to open up the discussion and enable them to take part in designing the software in a more usable fashion. Whenever I’ve had the opportunity to use this approach, the results are often eye opening to everyone involved and can have a dramatic effect on users understanding the big picture of their flow of work.

I’m glad Microsoft is embracing convention over configuration

I read Agile Web Development with Rails while visiting San Diego a couple years ago and was blown away by how well put together of a framework it was. What the book helps you realize is that if you follow certain naming conventions for your code artifacts (in this case ruby source files), it automatically wires up communication between the different architectural layers of your application.

With the recent release of ASP.NET MVC 1.0, which is Microsoft’s answer to ruby on rails, Microsoft has provided what seems to me to be a simpler approach to web applications and adapts to testability better than the oft-complicated event model of existing ASP.NET web applications.

I also downloaded Silverlight 3 Beta, Expression Blend 3 Beta, and Microsoft’s Rich Internet Application (RIA) toolkit preview. The new version of Silverlight has a ton of controls, and I love that editable forms with built in wiring up to validation are included out of the box!

When you have the RIA toolkit installed, you can create a data model in Entity Framework in your web application, create a special link to it in your Silverlight “client” project, and you can wire up similarly named domain objects to databind to your Silverlight project and the databinding hits the server using REST transparently. It’s very slick.

ASP.NET MVC Preview 5 Released

Scott Guthrie’s Blog Post has more details here. My only concern at this point is that a new attribute “AcceptVerbs” has been added, which specifies which HTTP verbs a method supports. If ASP.NET MVC eventually supports returning JSON, XML, and other types based on the requested content-type, it needs to be decoupled from HTTP to compete with rails here.

Late May goodies on Microsoft blogs

Here’s a quick rundown of some stuff going on around the Microsoft blogsphere related to development of applications like those created by the custom development teams here at Catapult Systems:

Microsoft’s support for Ruby, what’s the strategy?

Today I came across a blog post by Charles Nutter that was linked to from a post in the IronRuby mailing list. This fellow has a very good blog and writes an interesting post about the current state of ruby implementations, inlcuding IronRuby, from his point of view. I think for the most part, he is spot on with all his conclusions. He makes the statement that Microsoft would never back an open source framework like rails in preference to its own. This seems to have caused a bit of a stir on the rails mailing list and folks are coming up with replies. Here’s mine.

Microsoft used to write IDEs for C++ before all this framework madness happened (I’m talking before MFC even). Folks stayed with Microsoft’s tools over others because they found them to be of higher quality and the productivity enhancements brought by the IDE saved them time and money. Today Microsoft holds industry control of the runtime and compilers itself for their .NET framework, and so for most folks on Windows, they are the only ones that offer a development IDE for it. Sure there is eclipse support for C#, SharpDevelop, and Microsoft has always touted that anyone with a text editor and command-line can build apps but due to the design and breadth of the class libraries this really isn’t feasible. You don’t see most folks using non-intellisense aware Java IDEs these days when Eclipse is around. Now I don’t really believe that Microsoft planned for Notepad to be a real development environment for .NET, I think this statement was more about proving the opportunity for other tools in the market to target .NET.

Rails is not just another bytecode based, intellisense requiring, class-library-laden layer over your operating system like .NET or Java are. Sure ruby could be argued as such but the knowledge of a small subset of Ruby plus the simple and elegant design of the libraries in rails make up a smaller set of APIs that let someone be very productive in their target space (web applications and services) without an IDE, as Microsoft had originally touted for .NET. While Microsoft has been working on creating tools for generating DSL’s with .NET (domain specific languages, where you only need a subset of APIs to deal with a industry or problem domain when coding against it with .NET) Rails has actually delivered this albeit with the entire runtime platform, and targeting web applications as the “domain”.

Rails and ASP.NET aside, I am personally not impressed with the current state of web applications. AJAX is a hack, and I was doing XML HTTP requests to classic ASP pages back in 98 because Internet Explorer let you create some higher fidelity user interfaces than was possible with Visual Basic, MFC, and the like at the time. I learned early in my career that a sharp user interface outweighs some fancy code (though I’ve learned since that maintainability is right up there, and hence, DRY API design) so going through all this work to get a snazzy HTML UI was worth the effort from an innovation standpoint. Fast forward to today – innovation in the user interface either requires a boatload of javascript in the form of frameworks like prototype, other open source javascript libraries, or Microsoft’s atlas – and custom code that is always a pain to get working on all the browsers. Many shops resort to go with ASP.NET, require the clients to use Internet Explorer, and call it a day. Others that aren’t tied to Microsoft are choosing rails and hitting the ground running. These shops won’t bother with IronRuby or the DLR unless it lets them do things from the UI that isn’t possible with rails, or develop things faster than rails lets you do. The only way Microsoft will draw these folks in is by having a MVC framework that’s as productive as rails and provides a better UI (Silverlight). Serving Silverlight from ASP.NET apps, ASP.NET MVC, and the Dynamic Silverlight projects are a step in the right direction, but not really whole-heartedly solving the problem IMHO.

If you look at Microsoft’s revenue, they are making far more money nowadays on Sharepoint, Exchange, and Windows Servers than on any of their development tools (Team Foundation Server makes them some cash too, but adoption seems relatively low). Many of the features in these products were built on .NET. Should IronRuby produce a high performing, CLR interoperable VM as is its goal, Microsoft encounters its usual dilemma. How do we support previous technology (.NET) and move forward at the same time with a completely different MVC paradigm such as rails enables. Unless you work for Microsoft, and even if you do, some of these strategic conclusions are hard to determine. A possible obvious solution would be that Microsoft will employ IronRuby as a language to use with their ASP.NET MVC framework. They will also use IronRuby, as they have in many demos, to serve Silverlight pages from the server (ala the Dynamic Silverlight effort, again). The problem I see with both of these is that most developers do not make great decisions about which APIs to leverage and not to leverage in .NET when building applications. There needs to be tighter control than just enabling the entire .NET platform’s libraries accessible from these technologies to create maintainable architectures in application’s code bases. I already see a host of browser served, ruby utilizing, .NET framework bastardizing apps that do crazy things from an architectural standpoint resulting in difficult deployment, and wildly different code organization.

One of the successes of rails to me is minimizing the number of APIs you need to do real work, and having standard conventions for placement of things. In the current ASP.NET MVC implementation, there is still a lot of calling C# code to wire up things like routes and opportunities for developers to place code in weird spots. I for one don’t enjoy when I switch from one project to another learning how they decided to do data access, exception handling, and all the other things that every single good ASP.NET app needs. This should be available for free, or though plugins similar to ruby’s mixins paradigm.

Therein lies my dream. I would love to see Microsoft create a MVC implementation that leverages the ruby language’s metaprogramming features to create a framework that uses XAML as its views and a combination of Active Record and REST for its models (whether in a Microsoft-created implementation that has providers for databases other than SQL Server) but is designed from the ground up for using WPF as a MVC runtime and not simply a clone of rails with a XAML view renderer. This framework needs to leverage ruby in its implementation – not just be another .NET framework you can code against with ruby.

I think Blender is cool for creating HI-FI XAML controls, but these should be databound to data served up by this MVC framework and rendered in the context of a controller action so that the same patterns are used as consistently as possible. I’m sick of the browser’s age old, buggy DOM – and if Silverlight is going to support everything in WPF 3.5 at some point, I would much rather code for this and test it on macs and under moonlight going forward. I would also like to see Microsoft ship an application that hosts Silverlight outside the browser on all platforms.

I know most folks probably won’t agree with me, but I think it’s high time that we get rid of some of the bloat that legacy browsers and class libraries bring when we aren’t even utilizing most of it in modern applications if they are designed well up-front. At some point you have to say that supporting the existing APIs in .NET is the responsibility of the .NET platform, and the DLR and Silverlight are new platforms for development that may have minimal interop, but are designed for a wholly different development model. Those who say this is too big of a goal don’t remember the Sun Microsystems and Microsoft from the 90s, who cranked out innovations in the runtime and user interface space every six months!

Mapping Rails to ASP.NET 3.5

If you’ve done some rails work like I have, and are getting started with looking at ASP.NET MVC for your .NET work; or you are a .NET guy, and looking at rails for the first time, you will want to see which technologies are available to do things in each platform. I hope the following chart is helpful:

Feature Rails Technology ASP.NET 3.5 Technology
Model View Controller architecture Rails Core (Action Controllers, Views) ASP.NET MVC
Domain model from relational database Active Record ADO.NET Entity Framework
REST Active Resource ADO.NET Data Services
Markup language for MVC frameworks HAML NHAML
Build platform Rake MSBuild

IronRuby development is taking off…

Prior to my recent move from Milwaukee to Austin, I helped a friend create a web application with Ruby on Rails on the side from my day job as a .NET architect. After 6 years at the architect level on Java and .NET projects, one of the things that struck me instantly as so beneficial was rails’ standard project directories that linked models, views, and controllers together without any configuration. Documenting and tracking adherence to standards in project structure is always a necessary but many times repetitious task that can make the difference between a really maintainable enterprise class solution, and one that simply meets requirements known upon first implementation.

The ASP.NET MVC project that’s currently being developed by Microsoft is capitalizing on the success of rails in a big way. It takes advantage of .NET in some ways that ruby is not able to, and succeeds in bringing some of the rapidity of the rails platform to ASP.NET without forcing developers familiar with the Visual Studio tools to drop their favorite IDE to join the “all I need is a text editor, man!” camp.

I have to admit that ruby is a great language however, and for all the great new things in C# 3.0, the japanese fellow who created it gave us a really clean syntax and it’s obvious that the folks in Redmond agree. The IronRuby project, created by Jon Lam who recently joined Microsoft last year, is a full-blown implementation of ruby that has as its primary goal the ability to run existing ruby programs. The second goal is to provide first class interoperability with the existing .NET technology stack, without losing the spirit of the interpreted language that ruby is.

Jon and the other folks working on IronRuby have succeeded in this by leveraging Microsoft’s upcoming DLR, a parallel evolution of the CLR that provides a standard interface for creating dynamic language runtimes that target .NET.

What does all this mean? Well with the current bits you can write ruby code to create WPF apps, ASP.NET pages, Silverlight applications, and hopefully at some point ASP.NET MVC apps that can access all the goodness of .NET while at the same time having access to the thousands of open source projects in ruby such as those on rubyforge, where the IronRuby project’s course code is currently hosted.

I’ve been following IronRuby, mostly as an observer, and am seeing development start to really pick up this past month. I made some updates to their project wiki the other day to organize things in anticipation of growth and hope that more folks will soon join in to help make this a really great technology that might help you be more productive on your next .NET solution.