Starting a project with Express, node.js and Stylus
Node.js gets a lot of attention lately, out of curiosity I decided to try it out. After reading the excellent hands-on node e-book I wanted to port one of my pet projects, a price comparer between different IKEA branches, written in ASP.Net MVC to node.js. As a web framework I went for Express. In this blog post I’ll show you how you can get Express to generate a very basic app for you and how you can use Stylus in combination with Express.
First of all make sure that node and the node package manager are installed on your system, it can be downloaded from the node.js website. Once that is done, you can let Express generate a basic application structure for you. You don’t have to use that folder structure but it gives you a nice head start. It’s ridiculously easy, open terminal and browse to the folder where you want to put your new project and type the following command:
1: $ express
Express has generated a few files and folders for you. But before you can run your newly generated web application you have to install the dependencies that express uses. You can use the node package manager (NPM) for that. Just use the following command:
1: $ npm install
If all went well, you can now access your application by pointing your browser to http://localhost:3000. Don’t forget to start the app before surfing with the command:
1: $ node app.js
Now that we have a very basic application up and running it’s time to make our web pages pretty. Because plain CSS is so 2004, I was looking for something like LESS or SASS. I stumbled on Stylus, it’s an expressive CSS language that is specifically built for node. Its syntax is similar to the Jade templating engine’s syntax. Installing it is easy with NPM:
1: $ npm install stylus
Stylus provides you with Connect middleware that you can use in Express to configure stylus. In the following code snippet you can see the middleware in action, you should add lines 8 to 12 to your app.js:
1: app.configure(function(){
2: app.set('views', __dirname + '/views');
3: app.set('view engine', 'jade');
4: app.use(express.bodyParser());
5: app.use(express.methodOverride());
6: app.use(app.router);
7:
8: app.use(stylus.middleware(
9: {
10: src: __dirname + '/views',
11: dest: __dirname + '/public'
12: }));
13:
14: app.use(express.static(__dirname + '/public'));
15: });
If you take a closer look to the added lines, you see we give the stylus middleware a source and destination directory where to find the necessary files. Don’t forget to require stylus in your app.js like this:
1: var stylus = require('stylus');
The middleware will search for *.styl files in the source (src) directory and compile them to *.css in the destination (dest) directory. Look out! At first I wanted to be fancy and place my stylus files in neatly organized folders, you can do that as long as the folder is a subfolder of the src property that you set in your configuration. For example if you put your *.styl files in a stylesheets subfolder under views, your source directory is still __dirname + ‘/views’, __dirname + ‘/views/stylesheets’ will not work!
Now we add a *.styl file in the source folder (or a subfolder of the source folder) and add a link element to the compiled *.css file in our main layout.jade file. The template file looks like this:
1: !!!
2: html
3: head
4: title= title
5: link(rel='stylesheet', href='/stylesheets/style.css')
6: body!= body
If all went well, rerun the application via the node command and point your browser at http://localhost:3000. The css file will be compiled automatically by stylus and applied to the web page by the browser. You can now start building your app!
All code of this example can be found in a repository in my Github account.
‘Till next time.
Using an anonymous object as the model for your Spark view
Well another post about Spark, I’ve been spending a couple of hours with the library and I really like it. On one of my previous posts Byron Sommardahl asked if it was possible to use an anonymous object as the model of your Spark view. I proposed a solution but I didn’t really have an idea if it actually worked. Because I was curious if it would work I fired up Visual Studio.
A little warning before we dive in, my gut feeling says that the code could be prettier but it does work. Some reflection is used to get the job done.
As a base of my solution I started out with the code I’ve written in my previous post on how to generate html with Spark. I recommending rereading it before continuing. This is my new, more generic Spark view which will be used to generate HTML:
Where in the previous post we had a data transfer object with a specific type which had all the necessary data, now the Data property is of the object type. There is a second property which will hold a reference to our Anonymous type.
The Data object with which we will be working is this:
A simple Anonymous object with 4 properties will be our DataTransferObject (DTO). We will initialize our AnonymousSparkView with the following data:
Our DTO is filled out into the Data object. The type of the anonymous DTO is filled out in the AnonymousType property. Now is the time to fill out the necessary data in our template. This is the template:
This little snippet uses a bit of Reflection magic to read the properties from our anonymous object. Between the ${ } token in Spark you can put a property from your view or you can put in a c# expression. We get the AnonymousType property of our view and get a specific property of our DTO, which is an anonymous object, via the GetProperty function. Then we can get the value of a specific property by calling GetValue on the found property.
It’s not pretty but it does work. I tried out a couple of methods that didn’t use Reflection but none of them worked. I am planning of putting all future code on my GitHub account. You can find the repository here and fork it if you want. Any comments or alternative solutions are welcome, as always.
Spark HTML generation fails: View source file not found
I use Spark as engine to generate all sorts of HTML but on Monday last week that specific code snippet failed without being changed. Spark indicated that it could not find the view file, so I checked and double checked that the view was in the correct place. This was as it should be, but still Spark threw the exception that it could not find the view source file. I decided to try the same code on my laptop and there Spark still worked as it should, so the issue was related to my development machine configuration.

When I further investigated the odd exception that was thrown, I saw that the inner exception was an AspNetHostingPermission exception.
So I checked all the rights on the folders where the view files resided and found nothing out of the ordinary. I really couldn’t find anything that could’ve broken the HTML generating. So it was back to the drawing board, in my case Google, to search for possible causes and solutions. After a lot of searching and not finding very much answers I stumbled onto the following post. The error in that post was the same error that I got, but I was obviously not working with Windows 7 RC.
As solution the author states that you have to enable the ‘Load User Profile’ property of the application pool under which your web application runs. You can find the property in the advanced settings dialog of the application pool. Because being a bit really desperate I tried out the given solution and although I was rather sceptic to my surprise it worked.

I have no idea how that property got switched off in IIS, but if you ever have the same problem you’ll hopefully won’t look for a solution as long as I did. You’ve got the solution right here! ‘Till next time.
Using spark as a html/text rendering engine
I can’t remember a project which I worked on that didn’t have a requirement which included sending out emails. Most of the time the templates that are needed for these emails are so small that a simple text file with some wildcards does the trick. It does the trick but nothing more. It’s hardly an elegant solution and there is no support to loop through elements or do any other complicated stuff. I wanted a better, broader solution so I started to look around for usable libraries. I have been hearing a lot of good things of the Spark View Engine and wondered if it was possible to use it to generate html from a given template.
Most articles I found were about using Spark with ASP.Net MVC, only one talked about using Spark as a general purpose template engine by Louis DeJardin. Although dating from 2008 it is still very relevant. The article uses an in-memory template so I changed it that it reads its templates from a folder on the file system. This is certainly no rocket science and most of the code is based on the code of Louis but here goes:
First thing to do is create a Spark template, we’ll be using this very simple example:
<div> <strong>${name}</strong> <span class="address">${address}</span> </div>
Now we need to create a corresponding abstract view with the properties that will be mapped to the template:
public abstract class ASimpleView : AbstractSparkView { public string name { get; set; } public string address { get; set; } }
There are 2 things you need to remember when creating a view code file. The view must inherit from the AbstractSparkView class and the names of the properties in the view have to be the same as the names in the template file. So, obviously, the property ‘name’ in the view maps to ${name} in the template file.
And at last we glue it all together:
var settings = new SparkSettings().SetPageBaseType(typeof(ASimpleView)); var templates = new Spark.FileSystem.FileSystemViewFolder(HttpContext.Current.Server.MapPath("~/Templates")); var engine = new SparkViewEngine(settings) { ViewFolder = templates }; var descriptor = new SparkViewDescriptor(); descriptor.AddTemplate("simple_template.sprk.htm"); var view = (ASimpleView)engine.CreateInstance(descriptor); view.name = "Name"; view.address = "Address"; var stringWriter = new StringWriter(); view.RenderView(stringWriter); var html = stringWriter.ToString();
Let’s go briefly through this snippet. We first create a SparkSettings object on which the basetype is set to our view. We load the templates via the filesystem, in this example the templates are located in the /Templates folder. Then we instantiate the spark view engine and a descriptor for our specific template. As you can see, after creating an instance of our specific template, the properties defined in the template are strongly typed and we can fill them out with the correct data. Finally we render the view into a StringWriter, getting the html from the StringWriter is as easy as calling the ToString method.
With this solution we can leverage Spark in our templates. I think this is a pretty elegant solution. Any opinions on this matter? What do you use to generate html in your projects?
A Kindle DX or an iPad?
I love reading technical books, more than blog posts. They give you a better and deep insight in the matter you’re reading about. The big problem is that, at best, these books are relevant for a few years and then can be thrown out. In January of this year Amazon released the Kindle DX with global wireless. Since then I’ve been looking out for the eReader that would best fit my needs. Based on the review by Scott Hanselman and some other internet resources I had set myself to let Amazon fly over my very own Kindle DX to Belgium.
It was about the same time that there was a lot of buzz around the iPad that Apple has released in April of this year. I had already set my mind to buying the Kindle DX and I didn’t have enough patience to wait until the release of the new Apple wunderkind. I had a 3 week holiday planned to Bali in May and that was the perfect opportunity to stress test the device.
The first thing that I absolutely love about the Kindle is the battery life. I used the device a lot during travel, on the plane, on the beach, … and not once did it run out of juice. For me this is a deal breaker, you don’t want to be stuck on a flight of 14 hours and have your eReader run out of batteries after 2 hours. Then you’ll have to watch a movie with Chinese subtitles on those crappy entertainment systems they provide. The second thing that was absolutely great was the screen. Not once did my eyes feel tired or sore from staring at it for a long time. And I read 1000+ pages on the device in a few days. In my opinion there is no LCD screen that can match an eInk screen. Although it’s only black and white and the response is a bit rough, I am a real fan of the screen.
Once in Bali I was afraid that it would be fragile to take the device to the beach, with sand crawling in places you don’t want it. But again I was reassured, it is robust enough to take it to delicate places. You do have to buy a case for it, otherwise it’ll get dirty pretty fast. I’m not the most neat guy and I spilled sunscreen, an exotic cocktail and who knows what else on my Kindle case. The case earned its cost back by protecting my precious Kindle perfectly. Although it’s a bit stained right now but that’s what a case is for right?
And now to my disappointments. My girlfriend had bought a book in KL Airport that she said was very good. I wanted to buy it on my Kindle, because that is a strong selling point of the global wireless, but it didn’t work in Malaysia. It also didn’t work in Indonesia. I could connect to the Kindle store, but every time I wanted to buy a book I got “This book is not available in this country”. Once I was back in Europe, I could surf the Amazon Kindle Store and buy books. If they sell it as global wireless, I want global wireless. Indonesia and certainly Malaysia are not the end of the world. Their internet usage is almost up to par with the European and American so I would have expected the global wireless to work there.
While using it I couldn’t stop thinking how cool it would be being able to read my RSS feeds. I have to admit, I see the Reeder application on iPad and I’m jealous. This is for me the biggest drawback of the device. You can’t install any additional applications on it. I don’t want to play airhockey on the thing but if I have a dedicated mobile reading device it would be nice to download my feeds to it and read them while being offline. In the experimental option there are some new features like playing MP3s and surfing the web. But I haven’t been in a country where I can actually surf the web. Although exciting features in theory, they’re disappointing in reality.
Conclusion? I get a lot of people asking me, what should I buy? iPad? Kindle? Kindle DX? Well, if I had to choose again I’d probably get an iPad. I love the eInk screen on the Kindle and think it’s a must if you read a lot on your device. But installing applications is a real deal breaker for me. The possibilities are endless with an iPad, not so with a Kindle. I haven’t tried myself reading hours and hours on an iPad. But I’ve heard from different persons that it’s a really good screen and isn’t tiring on the eyes. But still I’m pretty happy with my Kindle.
How about you, do love your iPad? Or your Kindle? Show it in the comments.
Book review: Getting Real by 37 Signals
If you’re sick of reading book reviews, I’ll give you the short version. If you are a project manager, designer, developer, entrepreneur or business analyst who is involved in creating a (web) application read this book. It’s awesome.
Now for the longer review: although the guys from 37 Signals just published Rework, I still had to read their previous one called Getting Real. They describe their process of creating popular applications like Basecamp, Campfire and many others. I got great value out of it even though I’m currently not developing my own products. It has great advice on subjects like how to deal with clients and users.
For example, scope creep is something everyone involved in a project should really look out for. A web application is never finished and clients will hold the release until the perfect product has been created. Instead they state that you should get your application out into the world as fast as possible. You will instantly see what works and what doesn’t. And no unnecessary features will be introduced just because the client thinks it will be a big hit. This is based on the “Release early, Release often” idea and that’s also what I try to do at Two to Tango when developing software projects. On top of that the book advices not to fix every bug, especially layout bugs. Don’t worry about that button that is 2 pixels out of place in Internet Explorer 6. Just release your application and let the magic happen.
About users they say the following: don’t listen to your users. Don’t implement every little feature that they request. Instead have a clear vision about where you want to go with the product and stick to it. If you listen too much to your users, you’ll get an application that serves it all. I see it as an application without a spine. They advice to build an application for yourself not for your users.
I just described two points that I took away from he book but it is filled with beauties like this. So just go read it now, you won’t regret it! You can even read it for free online. And read Rework also while you’re at it, I’m pretty sure it’ll be worth it.
Permission to access webcam not asked by Silverlight 4 beta on load of page
I was playing around with the Silverlight 4 beta and was trying to get my webcam working by following this article. Although the code to achieve this is very simple, the webcam did not work in my *.aspx page which contains my Silverlight component. I googled and stackoverflowed around but didn’t find anyone with the same problem as I had. When the page loaded, I just saw an empty rectangle and Silverlight did not ask for permission to access my webcam like it should.
This is how the component looked in Firefox and this was the code, it’s the same as in the article:
Then I realized that all examples I saw on the web used a button before enabling the webcam. So I changed my component a little: added a ‘Turn on camera’ button and copied the code to start the camera to the click event of the button. If I now clicked the button, Silverlight asked for permission to use the webcam.
So the resulting code looked like:
And I was a happy coder, because I could now see myself in the webcam.
I documented this for everyone who might have the same problem. I don’t know if this is a known bug or not I didn’t find any documentation or ticket about it.
An alternative to editing JavaScript in Visual Studio: RubyMine
Unfortunately the images to this post were lost during the migration from Blogengine.Net to WordPress
A while ago Chris Missal asked the following question on Twitter.
One of the projects I am currently working on is a JavaScript intense web application. That’s why the question instantly caught my attention, JavaScript editing in Visual Studio has been bugging me for a long time. In one of my previous posts about Visual Studio somebody said in the comments that VS isn’t build with web developers in mind. Well, that’s the least you can say. But still, since my business is mainly focusing on .Net web development I’m obligated to use Visual Studio for all my ASP.Net Webforms and MVC projects. And for all the JavaScript, (LESS)CSS, ASPX, HTML editing that comes with those projects. If you don’t know it yet, Visual Studio is really bad at all those things. In those cases the editor is comparable to a colored version of Notepad.
Some of the replies to Chris’ question suggested Notepad++ others suggested RubyMine. RubyMine from JetBrains, the same company that created Resharper, is a tool I always wanted to try out and I thought this was the perfect opportunity. So I downloaded the whole thing, there is a trial available, installed it and pulled my Scripts folder into the editor. I didn’t have very high hopes, because I use JavaScriptMVC and jQuery on this project and I thought it would be very hard for the IDE to figure out all the different references and relations between the files and classes. To my surprise the IDE succeeded in parsing the different JavaScript files. So we were all set, time to try some stuff out:
I created this simple class, using the functionality JavaScriptMVC provides for creating classes:
First thing to try out that comes to mind, let’s declare a variable that is not used and see what RubyMine says about it:
Very nice, this thing is already doing more than Visual Studio does. It detects unused variables.
Time to try some more complicated like things renaming a variable which is not possible in Visual Studio. So I tried right clicking on the variable and there is a nice Refactor item in the context menu. A very Resharper-like experience, I haven’t tried out all of them but the basic things like Extract Method, Rename and Introduce Variable worked very well.
All this is really impressive, and there is more! I have multiple classes in this project and RubyMine detects them and provides Intellisense. Even though I use a framework to declare my classes, it still detects which are classes and what functions are defined on my class. Pretty nice huh? On top of that, all R# shortcuts that you are used to also work in RubyMine. Ctrl+N to find a given file, even Ctrl+12 to list and find a method of the open class:
Although I only scratched the surface of RubyMine, navigating, editing and refactoring JavaScript has been a great experience. Certainly when you’re used to using Visual Studio for that. I can already conclude that it beats Visual Studio in every aspect when it comes to writing JavaScript. It’s a shame that we have a feature-rich tool like Visual Studio and still need to open a second IDE to edit JavaScript files. I can only hope that Visual Studio 2010 brings some more options to the table. Maybe JetBrains should think about adding an ASPX editor and a C# compiler to RubyMine, call it SharpMine and sell it. That would definitely be something I would consider buying.
Not another NDepend review, link roundup
I had the chance to try out NDepend, thanks to Patrick. After playing around with it I was pretty impressed and started writing a review of it. Out of curiosity I googled around a bit and found that there are already a lot of good reviews about it. I didn’t want to do just another review so instead I was thinking of creating a round up of all the blog posts out there that give more information about one or more features of the product. And which I used to get up to speed.
I don’t think the tool still needs an introduction. But for the .Net developers who have been programming on Mars in these last years. Here is a short intro: NDepend is a static code analysis tool. It collects information about your code base and gives you the opportunity to view it, query it, analyze it and so much more. Actually it is packed with features to help you in better understanding your codebase and its problems. It even has integration with Reflector and Visual Studio.
So here goes:
Getting started
Introduction video’s on the NDepend website
The NDepend website has some really good video’s on how to get started. If you want to start anywhere, start here.
Hanselminutes episode on NDepend
This podcast episode is ancient in Internet age (from 2007), but it does provide some interesting information.
Interview on DotNetCurry with Patrick Smacchia, the creator of NDepend
Patrick talks about he basics of NDepend: what it does, when and how to use it
Introduction by Andre Loker
Simplify code using NDepend
Introduction by Gil Fink
NDepend for Instructors
This article gives the tip for instructors to use NDepend to check on code written by students. I think that’s an excellent idea!
Getting up-to-speed on NDepend and Code Metrics on InfoQ
Talking .Net Code Analysis with Patrick Smacchia
NDepend and complex methods
Using CQL queries to pinpoint complex methods in your code base
Day-to-day working
Analyzing the code base of CruiseControl.Net
Patrick analyzes the CruiseControl.Net codebase with NDepend
NDepend analysis inputs
Using NDepend on large project, a success story
Working on F# with NDepend by Steve Gilham
Using NDepend to help guide refactoring
Steve Wright wrote a great article how to use NDepend to make your code more understandable and manageable. Although written in 2008, it still is applicable today.
Static Analysis and generated code
Skip generated types when performing analysis in NDepend
Remove assemblies from Dependency Graph in NDepend
Lessons learned from the NUnit code base
NDepending Resharper
CQL (Code Query Language)
Beginning CQL
Getting started with CQL post by Stuart Thompson
Code Query Language Specification
Active conventions with NDepend part 1 and part 2
Jan uses CQL and NDepend to enforce BDD naming convention in his unit tests.
Fun with NDepend
Integration
Video on adding NDepend to your Nant script on Dimecasts.net
NDepend task for Nant
NDepend and CruiseControl.Net
Integrating NDepend code metrics into an NAnt / CruiseControl.Net Build
Extra
Influence the future of NDepend
If you’re missing a feature, this is for you. Patrick calls out the community to propose missing features for NDepend.
XDepend, NDepend for Java
CppDepend, NDepend for C++
Reviews
There are a lot of reviews out there, there is not one negative review and they all have some interesting information about NDepend. Worth checking out! Here they are (in some kind of alphabetical order).
By Manuel Abadia
By Vagif Abilov
By Gojko Adzic
By Donald Belcham
By Nick Berardi
by Steve Bohlen
By Laila Bougria
By Chris Brandsma on Elegant Code
by David Brown
By Jeff Brown
By Herbert Joey Calisay
By Henry Cordes
By Ben Griswold
By Scott Hanselman
By Brian Hartsock
By Travis Illig
by Philip Japiske
By Brendan Kowitz
By David Lambert
By Anatoly Lubarsky
By Hendry Luk
By Elijah Manor
By David Mohundro
By Muhammad Mosa
By Diego Muñoz
By Keyvan Nayyeri on DotNetSlackers
By Benjamin Nietschke
by Grant Palin
By Jan Van Ryswyck
By Steven
By Craig Stuntz
By Steve Trefethen
By Ben Watson
By Davide Zordan
By Arjan Zuidhof
Closing
If you still need some reading material, I suggest you follow Patrick Smacchia’s blog. He’s the creator NDepend and frequently blogs about the subject of static code analysis. If you have an interesting link about NDepend to add you can always leave a comment and I’ll add it to the list.
Continuous education, Hanselminutes show #187
It has been quiet on this blog lately but I’ve been very busy with work. Between my busy schedule I’ve been trying to keep up on the technology front by listening to different podcasts. Although the quality of a lot of podcasts is highly dependant on the guest that is starring in that week’s episode, Scott Hanselman has been able to keep me interested all the time. Even for topics in which I’m not 100% interested in. If you’re not listening to his podcast you should subscribe right now.
I particularly enjoyed episode 187 with guest James Bach. Apparently James is a famous Software Tester, although I first thought the podcast would teach me a thing or two about software testing I didn’t know yet I was actually surprised that it was more about how to advance your career. Every software developer knows that IT is a very fast moving sector to be working in. Each day some tech company brings out a new technology that could make your current skills and thus you as a person obsolete. That’s why it is so important to continuously keep learning.
James has a rather unconventional school career, he dropped out of school at the age of 16. And he based himself on the American constitution to convince his teachers that he didn’t have to do homework at the age of 12. Everything he learned is based on passion, he only learns about things which he is truly passionate about. What I took away from the episode is that I have to try each day to keep learning and to stimulate myself to be a continuous learner. To do that I am now trying to, even more then I used to, read blogs and books, watch videos and listen to podcasts.
The best advice that was given is summarized by the following question you can ask yourself:
How can I feature myself as someone unique?
In these times of crisis and people losing their jobs all of the world. It is important to have skills that make you unique. You’ll probably never be the best programmer in the world or the best CSS guru, there is always someone better than you. But by keep learning new things you shape yourself as unique person with a very broad skill set. The more you know, the more valuable you become.
James also wrote a book about this subject which I think will be a great read. I quickly added it to my reading list. I just need Amazon to create an international version of the Kindle DX so I can start reading.
To finish off I would like to talk about upcoming posts. Patrick Smacchia was so kind to provide me with a review copy of NDepend. So I’ll be playing around with it and blog about it. I can already say I’m very impressed.
Till next time, hopefully It won’t take half a year for me to write another blog post.






