JavaScript Frameworks for Modern Web Dev

JavaScript Frameworks for Modern Web DevI am thrilled to announce the publication of my newest book, JavaScript Frameworks for Modern Web Dev, available now from APress!

A year ago my friend and former co-worker Tim Ambler approached me with a project: a list of strong frameworks and libraries in the JavaScript space that can each be effectively introduced in a single chapter. Over the last twelve months we wrote numerous drafts and revisions, and created a somewhat frightening amount of source code for these sixteen topics:

  1. Bower
  2. Grunt
  3. Yeoman
  4. PM2
  5. RequireJS
  6. Browserify
  7. Knockout
  8. AngularJS
  9. Kraken
  10. Mach
  11. Mongoose
  12. Knex and Bookshelf
  13. Faye
  14. Q
  15. Async.js
  16. Underscore and Lodash

Obviously, the scope of each topic is greater than its chapter, but the book’s goal is to be a quick but thorough introduction to the core concepts in each framework and library. The source code is non-trivial and executable, so a reader can see concepts in action while following along in the text.

Some of the technologies covered have aged (like fine wine!), and some are much younger, but we believe that each has staying power and stands well among its peers. Between us we have used all of these technologies in our own projects and in production deployments, and while we cannot claim complete expertise, we humbly submit that, to the best of our knowledge, the information here is both sound and practical.

We sincerely hope that this book brings much value to you and your team!

 

 

A Book Apart sponsors STL ALT.NET

When I ask my web UI friends what resources they would recommend to a n00b looking to develop his HTML and CSS chops, the near universal answer is to direct me to the wonderful websites A List Apart and its publishing arm, A Book Apart.  For years these websites have been delivering high-quality, non-trivial articles and books on front-end web development and design.  They are universally acknowledged as accurate, if not authoritative, sources of knowledge, and have been a tremendous help to me in my professional career.

A Book Apart has graciously donated one copy of each book in the Complete A Book Apart Library to be raffled during the next several months at STL ALT .NET meetings:

Each volume is a concise and fresh take on an important field in web design. Jeremy Keith’s HTML5 for Web Designers explores what the web’s new lingua franca means for working designer/developers. Dan Cederholm’s CSS3 for Web Designers shows how you can design for the experience layer today. Erin Kissane’s The Elements of Content Strategyexplains where content strategy came from, and how you can do it well. Ethan Marcotte’s Responsive Web Design demonstrates CSS techniques and design principles for crafting fluid, responsive websites. Aarron Walter’s Designing for Emotion will teach you how to you make your users fall in love with your site, while Luke Wroblewski’s Mobile First will make you a master of mobile, and improve your desktop designs, too. 

Mobile First and Responsive Web DesignI personally own digital copies of each book in this series, and I’ve finished three of six.  Of particular interest to me were Ethan Marcotte’s Responsive Web Design and Luke Wroblewski’s Mobile First.  Both of these books take a long look at the current state of mobile web development, and make a compelling argument that not only should developers be aware of the issues and technologies involved with the mobile web, but they should be coding their websites to take advantage of those things right now.  Mobile first design — once onerous in CSS2 and HTML4 — is becoming the standard design approach as mobile phones and tablets saturate the consumer market.  Mobile First makes the technological and business cases for embracing the mobile web, while Responsive Web Design shows how this can be achieved with fluid layouts, flexible images, and CSS3 media queries.

I have nothing but the highest opinion for A Book Apart, and I am excited that STL ALT .NET members will get to experience this awesomicity as well!

Debugging client-side ASP.NET validators

I used this JavaScript snippet to debug an ASP.NET page that was swallowing client-side validation errors (in an UpdatePanel *gag*). I would click a button to submit a form, and nothing would happen — no visual indication of which validators were failing — so I opened the Chrome console and quickly iterated through the validators to locate the offender.

for(var i in Page_Validators) {
  var v = Page_Validators[i];
  if(v.isvalid) {
    continue;
  }
  console.log(v.id);
}

If you want it on one line (easy to paste into Chrome), refer to my github gist.

If you want to read more about ASP.NET client-side validators (I dunno, maybe you have insomnia), check out the official MSDN documentation.

Jessica (.NET Micro Web Frameworks Part 2)

Here is my talk about Jessica, the .NET micro web framework, given at the April 2011 STL ALT.NET meetup.  This is the second in a series of two videos.  The slides and code examples can be found here.

Jessica (Micro Web Frameworks Part 2) from STL ALT.NET on Vimeo.

EDIT: I received some feedback from Tom Bell, the gentleman who maintains the Jessica project; here is my follow-up video.

Jessica Addendum and Clarification from STL ALT.NET on Vimeo.

Nancy (.NET Micro Web Frameworks Part 1)

Here is my talk about Nancy, the .NET micro web framework, given at the April 2011 STL ALT.NET meetup.  This is the first in a series of two videos.  The slides and code examples can be found here.

Nancy (Micro Web Frameworks Part 1) from STL ALT.NET on Vimeo.

EDIT: I received some fantastic feedback from the Nancy team after I posted this video, so I created a mini-presentation with a few clarifications and corrections to my original presentation.

Nancy Clarification and Corrections from STL ALT.NET on Vimeo.

STL ALT.NET April meetup

Open source .NET micro web frameworks

Wednesday, April 27, 2011 at 7:00 PM

Micro web frameworks are very thin, very lean libraries for serving web pages that do away with high ceremony configuration and mountains of code in favor of simple templates and dynamic view models.  The Sinatra micro web framework has become very popular in the Ruby community, and it has inspired open source developers in the .NET ecosystem to follow suit.  We will be talking about two of these frameworks, Jessica and Nancy.

Don’t forget, if you want to be eligible for the following raffle prices you must be a member of the meetup group and you must be present!

  • 1 license of EFProf from Hibernating Rhinos
  • 2 copies of Pro .NET 4 Parallel Programming in C# by Adam Freeman

Also, members who choose to give a 5-10 minute lightning talk on a technical topic of their choice will have their name entered into the raffle a second time.  Please notify me at least two weeks in advance if you plan to give a lightning talk so I can adjust the schedule accordingly.

For location details, visit the meetup page.

Dynamic CSS and the Plan of Attack

I’m working on an ASP.NET website where I need to generate dynamic CSS, mostly for “theming” purposes.  I really don’t like .NET skins or themes — I prefer straight CSS and markup; besides, it needs to be configurable through an administration page and persisted to a database.  Here are the options I’m contemplating:

  1. Allow the client to define CSS styles and generate a flat file based on what is in the database when the web application loads (if no file exists, write one — reference that for every subsequent request).  The downside is that I have to write to the filesystem, which means at least one publicly exposed directory must be writeable by some process.  The upside is that browsers will cache the file, so no subsequent requests are needed.
  2. Allow the client to define CSS styles and write them to the output stream using a specialized instance of IHttpHandler.  The upside is that, well, this appeals to the code monkey in me.  The downside is that I’m not sure if a browser will cache this since it’s not a CSS file per se.  I suppose some experimentation is in order.

If anyone has experience with this, please let me know what solution you settled on.

IE does something better than Firefox, hell freezes over

Like most web developers, I write markup and Javascript that will work on both IE and Firefox, and if I’m particularly ambitious, Chome and Safari.  I’ve been writing a lot of Javascript lately, which has been a good learning experience but frustrating at the same time.  I don’t have the luxury of using jQuery on my current project — I am pretty much restricted to Prototype for legacy reasons.  I was in the throes of reconciling a piece of code that copied values from one set of input fields to another, then accessing the innerHTML property of the target fields’ containing div.  I was doing simple value assignments ($(“textBox1”).value = $(“textBox2”).value), and in IE everything worked like a peach.  Then I tested in Firefox and, to my amazement, the target input fields remained blank, even though FireBug assured me that the values were in fact being copied.  I was certain I was making a mistake somewhere in code, and spent an hour or so meticulously pouring over every line of Javascript, attempting to find the roadblock.  In desperation, I turned to the Google in search of an answer.  What I found surprised me enough that I felt compelled to write this post.

Firefox does not reflect dynamic DOM changes in the innerHTML property of a given DOM element.

This means that if you set the value of a text box to “123”, then call the innerHTML property of the DOM element that contains the text box, the value of the text box according to innerHTML will appear to be whatever it was prior to your alteration.  In practice, when the page posts back to the server, the value will actually be “123” and not what innerHTML reports, but the fact that Firefox ignores the change gives me yet one more gray hair.

To get around this glaring oversight, I had to use the setAttribute() method on the DOM input element:

$(“textBox1”).setAttribute(“value”, $(“textBox2”).value);

This accomplishes both tasks — updating the actual input value and changing the innerHTML property accordingly.

You’ve won this round IE… you’ve won this round.

Ambiguous match really is ambiguous in ASP.NET

I just love days of lost productivity.  You know, the ones where you pine away at some problem, retracing every change you made, every source control update you performed, attempting to track down the offending bug in code.  Days like yesterday, for example.  I was working on a fairly nondescript ASP.NET web page, but every time I would attempt to run it I would get the following error:

Parser Error

Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.
Parser Error Message: Ambiguous match found.

Source File: /Default.aspx Line: 1

The only thing that is typically on Line 1 of any ASP.NET web page is the Page declaration, which specifies the CodeBehind and Inherits properties, so naturally my first thought was that perhaps the class name for the page conflicted with another class in the same namespace.  But this was an erroneous assumption, and after renaming the file several times I decided that was probably not the case.

After a few hours of searching, I realized that I had a button on my page declared something like this:

<asp:Button ID=”cancel” runat=”server” Text=”Cancel” />

and an event on the same page (in CodeBehind) declared like this:

public event EventHandler Cancel;

As it turns out, when ASP.NET parses a page’s controls, it does so in a case insensitive manner, which means that the two “cancel” properties (a button is really a protected property declared in the designer) conflict.

This, of course, is completely contradictory, since the code will actually compile (case matters; there should be no name conflict) and only crashes at runtime.  This reeks of FAIL, especially since the whole point of ASP.NET is to make web pages more “object-like”.

All the more reason to use MVC.

<asp:Button ID=”cancel” runat=”server” Text=”Cancel” />

The cake is not a lie with MVC and JSON

Ever since Google Maps showed us that rich internet applications were not only possible but pretty damn cool, developers have been striving to streamline the process of communicating with web application servers without refreshing the browser.  Initially this was done by writing JavaScript to work directly with the XMLHttpRequest object; but this was tedious and not at all elegant.  Then some smart folk came up with the Prototype JavaScript framework and made everyone’s lives easier by abstracting AJAX functionality, making it easier to work with.  jQuery dazzled developers by simplifying the process even more.  XML began leaving a bad taste in everyone’s mouths, so other smart people figured out that instead of passing tagged markup data back and forth, these JavaScript frameworks could transmit and receive JSON.  Because JSON is the native way to serialize JavaScript objects, and because it is significantly less bloated than XML, it was the natural choice for future rich internet applications.

Now, I have a real passion for simplicity and elegance, so any web application framework that makes AJAX easier to write and maintain is my friend.  Since I’ve been learning ASP.NET MVC, I decided to see how it stood up to the challenge.  Like most everything else in MVC, AJAX/JSON support is cake, not a lie.  A JSON driven AJAX call in MVC consists of:

  1. the page that makes the AJAX call, which sends and/or receives data;
  2. a custom MVC action on a new or existing MVC controller that will handle the AJAX call, do the heavy data lifting, and return a result; and
  3. a custom MVC Route that maps to the controller/action in Global.asax

It’s easiest to start with the controller/action, so here we go.

There are a few things to note here, namely the return type of the Authorize() method (JsonResult instead of ActionResult), and the method called to render the data (Json() instead of View()).  Also, while any pre-defined, strongly typed object could be passed into the Json() method, an anonymous object works marvelously for simple values.  (As an aside, best practice dictates that the user repository be retrieved from an IoC container, but for the purpose of this demonstration and for space considerations, I have hard-coded it here.)  The logic in the action is very simple; we fetch a user based on credentials and return a value indicating if the user exists and if they have proper login access.  Because the action here is a simple method in a controller class, it is also possible to write automated unit tests to make sure that the method behaves as expected under a variety of conditions.

The Route for this controller/action is likewise very simple.

The route does not define any parameters for username or password.  This is because jQuery will append arguments to the route using the normal query string notation.  I suspect, but have not verified, that if a route was specified with parameters such as /{username}/{password}, and a dynamic URL was constructed in JavaScript and no arguments were passed to it, the functionality would be identical.

The actual view contains the most involved code.

The form at the bottom contains two fields, Username and Password, and a simple input button that is used for submission.  The click event of the login button calls jQuery’s built in getJSON() method, which takes the following arguments:

  1. the URL that will be used to submit the AJAX request (the URL defined in the MVC routing table);
  2. an anonymous JavaScript object with properties identical to the method arguments of the action I am calling; and
  3. a callback method that takes the return result of the AJAX request as an argument.  This result will have identical properties to the object we returned in our action method.

Based on the return value from Authorize(), I show a popup dialog indicating whether the user should be allowed to log in.  (Best practices dictate that authorization and authentication be performed by two distinct services, but I have consolidated them here for brevity.)  Because AJAX calls are asynchronous, it is important to remember that the click() event will likely exit before the getJSON() function has completed.  If you add an hourglass or twirling Web 2.0 spiral (probably not the technical name), you will want to display it before getJSON() is called and hide it in the callback function instead of at the end of the click() event to ensure that it is displayed for the duration of the request.

That’s all for now.  I will post more on MVC later, but  I think we can all agree that:

This was a triumph.
I’m making a note here: HUGE SUCCESS.
It’s hard to overstate my satisfaction.

–GlaDOS