Finally found what I have been looking for: JavaScriptMVC

I'm very passionate about the code I write, and with the coming of jQuery I really began to love Javascript. But the Javascript I wrote was more of the procedural kind. I tried to split it up per page or user control but it still felt bad. For pages with a lot of interaction the JavaScript files grew very quickly over a couple hundred LOC. There is the possibility to split these up, but the problem that then arises is that the browser launches a request for each javascript file. And most (older) browsers have a suprising low amount of simultaneous request (I thought it was around 2 or 3, it was certainly below 5). So each file I added to make my application more maintainable resulted in a slower application. Not a good situation to be in.

I was constantly on the lookout for something that could easily minify and merge all my JavaScript files and still keep maintainability while developing. I had read solutions of people who had a build task that did this for them. But that seemed like a pretty vulnerable system. The build script has to create a new file on a certain location and has to change your pages so they include the correct javascript file (the newly generated one). So I lived with the pain.

Until I read about JavaScriptMVC on Ajaxian and decided to check it out. What is JavaScriptMVC?  I'll quote from their site:

JavaScriptMVC is a framework that brings methods to the madness of JavaScript development. It guides you to successfully completed projects by promoting best practices, maintainability, and convention over configuration.

So it uses some conventions and the MVC pattern to give you the ability to manage your JavaScript code. But the biggest thing I like so far is the possibility to run in different modes (development, test and production) and if you run in production all your javascript including your external libraries like jQuery get minified and combined into one javascript file. Yes that's right even if you have a dozen javascript files, after minifying them you'll only have one file called production.js left. The big advantage is that the browser only has to do one request to the server to load all of the javascript. You know what that means, faster loading times!

If you write a lot of JavaScript code, check out JavascriptMVC right now. I'll be writing more details about the framework in the coming weeks as I'm still in the process of learning it.


Book review: jQuery in Action

jQuery-in-Action I started reading this book about 6 months ago. After reading it half way through I stopped and start reading a newly purchased book. The reason that I stopped reading was because I was excited and impatient to start reading the new book, it's a problem I have every time I purchase a new book. After finishing some books I realized that jQuery in Action was still lying around, and because the new project I'm working on depends heavily on jQuery, I decided to pick up the book where I left off and finish it.

If you use jQuery in your day job or you are interested in JavaScript development in general this book is really for you. I read this book after several months of jQuery development experience and still learned a lot about the framework.

The authors of the book recommend reading the appendices first before getting into the real stuff. They are a very good start for people who are not that familiar with JavaScript and get you up to speed on some essentials of the language like the JavaScript Object and how functions and closures work. These concepts are explained in a very clear way.

After the appendices you dive right into the jQuery goodness with the explanation of the pure basics. Selectors are a very important part which is handled in detail. Via events, animations and effects they show the basic utility functions that are built-in in jQuery. Although the whole book is a very interesting read chapter 7 really pops out and shows how you can write your own plugins, which can result in a lot of code reuse when used properly. The book is finished with how to do Ajax calls with jQuery and some of the best jQuery plugins.

I think it's quite clear by now that this book is a good read for all levels: beginner, intermediate and advanced. I've learned a lot about jQuery that made my job a lot easier. And I think that's the reason why we read technical books, broaden your horizon and learn how to use framework and tools more efficient. The authors certainly succeeded with this book.

To close I would like to list my 5 favorites things I learned or learned more about while reading the book:

  • Selectors, although I already knew a bunch about supported selectors I learned some new ones that I didn't know of
  • animate() that enables you to create your own custom animations and gives you endless possibilities
  • $.grep() can be used to filter arrays
  • $.post, $.get, $.ajax, ... all the different features in jQuery that support ajax calls to the server and a reference of all the different options.
  • Live Query plugin, which can monitor if certain events occur on elements which match a certain selector. The good thing about this plugin is when adding new items to the page that match the selector, you don't have to bind the events for this new item. The plugin takes care of that.
Tags from Technorati: ,,

Sequentially download multiple files (with jQuery)

On my previous job, I was working together with a colleague on a file transfer application which lived in the browser. We were up -and downloading multiple files at the same time and needed a rich user experience. To ensure the best experience when uploading we turned to swfupload, it's free and I highly recommend it. But download was another story. The user experience for downloading files is actually something for which we entirely depend on the browser. It's not that there is a lot of choice. You click a link to a file which the browser can't open then you get a save dialog box and the browser shows you a progress bar. All that is out of the hands of the developer you just put the link there or stream the file directly to the client and let the browser do his thing.

But we offered the user multiple files and he could determine which files he wanted to download. This is a simplified mockup of how the screen looked.

image

If a user wanted to download the files he could click the links one by one and then save them. But how to make the "Download selected files" button work. After some googling I found that there are numerous solutions for upload but didn't find any decent solution for a 'richer' download experience. And after thinking it through it makes sense, because downloading requires access to the hard disk of the user. This would be a serious risk to allow javascript to write to a certain folder on disk.

So we were stuck, some suggested of zipping all the zips to one file but we didn't want to burden the end user with the extra effort of unzipping.  I got a hint on a forum post (can't remember which one sorry for that) that if you pointed the source attribute of an iframe to the file the browser would offer it as a download. So the first attempt to to this was with the following HTML code:

<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="j/jquery.js" type="text/javascript"></script> <script src="j/index.js" type="text/javascript"></script> </head> <body> <h1>Download files</h1> <iframe src="" id="download-iframe" style="display:none;" /> </body> </html>

And the following JavaScript was executed when the document was loaded.

$(function() { $('#download-iframe').attr('src', 'file1.zip'); $('#download-iframe').attr('src', 'file2.zip'); $('#download-iframe').attr('src', 'file3.zip'); });

You can see I'm using some jQuery magic. If you haven't used it yet, stop reading and go check it out. Did I already mention I'm a fan?

But there is a problem with the code. Only the last file is offered as download. I guessed, I'm not 100 % sure and please correct me if I'm wrong, that the problem was that the statements were executed directly after each other. So I used a little timeout to see if that was the solution to our problem, like so:

$(function() { var fileIndex = 0; var fileArray = [ 'file1.zip', 'file2.zip', 'file3.zip' ]; $('#download-iframe').attr('src', fileArray[fileIndex]); fileIndex++; var interval = setInterval(function() { if(fileIndex < fileArray.length) { $('#download-iframe').attr('src', fileArray[fileIndex]); fileIndex++; } else { clearInterval(interval); } }, 100); });

As you can see the code is not that much longer, I now have an array of the filenames (could be extracted from a list of checkboxes) and offer the first file as download. Then I set an interval that fires every 100 milliseconds which offers the next file as a download. Once all files have been handled, the interval is cleared and we're done.

Now the user gets prompted with 3 download dialog boxes. I know, it sucks that he still has to click three times to save each download individually. But if the user sets a default download location the files are automatically saved to that location and he doesn't have to click for each file that gets downloaded. It's certainly not perfect and from a user experience standpoint it still kinda sucks ... but it works. If you have another idea of solving this problem, please feel free to elaborate in the comments.

Tags from Technorati: ,,

One tool to test them all: Microsoft Expression Web SuperPreview

A new tool was launched by the Expression Web team at MIX09. Multibrowser testing these days is still a real pain in the ass. But as a web the-one-ring2standards fanatic I want my websites to work cross browser. Unfortunately this implies installing a handful of browsers on your desktop. To top it off you need additional tools to test all versions of Internet Explorer. There is no one tool that you can use to test and debug your website in all browsers.

Enter one tool to test them all: Microsoft Expression Web SuperPreview (a mouthful). It wants to fill the gap in multibrowser testing and looks like a real promising tool. The point of the program is that you have one program which groups all testing. And although the early bèta that is now available only supports Internet Explorer 6 and 7 (or 8 when installed) it is planned to support almost all large browsers in the future.

My installing experience with the product was a bit disappointing. The tool kept crashing on startup. After ranting about it on Twitter I got almost immediate feedback from Justin Harrison, program manager of Expression Web. He pointed me to a blog post with a workaround for the bug I was experiencing. Talk about efficient use of Twitter!

After applying the workaround the tool worked perfectly. You have to be a bit patient because the websites load pretty slow but I'm sure they'll fix this in one of the future releases. After all this is still a beta. One killer feature that immediately catches your attention is the possibility to overlay two websites. Then you can see the real differences between the two browsers

Picture 4

This could grow into a killer tool which would be indispensable for web designers/developers. One thing that would really top it off is if they added real time css editing. It is already possible to select a certain element on the page by clicking on it (Firebug style). In the status bar you then get to see the properties of the clicked element. If you could then start changing the CSS (and even the HTML) and see the changes in real time that would make one hell of a debugging tool. That's also what makes Firebug so powerful.

Conclusion: I like the way Microsoft tries to fill a gap in web development I hope it quickly evolves into stable product. When it does and it supports all common browsers it will become a standard in my tool belt to test my websites cross browser. And is it possible to release a Mac version? That would be great ;-).I know, I know ... wishful thinking.

For more information on Microsoft Expression Web SuperPreview you can check the following links:


Before I sign, can I see your codebase?

Changing employers is always a hard decision to make. Whatever the reason is you found that new opportunity that caught your attention: money, fame, need for a new challenge. There are plenty of jobs in the sea, certainly as a developer, and it's hard to find that one true job. You don't want to end up in a job which has the same drawbacks as your previous gig. If you take the leap you want it to be worthwhile on all areas: financial, job satisfaction, etc. Although the financial aspect is an important part of the decision making it's not the holy grail. For me even more important is job satisfaction. In every job interview they're telling you they have state of the art ASP.Net Turbo 3000 code running on their Windows 2099 machines. But as we all know there is code and there is code.

To be able to make a good decision, the first thing you do is gathering intel. Asking around with friends, former colleague's, friends from friends and so on about the company you're about to sign for. If all those signs are positive and the pay is good (I've been told it should be minimum 10% more then you're current wage), you could ask to meet the team you're going to become a part of. I don't believe in first contact, certainly not at a job interview because everybody is going to be at his best. You will see your future manager for about 2 to 3 hours and he will be looking for people so he will show his most charming side. Your future team mates don't know you so they'll act like the nicest people you've ever worked with because they don't know you. If you sign the contract you're going to spend more than 8 hours per day with these people, only then you will really get to know them. Worst case scenario if the first encounter with the team was a bad one, I would be reluctant to sign. But this is hardly ever the case.

So on what grounds should your decision be based? I've never done this before but I was discussing this topic with some people and it suddenly struck me. They can offer you double the wage you are earning today but if you have to work your way through the next big ball of mud you're nog going to have a lot of fun at your new job. Unless you're looking for a real challenge. But how do you make a distinction between a challenge and professional suicide? The best way to get to know how a company works and what the quality of the codebase is: ask if you can quickly see some codefiles and if they could shortly draw how their application is architected. You'll get a crash course in how the company works and which of the statements the recruiter or manager made about the software methodology they're currently following are really true. It will be enlightning because you'll not be jumping into an abyss, you'll have a better understanding of the risk you are taking. Of course there is always risk involved but calculated risk is in my opinion a part of an exciting life!

Employers can also learn something from this: If you have a neat codebase or some really cool continuous integration system show it to your future employees. It's certainly an extra plus when trying to convince someone to sign for your company.

Tags from Technorati: ,,

Why learning CSS is important in a (web) development world

I notice that a lot of development effort is going into creating a nice back end. Creating a GUI is a matter of using the designer - better known as system.draggy-droppy - and setting the right colors via the properties panel. But lately a shift has happened which forces developers to learn about CSS.

Web development

If you're into web development and I know more and more developers are into it you must learn CSS. It's part of the web and part of web development. It will make your applications slicker and nicer looking. You can make some very slick feedback messages with CSS. And everyone knows you can create an application with an almost perfect architecture, if it looks like hell you'll need ten times the effort to convince users to use it.

JQuery

With the popularity of jQuery, the adoption by Microsoft certainly helped, a lot of developers are starting to learn the pure basics of web development. People are starting to learn the (fantastic) language that JavaScript is. JQuery introduced us to another phenomenon: CSS selectors. You can use CSS selectors to select a certain element on the page. Where CSS used to be for layout only, it is now being used to code. Most developers don't care about layout. If the code works, they are happy. So most developers didn't care about CSS, until now.

Fizzler .Net

I recently read about Fizzler .Net, a tool which brings CSS selectors to C#. I think this is an excellent idea, using CSS selectors is very intuitive once you get used to it. I even read about using CSS selectors on plain XML files to select elements. That's even a better idea! We certainly haven't seen the last of CSS selectors in server side languages (like C#).

The problem(s)

I see 2 main problems. The first problem is browser compatibility. It takes a lot of effort to get certain CSS code to work in all browsers. Specially Internet Explorer 6 can be a real pain in the ass. A lot of developers lose courage when handling yet another problem of: "It works on Firefox but doesn't on IE6". The only solution to this is ... deal with it. Learn the Internet Explorer 6 bugs, try stuff out and get to know the solutions/workarounds. A lot of bugs have been dealt with before and after creating a few layouts with XHTML & CSS you are able to solve most of your problems.

The second problem is Visual Studio. It really lacks a tool to do good CSS coding. Sure it has intellisense but that's really it. There is a real market for a tool which support the developer who writes CSS in Visual Studio. A Resharper like tool which gives you hints like #ffffff can be abbreviated to #fff. That would really rock my world. I was hoping that Aggiornio was going to step up the plate but it hasn't so far. Another thing that should be added is cross browser testing. You should at least be able to test the different versions of Internet Explorer. Now you have to use tools like IETester and install Firefox, Chrome and Opera on the side to have a decent coverage. CSS Vista is worth checking out for this but Visual Studio is an IDE and CSS is part of the development cycle. The functionality that CSS Vista has should be incorporated into Visual Studio.

Conclusion

What are you waiting for? Good, practical books to get you started are those of Eric Meyer and the Zen of CSS design. You can find a lot of other books on my Shelfari profile, do you have an account yet? If not check it out, you can become virtual friends and it's a great way to learn about new books!

Tags from Technorati: ,,

Posting code on your blog

If you have a technical blog it's very important that you can somehow easily post code snippets to your blog. I was using the Visual Studio plugin Copy source as HTML for a while but I wasn't very enthusiastic about the result. I don't like the fact that I need a plugin in Visual Studio to be able to post code to my blog. Visual Studio is for programming. Jan told me that there was a Windows Live Writer plugin as well to do this. A few days ago I found the best plugin ever. It allows you to paste code into an intermediate window and then formats it for you!

Because I recently converted to the dark side, I didn't want my code snippets all to have a black background. But this problem is solved by the plugin without any configuration (As you can see below).

Picture 5

Screenshot from Visual Studio.

namespace TwotoContentTests.FilterAttributes { class Class1 { } }

Code pasted via the Windows Live Writer plugin.

What are you waiting for? Go download it!


Testing the OnActionExecuting event of a Controller

I was doing a bit of refactoring on an ASP.NET MVC web application and was using the OnActionExecuting event in a controller to do authentication. I had not yet written a test for it, blasphemy I know, so that had to be corrected. The controller was  something like this:

using System.Web.Mvc; namespace TwotoContent.Controllers { public class ExampleController : Controller { protected override void OnActionExecuting(ActionExecutingContext filterContext) { // check if user is authenticated before executing an action and redirect if not } public ActionResult Action() { return View(); } public ActionResult AnotherAction() { return View(); } } }

At first I did a stupid attempt thinking that if I would call a Controller action from the test, the OnActionExecuting would be automatically executed and tested. I quickly find out that's not the case and after thinking it through it would probably suck if it worked like that because you would have to write the same setup code over and over again for every action for which the OnActionExecuting was called. But there must be the another way to call the OnActionExecuting function directly without having to execute an Action.

naamloos

No luck, as you can see you can't separately call the OnActionExecuting event on a controller because it's protected in the Controller base class. I didn't really know what to do so I googled around a bit and found this article about creating your own action filter. It seems that the OnActionExecuting event is public when you create your own custom ActionFilter. What is an ActionFilter you ask? Let me quote from the article: "An action filter consists of logic that runs directly before or directly after an action method runs. You can use action filters for logging, authentication, output caching, or other uses." Exactly what I needed in other words. So after refactoring a bit I came up with the following code:

using System.Web.Mvc; namespace TwotoContent.Controllers { public class ExampleController : Controller { [ExampleActionFilter] public ActionResult Action() { return View(); } [ExampleActionFilter] public ActionResult AnotherAction() { return View(); } } public class ExampleActionFilterAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { // check if user is authenticated before executing an action } } }

Now the OnActionExecuting method in the ActionFilter attribute can now be tested as followed:

using System; using System.Collections.Generic; using System.Web; using System.Web.Mvc; using System.Web.Routing; using NUnit.Framework; using Rhino.Mocks; using TwotoContent.Controllers; namespace TwotoContentTests.FilterAttributes { public class When_executing_an_event { private ActionExecutingContext _context; private ExampleController _controller; [SetUp] public void SetUp() { _controller = new ExampleController(); _context = new ActionExecutingContext(new ControllerContext(MockRepository.GenerateMock<HttpContextBase>(), new RouteData(), _controller), new Dictionary<string, object>()); } [Test] public void Then_the_authenticated_indicator_must_be_set() { var subjectUnderTest = new ExampleActionFilterAttribute(); subjectUnderTest.OnActionExecuting(_context); var authenticatedIndicator = Convert.ToBoolean(_context.Controller.ViewData["authenticated"]); Assert.That(authenticatedIndicator == true); } } }

I first set up an ActionExecutingContext with a controller so it can be passed to the OnActionExecuting function. In the test I create an instance of the class that is under test, in this case the ExampleActionFilterAttribute class. As you can see the OnActionExecuting function can be called directly (because it's public in the base class). After executing the function I read a variable from the ViewData collection via the context that was set up earlier. Finally I test if the variable in the ViewData is filled out correctly. You actually need quite some setup code to be able to mock an ActionExecutingContext. Because I didn't need the HttpContextBase I have just injected a mock. This minimalizes the amount of Setup code that is needed.

I can't really think of a reason why the OnActionExecuting event is protected on the base Controller class and is public on the ActionFilter class. A benefit of this approach is that it results in a smaller controller class and an ActionFilter we can reuse over various controller classes. So nothing but advantages! Maybe this isn't the best solution but it worked for me. Ideas/additions/rants are always welcome.


VMWare Fusion vs Parallels

I have been using a Mac as my main development machine for over a year now. I have been very happy with it, you could call me an Apple fanboy. Because I develop in the .Net framework, and I'm not planning on changing that, I had to find a solution to be able to run Windows on my Mac. There are two options to get that done:

  • Installing Bootcamp: this implies that you have to reboot your machine to get to Windows
  • Virtualization: running Windows as a virtual machine on top of Mac OS X

The first reason I changed to Mac was the slick design but after using it intensively I came to realize that that isn't the strong point of a Mac. The strong point of the Mac is OS X. It's a robust operating system that doesn't get in your way. I was so pleased with OS X that I wanted to use my Mac for all general computer use (surfing, email, ...) and just use Windows as a shell for Visual Studio. So Bootcamp was no option for me.

parallels-logo The first choice was made, I wanted to work with Virtual Machines to run Windows on my Mac. There are two virtualization solutions on Mac, VMWare Fusion and Parallels. Because a good friend of mine, who has an excellent video production company by the way, recommended me Parallels I went for that solution and never looked back ... until a few days ago.

I was trying to set up a new Parallels Virtual Machine and was installing Windows XP. After 5 tries I had given up. Windows (in Parallels) kept throwing blue screens at me. In the past I had never had this problem. So out of frustration I decided to try VMWare Fusion. I installed it and created my first VMWare Virtual Machine. The first killer feature I noticed is that the desktop and documents is shared between your virtual machine and Mac OS X. It is very easy to copy files between the two.

The perfect situation for me is that I have one Virtual Machine, which I can copy if I want to test something like an early bèta and then delete it when I'm done. In this way I don't have to install vmware-fusion-logoapplication after application that I don't use in my Virtual Machine and I can keep my Windows clean. A VMWare virtual machine is only one file, you can copy it and when you boot it VMWare Fusion detects that the VM is copied. A Parallels Virtual Machine exists of several files and is less easier to copy. Another point scored by VMWare Fusion.

While doing some research on the two products, I noticed that Parallels is popular with designers and VMWare Fusion is more used by programmers. The fact that Parallels is so popular is in my opinion because of the design of the product. Starting a virtual machine is very slick, you've got rotating windows and stuff like that which makes it a great experience. Developers who use VMWare Fusion are mostly coming from Windows, on which VMWare is already very popular. On top of that, I have the feeling that VMWare Fusion is a little more robust then Parallels. A .Net developer tends to use his virtual machines a bit more thoroughly then a designer who most of the time just uses them to do some cross platform testing. I think that explains why designer prefers Parallels and developers prefer VMWare Fusion.

So I've made the switch VMWare Fusion and I'm very happy with it at the moment. Are there any .Net developers on Mac among my readers? Which virtualization platform do you guys use?

There is one thing that almost made me throw VMWare Fusion out of the window. The next screenshot explains it all:

Picture 1

Notice the Install McAfee menu item, I hope VMWare got a lot of money out of it because I really hate it when stuff like this get incorporated into a good product.

Note: I haven't tested Parallels 4 yet, I wrote this post before it came out.


Austin and Kaizenconf Part 2

Using and abusing ASP.NET MVC for fun and profit

Being a huge fan of ASP.NET MVC, I couldn't miss the opportunity to see guys that are much smarter than I am show off how they use the MVC framework. Jeremy and Chad showed real code of how they had been using the ASP.NET MVC framework in their projects.

Because this is a brand new framework, I have these moments when I'm using it that it doesn't feel quite right. I feel that the way I'm coding something isn't the best way to do it, but I don't know how to get around it. While sitting in the session I had a lot of aha-moments, I saw how other people tackled problems that I couldn't wrap my head around until now.

These are some key points that from now on I will try to keep in mind while using the ASP.NET MVC framework:

  • Keep your views light, your controllers medium and your model heavy
  • HttpContext is your enemy, controllers should not come in direct contact with the HttpContext even now it's mockable
  • Get rid of magic strings (for example hashtable examples like ViewData)
  • Thunderome principle
  • No if's or foreach's in the view, use extension methods, htmlhelpers and partial views to get rid of logic in your view

Another thing I couldn't wrap my head around before seeing this session was unit testing javascript with QUnit. I did write some tests with it but again bumped into some road blocks. It was great to see that other people used it with success. I'll probably be writing a blog post about this in the future, as I'm planning on taking the quality of my javascript code to the next level.

Last but not least was a demo that Jeremy gave of StoryTeller, it was a short demo but it looked very promising. I highly recommend viewing the session, you can find the video's at the KaizenConf wiki.

Presentation Patterns

This time Jeremy paired up with Glenn Block to tell us more about presentation patterns. They talked about several presentation patterns including passive view, supervising controller and view-viewmodel-model. The thing I realized is that I'm not using presentation patterns enough in my day to day job and that I should start using them where I can as soon as possible.

Open space

After the fantastic sessions it was time to kick off the open space. This was my first open space and I didn't really know what to expect. Doc List coordinated it all and it was a great learning experience. We started with a fishbowl, after which everyone participating could propose subjects. After that everyone voted and the topics that he or she was interested in. The schedule was formed.

An open space leans on four principles:

  • Whoever comes is the right people
  • Whatever happens is the only thing that could have
  • Whenever it starts is the right time
  • When it's over it's over

I followed a lot of sessions and have a lot of loose notes. I had a really good feeling with the concept of open space. The sessions are more debates and the participants discuss the things they want to talk about, not only what the speaker wants to show. Because almost everyone is participating you learn a lot from each other.

Conclusion

This was by far the best conference I've ever been to. I've learned so many things in such a short period of time. I would like to thank everyone who we met in Austin specially Conrad and Michael for letting us tag along and of course Scott for organizing the whole thing. If you are interested, there as a LOT of material produced you can find it on the KaizenConf wiki.