tag:blogger.com,1999:blog-9275044437399185962024-02-20T21:59:28.881-05:00Coffee Driven DeveloperDiscoveries during software developmentJeff Kwakhttp://www.blogger.com/profile/07550255824949903087noreply@blogger.comBlogger14125tag:blogger.com,1999:blog-927504443739918596.post-35924466269139130242012-04-13T23:24:00.000-04:002012-04-13T23:24:14.331-04:00Learning How to Serve Up Static Files with Node<div class="separator" style="clear: both; text-align: center;"><a href="http://upload.wikimedia.org/wikipedia/commons/thumb/c/ca/Lightning_simulator_questacon05.jpg/320px-Lightning_simulator_questacon05.jpg" imageanchor="1" style="clear:left; float:left;margin-right:1em; margin-bottom:1em"><img border="0" height="213" width="320" src="http://upload.wikimedia.org/wikipedia/commons/thumb/c/ca/Lightning_simulator_questacon05.jpg/320px-Lightning_simulator_questacon05.jpg" /></a></div><br />
So I consider myself a Level 2 node.js/CoffeeScript beginner. I'm learning out in the open. Some of the things I come across are interesting from the perspective of someone climbing the learning curve. To gain experience, I wanted to share some things I've learned about one of the most basic functions of any web server: Serving static files.<br />
<br />
Serving static files is something you might take for granted if you come from a background where the "website" is hosted on top of IIS or Apache. I never really gave it a lot of attention, but whatever framework I was using was silently, faithfully, serving up all my images, icons, style sheets, and scripts.<br />
<br />
Node gives you pretty low-level access to the HTTP server. So when you make an HTTP application in Node -- you're technically writing the server. So this means you have to be responsible for handling all aspects of the web request and every web request including all those cool static files.<br />
<br />
<h3>Writing it All from Scratch</h3><br />
So you might start the Node server up in the typical fashion.<br />
<br />
<pre class="brush:coffee">http = require 'http'
...
server = http.createServer serve_file
port = 3000
server.listen port
console.log "The static file server is on port #{port}"
</pre><br />
The function <code>serve_file</code> is the callback that will handle the request.<br />
<br />
<pre class="brush:coffee">serve_file = (request, response) ->
console.log "Serving #{request.url}"
context = { request, response }
fs.readFile 'public' + request.url, after_file_is_read(context)
</pre><br />
The first thing the static file server has to do is actually read the file. We use the asynchronous version of the standard <code>readFile</code> method. I'm bundling up the <code>request</code> and <code>response</code> objects into something I'm calling <code>context</code>. You'll see how I'm handling this object (notice I'm intentionally not using the word <i>class</i>) in subsequent method calls.<br />
<br />
<pre class="brush:coffee">after_file_is_read = (context) ->
(error, data) ->
console.log "The requested file has been read"
context = context extends {error, data}
respond_with_file(context) or respond_with_error(context)
</pre><br />
The method <code>after_file_is_read</code> isn't the actual callback. It's a method that is invoked immediately passing the context and returns a function (the real callback) and captures the current context in a closure. This helps prevent the Christmas tree effect with nested anonymous callbacks. Essentially the sequence can be followed by looking at functions defined on the left side of the code.<br />
<br />
I'm probably being a little too <i>clever</i> (and maybe not in the good way), but something that is just too cool to pass up (during my experimentation phase) is to use the <code>extends</code> keyword to add the additional values of <code>error</code> and <code>data</code> into the "context". Essentially, <code>extends</code> adds two additional properties (<code>error</code> and <code>data</code>) onto the exsisting object that already has a <code>request</code> and <code>response</code> properties. <br />
<br />
Now here's where it get's really <i>clever</i>. I call into the <code>respond_with_file</code> function. But what if there's an error? Shouldn't I be protecting the call to <code>respond_with_file</code> with an <code>if</code> statement and calling <code>respond_with_error</code> in an <code>else</code> block?<br />
<br />
<pre class="brush:coffee">respond_with_file = (context) ->
if context.error then return undefined
console.log "Responding with the file"
{response, data} = context
response.writeHead 200, {"Content-Type":"text/html"}
response.end data
@
</pre><br />
I could, but instead, I'm turning the more conventional approach inside out. I'm making the absence of an error a pre-condition for executing the main body of the <code>respond_with_file</code> method. The function returns <code>undefined</code> if the precondition is not met. This let's me compose the functions using the <code>or</code> operator as I've done.<br />
<br />
Notice the "Content-Type" header. There's a bug (a.k.a. an unimplemented enhancement) here.<br />
<br />
The <code>respond_with_error</code> function does what you might expect. Based on the error received from <code>readFile</code>, it returns either a 404 or 500 response with the error message.<br />
<br />
Now start the application up and browse on over to http://localhost:3000. <br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhMd8TL7TwqfHDoBRiJxEZdpQ9kdOftxYW5eUMt_DaUvII4T5gQzjZm_UoyWNNTxakg7o3MmushmaXJHvq5EfM9Q19GhyPVhBWBoXOXXm7peI_uj2RDVeATHzIDQ6FloEX3rjLcQv1elQP9/s1600/by-hand-default.png" imageanchor="1" style=""><img border="0" height="226" width="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhMd8TL7TwqfHDoBRiJxEZdpQ9kdOftxYW5eUMt_DaUvII4T5gQzjZm_UoyWNNTxakg7o3MmushmaXJHvq5EfM9Q19GhyPVhBWBoXOXXm7peI_uj2RDVeATHzIDQ6FloEX3rjLcQv1elQP9/s320/by-hand-default.png" /></a></div><br />
Ugh error! Sorry no default handling for index.html. Ok, browse over to http://localhost:3000/index.html. <br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjyGwSq1DFN9zjov-AmuGqhamqnCf9slIAGv5TPHW-UjI8F6c-pplS6IUcgmkq5oDAuvi3-HypsqPOcU6awkE0dvNZt-wAD_n6Kbn7gcbGsbQ0EHYUhgpY5JRVu5H2Ng12hdGjH9AKMsceJ/s1600/by-hand-index.png" imageanchor="1" style=""><img border="0" height="226" width="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjyGwSq1DFN9zjov-AmuGqhamqnCf9slIAGv5TPHW-UjI8F6c-pplS6IUcgmkq5oDAuvi3-HypsqPOcU6awkE0dvNZt-wAD_n6Kbn7gcbGsbQ0EHYUhgpY5JRVu5H2Ng12hdGjH9AKMsceJ/s320/by-hand-index.png" /></a></div><br />
Success!! We're serving up a static HTML page! <br />
<br />
With the source I included an image. Browse on over to http://localhost/bunny.png<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj0jGKB7N2j1cpB8U0U7-NQhzajTlS30HEbtSP-PGNbrPToxb1WDOgabmP4MjtyEibgKjZwDWfOdpMNJ03h6tkiP_UUMMY8wbXmxP6OErq82c9RmFjOMMn4L8bg3xCHlKTgsSvd1jqG51QF/s1600/by-hand-bunny-image.png" imageanchor="1" style=""><img border="0" height="226" width="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj0jGKB7N2j1cpB8U0U7-NQhzajTlS30HEbtSP-PGNbrPToxb1WDOgabmP4MjtyEibgKjZwDWfOdpMNJ03h6tkiP_UUMMY8wbXmxP6OErq82c9RmFjOMMn4L8bg3xCHlKTgsSvd1jqG51QF/s320/by-hand-bunny-image.png" /></a></div><br />
Ummm...that doesn't look anything like a bunny. Remember the "Content-Type". Well, you have to deliver the right one based on the media type you're serving. Otherwise, the browser has every right to be confused.<br />
<br />
<h3>Now the Easier, More Powerful, More Complete, More Extensible Way</h3><br />
Wouldn't it be nice if there was a library already built that let us do all that web server stuff? But it can't get in the way like some <b>BAFx</b> would. Well there is of course. <a href="http://www.senchalabs.org/connect/">ConnectJS</a>.<br />
<br />
All that code turns into this:<br />
<br />
<pre class="brush:coffee">connect = require 'connect'
server = connect()
server.use connect.static('public')
port = 3001
server.listen port
console.log "Connect is listening at #{port}"
</pre><br />
The primary difference being that now it's a much more complete and robust solution. Browse over to http://localhost:3001/bunny.png<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhr5DL8AQIWS-zrOJAeI_Prf0ZGeqtPNgI_el8-1oliRnaMNWK2ZYPyWSwfK8eDayrHu5JzCI-u-Y91-P8duzuQx5M27xcS_RJOOFRJtzXguzvMyEGcqIRJFs4eD6KGQe1dGsKkJLf74sKw/s1600/connect-bunny-image.png" imageanchor="1" style=""><img border="0" height="226" width="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhr5DL8AQIWS-zrOJAeI_Prf0ZGeqtPNgI_el8-1oliRnaMNWK2ZYPyWSwfK8eDayrHu5JzCI-u-Y91-P8duzuQx5M27xcS_RJOOFRJtzXguzvMyEGcqIRJFs4eD6KGQe1dGsKkJLf74sKw/s320/connect-bunny-image.png" /></a></div><br />
It works by adding a concept Connect calls <i>middleware</i>. I think of middleware as a plugin. Essentially, all the middleware objects that are attached to the <code>connect()</code> object are run, and when one of them handles the request it stops. There is existing middleware for a lot of things including authentication, logging, and many many more. In the code above you can see we're attaching the <code>static</code> middleware that serves up static content in the 'public' directory.<br />
<br />
What's more, middleware in the context of Connect isn't some heavyweight component technology. It's simply a function and a callback. Very elegant. Very powerful. Very simple. Writing a connect compliant middleware component is for another time (but it won't be a long post).<br />
<br />
The source for these examples is on <a href="https://github.com/futureturnip/node-static-examples">GitHub</a> and the <a href="http://futureturnip.github.com/node-static-examples/">annotated source is the GitHub page</a>.<br />
<br />
<h3>What's Next</h3>I got plenty of XP from this exercise, but not quite enough to level up. Still need to tackle:<br />
<br />
<ul><li>Talking to a persistence store</li>
<li>Handling authentication of users</li>
<li>Logging</li>
</ul><br />
Two out of three are handled by standard Connect middleware.<br />
<br />
Then I might be ready for level 3. Just enough to start fighting some of the bigger monsters, and getting into bigger trouble.<br />
<br />
<br />Jeff Kwakhttp://www.blogger.com/profile/07550255824949903087noreply@blogger.com0tag:blogger.com,1999:blog-927504443739918596.post-8324213508032689312012-04-03T23:17:00.000-04:002012-04-03T23:54:09.851-04:00The Node Beginner's Example in CoffeeScript<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjXih2FMRw623-AngfL7QLE3GBcPg_6KwMIVMib0qWABdOTr5-5L1lvGiXVr5JCRNgDB2BXaG0tIkBM3crOEHIXCFb4B71jJ9EmQUolU_5SpANlPlt3g5LhVLeXMWO8XBVsmX_C-g45JoTi/s1600/download.jpg" imageanchor="1" style="clear:left; float:left;margin-right:1em; margin-bottom:1em"><img border="0" height="320" width="213" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjXih2FMRw623-AngfL7QLE3GBcPg_6KwMIVMib0qWABdOTr5-5L1lvGiXVr5JCRNgDB2BXaG0tIkBM3crOEHIXCFb4B71jJ9EmQUolU_5SpANlPlt3g5LhVLeXMWO8XBVsmX_C-g45JoTi/s320/download.jpg" /></a></div><br />
I started programming in the era when to play a game, you had to type it in by hand. To this day, I still learn best by following along with an extended tutorial; getting it to work initially and then playing around with it to see what happens.<br />
<br />
I was delighted to find Manuel Kiessling's <a href="http://www.amazon.com/The-Node-Beginner-Book-ebook/dp/B005T75AF4/ref=sr_1_sc_1?s=books&ie=UTF8&qid=1332904702&sr=1-1-spell">The Node Beginner's Book</a>. What a little gem of a tutorial. It starts from the obligatory node http application, and then extends it to deal with real world problems like asynchronous handlers, listening to events, organizing the code, and more; without going too deep. As he states, it's designed to be the tutorial he wishes he had when he first started, and you'll go from beginner to advanced beginner.<br />
<br />
I decided to follow along in CoffeeScript. The tutorial provided a great little workbench to try out all sorts of things from code organization to putting the project up on <a href="https://github.com/futureturnip/NodeBeignnerInCoffeeScript">GitHub</a> to trying out code documentation in <a href="http://futureturnip.github.com/NodeBeignnerInCoffeeScript/">docco</a>.<br />
<br />
I'll walk you through some of the code, but check out the <a href="http://futureturnip.github.com/NodeBeignnerInCoffeeScript/">docco</a> documentation for the full details. Like the author did, there's more code, and more abstraction than is required. The point of the walk through is to have a place to try some things out that might come in a "real" application.<br />
<br />
Here is the basic specification from The Node Beginner Book:<br />
<br />
<ol><li>Users can access the application from a web browser</li>
<li>The user should see a welcome page when requesting <code>http://domain/start</code> which displays a file upload form</li>
<li>By choosing an image file to up to upload and submitting the form, this image should be uploaded to <code>http://domain/upload</code>, where it is displayed once the upload is finished</li>
</ol><br />
Here's what you get if you type:<br />
<br />
<pre>coffee begin.coffee
</pre><br />
...and browse to <code>http://localhost:8989</code>.<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjI7Z9wUFQR3qbWsJpLTqPF3zOx1s9gOvjkQ10q7tocNUATucugyAL0A5-5E7b7PaHsj3MnID5i0Ps_L_tNS7FnyjHdvhiC0JapS2C5BJDtvOfiBj0O1piWLWWxA5374PrbHVlzPVRk_oBN/s1600/node-begin-ss.png" imageanchor="1" style="margin-left:1em; margin-right:1em"><img border="0" height="400" width="376" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjI7Z9wUFQR3qbWsJpLTqPF3zOx1s9gOvjkQ10q7tocNUATucugyAL0A5-5E7b7PaHsj3MnID5i0Ps_L_tNS7FnyjHdvhiC0JapS2C5BJDtvOfiBj0O1piWLWWxA5374PrbHVlzPVRk_oBN/s400/node-begin-ss.png" /></a></div><br />
Beauty, right? Hey, it's not a design project :)<br />
<br />
A convention in node is to name the entry point of the application <code>index</code>. I'm not a fan of that convention. <code>Index</code> to me is a view name. My personal convention is to start the application in a module with the same name as the application itself. So the entry point to my application is called <code>begin</code>.<br />
<br />
<pre class="brush:coffee"># The entry point to the application.
server = require './server'
server.start 8989
</pre><br />
The server module is my code. It simply starts the canonical node <code>HTTP</code> server and starts listening on the passed port. It provides a handler that parses the incoming request URL, bundles them up into an object, and passes them into a router function.<br />
<br />
The router is a simplistic route map. The little <code>action</code> function serves as a macro to return the actual function (functions are first-class citizens remember) that is exported inside the module referenced by <code>name</code>. This is a little trick of mine to put all the "actions" in their own folder. It works as long as the action exports its namesake. This shortens the map (<code>routes</code>). The single exported <code>route</code> function, looks up the passed URL path in the <code>routes</code> object literal (or sets the next action to the <code>not_found</code> handler) and processes the request.<br />
<br />
<pre class="brush:coffee"># Router determines what to do with the requested path
action = (name) ->
require("./actions/#{name}")[name]
routes =
"/": action('start')
"/start": action('start')
"/show/uploaded": action('show')
"/show/sad_panda": action('show')
"/upload": action('upload')
exports.route = (http) ->
console.log "Routing #{http.path}"
process = routes[http.path] ? action('not_found')
process http
</pre><br />
Again for the purpose of code organization I separated out the "views" into their own folder. Some of the simpler actions like <code>start</code> just write an HTML response.<br />
<br />
<pre class="brush:coffee"># The start action
html = require '../lib/html'
view = require '../views/start_view'
exports.start = (http) ->
console.log 'Start action invoked'
http.respond = html.write_html
http.respond view.render()
</pre><br />
Notice how on line 8 (above), I attach the <code>html.write_html</code> to the <code>http</code> object. This is me noodling with the <code>this</code> property in JavaScript/CoffeeScript. It's different than the meaning of <code>this</code> in C#. The reference to <code>this</code> refers to the context of the function when it is <i>called</i>. It has nothing to do (necessarily) with an object instance of a class. So when you set the <code>respond</code> property to the function <code>html.write_html</code> you essentially spot weld a method on the instance that is held by the <code>http</code> parameter. Invoking it on line 9 (above) with <code>http.render</code> makes the <code>@response</code> properties of <code>http</code> available as on lines 8 and 9 below. Keep in mind that <code>http</code> is just an ordinary object (not a type from a <code>class</code>). The <code>@response</code> was attached to the object way back in the <code>server</code>.<br />
<br />
<pre class="brush:coffee">exports.write_html = (html = '', status = 200) ->
console.log 'writing html'
headers =
"Content-Type" : "text/html"
"Content-Length" : html.length
@response.writeHead status, headers
@response.end html
</pre><br />
All that was me trying (probably to an extreme) trying to escape from the <a href="http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html">Kingdom of Nouns</a> as referenced in the book.<br />
<br />
One other discovery worth mentioning is handling asynchronous programming (without an <code>async</code> or <code>await</code> keyword). Take the <code>show</code> action; responsible for determining what image file to write.<br />
<br />
<pre class="brush:coffee"># The show action displays an impage
html = require '../lib/html'
view = require '../views/show_error_view'
fs = require 'fs'
exports.show = (http) ->
match = http.path.match /\/(\w+)$/
http.image_name = if match then match[1] else 'sad_panda'
console.log "Display the image #{http.image_name}"
fs.readFile "./images/#{http.image_name}.png", 'binary', file_loaded(http)
file_loaded = (http) ->
(error, file) ->
if not error
http.respond = html.write_png
http.respond file
else
http.respond = html.write_html
http.respond view.render({image_name:http.image_name, error}), 500
</pre><br />
The first lines just determine what image to display, in a rudimentary way. The last line of the <code>show</code> method calls node's <code>readFile</code> method. The last parameter is the callback to invoke when <code>readFile</code> is ready. I could have defined the function anonymously, and in this particular case it might not matter. Instead, something I really like is invoking a function that returns the actual callback. <br />
<br />
If you look closely <code>file_loaded</code> is actually being invoked immediately. However, the result of the function is another function (it returns a function) that will serve as real callback later. The function <code>file_loaded</code> is also saving the state of the <code>http</code> object in a closure. This pattern also has the effect of avoiding deeper and deeper indentation across callbacks. The functions and the "steps" are all along the left side of the code file (but still very much asynchronous). I thought this was an easy way to understand what has happening.<br />
<br />
Please checkout the <a href="http://futureturnip.github.com/NodeBeignnerInCoffeeScript/">GitHub page</a> for a line-by-line account of the source. Please mess around with the code on your own, and check out <a href="http://www.amazon.com/The-Node-Beginner-Book-ebook/dp/B005T75AF4/ref=sr_1_sc_1?s=books&ie=UTF8&qid=1332904702&sr=1-1-spell">The Node Beginner's Book</a>.<br />
<br />
<h2>What's Next</h2><br />
Now that I've leveled up to (Level 2) as a Node advanced beginner I realize just how far I have to go.<br />
<br />
<ul><li>Exploring some of the bigger frameworks like <a href="http://expressjs.com/">Express/Connect</a> and <a href="http://zappajs.org">Zappa</a>.</li>
<li>Doing some of the more mundane things<br />
<ul><li>Authorization</li>
<li>Logging</li>
<li>Persistence</li>
</ul></li>
</ul><br />
Node + CoffeeScript is Love.<br />Jeff Kwakhttp://www.blogger.com/profile/07550255824949903087noreply@blogger.com0tag:blogger.com,1999:blog-927504443739918596.post-44581256968231802322012-03-22T23:37:00.002-04:002012-03-22T23:41:14.155-04:00Try and Tell Them That Today, and They Won't Believe You<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEha4Sxbv2WwySexG-x88a2i_1Ib9zg8wnRLmc-xHC7D9LJgCMQOMqD3U1GIx6OwQScfIMcMzatjYbHl7SuIy36R6LdOKz9imK9OU6YtFDlnkMACnQ6SWs9rswNgn_yopxp2VoGzJOiaGncM/s1600/Four+Yorkshiremen.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" height="240" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEha4Sxbv2WwySexG-x88a2i_1Ib9zg8wnRLmc-xHC7D9LJgCMQOMqD3U1GIx6OwQScfIMcMzatjYbHl7SuIy36R6LdOKz9imK9OU6YtFDlnkMACnQ6SWs9rswNgn_yopxp2VoGzJOiaGncM/s320/Four+Yorkshiremen.jpg" width="320" /></a></div><br />
I would have put long odds that JavaScript would someday rule the world. I remember it as an awkward and terribely mal-supported child in the early days; back when AOL was still around, and the primary purpose of JavaScript was to create a DHTML spinning clock that would follow your mouse.<br />
<br />
Silently, over the years, and largely because every browser had to support it for the web to be useful, the JS runtime became the most ubiquitous runtime on the planet. Innovation happened in the background (my background); Gmail, CommonJS, jQuery, Node, etc... I mean, holy cow, the way to develop apps for Windows 8 will be HTML5 and JavaScript. Who would of thought?<br />
<br />
But, it's still JavaScript. It's still indisputably an ugly, warty, and hastily thrown together language. Even <a href="http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742">The Good Parts</a> can't really come up with that many good parts. JavaScript, as a language, is still unappealing to me which is simply a matter of taste. Obviously, it's won and people are doing <a href="http://madebyevan.com/webgl-water/">great things</a> with it.<br />
<br />
<blockquote class="tr_bq">"Every now and then I feel a temptation to design a programming language but then I just lie down until it goes away." — L. Peter Deutsch</blockquote><br />
Enter <a href="http://coffeescript.org/">CoffeeScript</a>. A language that compiles to JavaScript. It's not perfect, but it's appealing to me. It still has some of the warts left over from JavaScript, and a few new of its own. Attempting to use it as a shield from learning JavaScript is a mistake -- you need to know JavaScript. Beware. CoffeeScript is still JavaScript. I find it's syntax pleasant and it's features helpful. <br />
<br />
There are several debates as to whether or not it's useful <a href="http://wekeroad.com/2012/03/21/coffeescript-or-straight-up-js-i-suck-either-way/">(Rob Conery summarizes and links to some of the more prominent talking points in his own struggle)</a>. Personally, I don't care that there is a debate at all. I will use CoffeeScript when I can because it's appealing to <u>me</u>. There's room for different tastes, at least in my world.Jeff Kwakhttp://www.blogger.com/profile/07550255824949903087noreply@blogger.com0tag:blogger.com,1999:blog-927504443739918596.post-4573404253333278922010-12-07T06:27:00.003-05:002010-12-07T06:30:49.681-05:00Creating a NuGet Package<p><a href="http://nuget.codeplex.com" target="_blank">NuGet</a> is a package manager for .NET that was recently released by Microsoft as a CTP. This library is similar to <em>gems</em> or <em>cpan</em> or similar libraries in other languages. I decided to try my hand at creating a <em>HelloWorld</em> package.</p><p>First I needed a package. My original idea was to create something useful enough to <a href="http://nupackpackages.codeplex.com/" target="_blank">contribute to the public feed of NuGet packages</a>. I started by creating the <a href="http://shelf.codeplex.com" target="_blank">Shelf</a> library, which is a small set of extension methods. Notably, I created the <code>Each<T></code> method that extends <code>IEnumerable<T></code>. It takes an <code>Action<T></code>, invoking the action for every item in the sequence. It's a trivial and small library at the moment, but imagine it is something useful and complicated. The library itself isn’t the point here.</p><p>Create the package “manifest” (my term).</p><div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:c1d77ec8-8da1-4fea-af36-33c6ecce16f8" class="wlWriterEditableSmartContent"><pre class="brush: xml;"><package>
<metadata>
<id>shelf</id>
<version>2010.1203.2330.42313</version>
<authors>Kwak</authors>
<description>Shelf is a library of common extension methods</description>
<language>en-US</language>
</metadata>
<files>
<file src="Shelf\bin\Release\*.dll" target="lib" />
<file src="Shelf\bin\Release\*.pdb" target="lib" />
</files>
</package></pre></div><p>The documentation says the files element is optional. It seems I didn’t discover the “convention” they were speaking about in the documentation. I needed it.</p><p>I ran the command-line tool <em>nuget.exe</em> passing it the <em>pack</em> command and the package manifest. It spat out the packaged file (BTW, you can use just about any zip tool to browse the contents of the package).</p><p>There are couple of different ways to deploy the package. Submitting your package for inclusion in the public feed is one option. You can put the file on any accessible URL. The NuGet source includes a “Server” utility. Until my library grows to a point where it’s not laughably trivial, I opted for just putting it in my file system and pointing the package manager to folder. Phil Haack has a <a href="http://haacked.com/archive/2010/10/21/hosting-your-own-local-and-remote-nupack-feeds.aspx" target="_blank">great post</a> explaining the deployment options.</p><p>So with my package (<em>shelf.2010.1203.2330.42313.nupkg</em>) located in my local packages folder, anytime I want to make use of the shelf library, I simply go to the package manager console and type </p><pre>Install-Package shelf</pre>NuGet goes off, makes sure it has the latest package, adds the package folder to my source if it doesn't already exist, downloads (copies) the assembly, and adds the reference to the project. <p>Here are some of the references, I’ve found useful:</p><ul><li><a href="http://www.hanselman.com/blog/IntroducingNuPackPackageManagementForNETAnotherPieceOfTheWebStack.aspx" target="_blank">Scott Hanselman’s walkthrough</a>.</li>
<li><a href="http://haacked.com/archive/2010/10/21/hosting-your-own-local-and-remote-nupack-feeds.aspx" target="_blank">Phil Haack’s aforementioned post on deployment options.</a></li>
<li><a href="http://nuget.codeplex.com/documentation" target="_blank">The NuGet Documentation and CodePlex site.</a></li>
</ul><br />
<b>Conclusion:</b> Piece of cake and terribly useful for consumers of your library.Jeff Kwakhttp://www.blogger.com/profile/07550255824949903087noreply@blogger.com0tag:blogger.com,1999:blog-927504443739918596.post-35139765961729278662010-08-09T11:35:00.001-04:002010-08-09T11:35:43.998-04:00Mercurial .hgignore File for .NET Projects<p>I’m currently using Mercurial, and find myself starting out with this as a base .hgignore file.</p> <pre class="brush: plain;">glob:bin/*
glob:TestResults/*
glob:obj/*
glob:*.suo
glob:*.user</pre> Jeff Kwakhttp://www.blogger.com/profile/07550255824949903087noreply@blogger.com1tag:blogger.com,1999:blog-927504443739918596.post-59574511599490922192010-05-07T23:58:00.001-04:002010-05-07T23:58:28.297-04:00Configuring SpecFlow to Work with MSTest<p>Add a reference to TechTalk.SpecFlow and then put this in an App.config file of the MSTest project:</p> <pre class="brush: xml;"><?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="specFlow" type="TechTalk.SpecFlow.Configuration.ConfigurationSectionHandler, TechTalk.SpecFlow"/>
</configSections>
<specFlow>
<unitTestProvider name="MsTest" />
</specFlow>
</configuration></pre> Jeff Kwakhttp://www.blogger.com/profile/07550255824949903087noreply@blogger.com0tag:blogger.com,1999:blog-927504443739918596.post-31647408671221323992010-05-04T01:08:00.003-04:002010-05-04T01:20:12.405-04:00Visual Studio 2010 Styles<p>If you haven’t checked out <a href="http://studiostyles.info/" target="_blank">Studio Styles</a> yet, please go do so. An improved version of the old <a href="http://www.codinghorror.com/blog/2006/09/is-your-ide-hot-or-not.html" target="_blank">Is Your IDE Hot or Not</a> (the old site seems to have fallen into disrepair). Studio Styles is one of those well-executed, brilliant ideas, that has you saying, “Why didn’t I think of that?”</p><p>I spent some time creating a version of my favorite color scheme. It’s called <a href="http://studiostyles.info/schemes/distant-stormy-shore" target="_blank">Distant Stormy Shore</a>.</p><p><a href="http://studiostyles.info/schemes/distant-stormy-shore" target="_blank"><img style="border-bottom: 0px; border-left: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px" title="CropperCapture[1]" border="0" alt="CropperCapture[1]" src="http://lh6.ggpht.com/_yJRO8Ay9w74/S9-rwfVZFaI/AAAAAAAAB90/v_yFFJYg6PE/CropperCapture%5B1%5D%5B11%5D.png?imgmax=800" width="640" height="415" /></a> It’s based on the work by Thomas Restrepo on the <a href="http://winterdom.com/2008/03/distantshoresavisualstudiocolorscheme" target="_blank">Distant Shores</a> color scheme.</p><p>Please download and give me a “Hot” rating if you like it.</p>Jeff Kwakhttp://www.blogger.com/profile/07550255824949903087noreply@blogger.com0tag:blogger.com,1999:blog-927504443739918596.post-6640639040192672082010-04-30T21:26:00.002-04:002010-04-30T21:27:31.100-04:00Yet Another FizzBuzz<p>As interesting as I could make it.</p><pre class="brush: csharp">private static string FizzBuzz()
{
var fizzBuzzMap =
Enumerable
.Range(1, 100)
.Select(num => MapToFizzBuzz(num));
return String.Join("\n", fizzBuzzMap.ToArray());
}
private static string MapToFizzBuzz(int num)
{
if (num % 15 == 0)
return "FizzBuzz";
if (num % 5 == 0)
return "Buzz";
if (num % 3 == 0)
return "Fizz";
return num.ToString();
}</pre><p>Before, I lost interest.</p>Jeff Kwakhttp://www.blogger.com/profile/07550255824949903087noreply@blogger.com0tag:blogger.com,1999:blog-927504443739918596.post-68356820637502785482010-03-25T00:33:00.001-04:002010-03-30T23:29:41.691-04:00Dependency Injection and the Controller Factory in ASP.NET MVC<p><strong>This is a re-post from the older blog. I’m retiring that blog address and this is one of those posts that I refer to when setting up a new project.</strong></p> <p>Using an IoC is one of those things that can take a time or two to understand where it fits in and how it’s useful. Once you cross the energy barrier, it’s a color in your palette you can’t imagine missing. </p> <p>Imagine having a QuestionController that takes an interface called DomainRepository. The job of any concrete implementation of the DomainRepository will be to fetch various domain entities from a backing store.</p> <pre class="brush: csharp;">public class QuestionController : Controller
{
private DomainRepository _repository;
public QuestionController(
DomainRepository repository)
{
_repository = repository;
}
public ActionResult Index()
{
ViewData.Model = _repository.AllQuestions;
return View();
}
}</pre>
<p>This is a perfect place to use an IoC container to provide build a concrete implementation and all of it's dependencies</p>
<p>The gotcha is that ASP.NET MVC, by default, requires its controllers to have default constructors. Luckily, ASP.NET MVC uses a <code>ControllerBuilder</code> to instantiate the controllers using a ControllerFactory. This is an extension point where we can provider our own factory, one that uses the IoC of choice to resolve the controller.</p>
<p>You'll need a class for the new controller factory. This is a minimal implementation that doesn't make use of the MVC 2 <code>requestContext</code> parameter</code> </p>
<pre class="brush: csharp;">public class StructureMapControllerFactory : DefaultControllerFactory
{
protected override IController GetControllerInstance(
RequestContext requestContext,
Type controllerType)
{
return
ObjectFactory
.GetInstance(controllerType) as IController;
}
}</pre>
<p>In your bootstrapper, or in the Global.asax.cs, make the ControllerBuilder use the new controller factory</p>
<pre class="brush: csharp;">ControllerBuilder.Current
.SetControllerFactory(
new StructureMapControllerFactory());</pre>
<p>Also, in the bootstrapper, or in the Global.asax, setup your container. This is using StructureMap's 2.6.1 syntax</p>
<pre class="brush: csharp;">ObjectFactory.Initialize(factory =>
{
factory
.For<DomainRepository>()
.Use<NoSqlDomainRepository>();
});</pre>
<p>These are the minimal steps required to get the ASP.NET MVC web application ready for use with an IoC (e.g., StructureMap).</p> Jeff Kwakhttp://www.blogger.com/profile/07550255824949903087noreply@blogger.com0tag:blogger.com,1999:blog-927504443739918596.post-32485889339517245182010-03-16T01:03:00.001-04:002010-03-16T01:03:23.620-04:00Declarative Style is My Golden Hammer<p>I was working on a little pet project recently, and I really was tickled when I wrote my unit tests like this:</p><pre class="brush: csharp;"> public class Given_a_HomeController
{
private static HomeController controller;
[TestClass]
public class when_asked_for_the_index
{
private ActionResult the_result;
[TestInitialize]
public void because()
{
using_a_new_home_controller();
after_performing_the_index_action();
}
public void using_a_new_home_controller()
{
controller = new HomeController();
}
public void after_performing_the_index_action()
{
the_result = controller.Index();
Assert.IsNotNull(the_result);
}
[TestMethod]
public void it_should_return_a_ViewResult_for_the_Index_view()
{
the_result.is_a_ViewResult().for_a_view_named("Index");
}
}</pre>
<p>If you can read through the test attribute decorators and the public void C# noise, the setup and the tests read like this:</p><pre class="brush: plain;">Given a HomeController:
When asked for the index:
because:
using a new HomeController
after executing the Index action
it should return a ViewResult for the Index View
</pre>
<p>It made me smile.</p> Jeff Kwakhttp://www.blogger.com/profile/07550255824949903087noreply@blogger.com0tag:blogger.com,1999:blog-927504443739918596.post-7737192821174520262010-02-06T00:15:00.001-05:002010-02-06T00:17:28.500-05:00Fitnesse Test Styling<p>In my previous post, I concentrated on setting up Fitnesse. Unfortunately, I did a lot of hand-waving when it came to the test used in the example. I got called out on it, and rightfully so.</p> <blockquote> <p>Gregor said…</p> <p>Are you really hard coding the prices and the name of the product into the method names? Do you also have methods named "The_sub_total_shows_3_49" and The_sub_total_shows_8_17"? This means that you cannot change your acceptance test without renaming or adding methods in the fixture. This surely is not the purpose of FitNesse.</p> </blockquote> <p>The test wasn’t the purpose of the post, and I should probably have <em>Lorem ipsum’d</em> it. Alternatively, I could have explained myself a little better, and improved the test.</p> <p>My response to the comment is, “Sincerely, thank you for your comments, and yes, yes, true, and sure it is.” The real problem to my point of view is that the product owner, subject-matter expert, customer, stakeholder, or whatever you have probably explained to the programmer (me) something like this:</p> <blockquote> <p>The customer purchases items. Those items are scanned. The price of the item is put on the bill along with it's description. See figure 1. The subtotal is calculated as the sum of the price of all items on the bill and displayed at the bottom.</p> </blockquote> <p>I immediately translated this in real time into an implementation. That of a bill, of descriptions showing up on receipts, and prices being displayed and tallied. I broke up the statement into easily re-useable and parameterized chunks. In traditional Fit/Fitnesse tests this probably could have been efficiently captured in a traditional <em>ColumnFixture</em> and look something like:</p> <p><a href="http://lh4.ggpht.com/_yJRO8Ay9w74/S2z62cKOoPI/AAAAAAAABAQ/WmmDxd7ChpU/s1600-h/colfixturetotalitems3.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="col-fixture-total-items" border="0" alt="col-fixture-total-items" src="http://lh3.ggpht.com/_yJRO8Ay9w74/S2z63X5FEhI/AAAAAAAABAU/EHceJeXTCyA/colfixturetotalitems_thumb1.png?imgmax=800" width="444" height="484" /></a> </p> <p>The corresponding fixture implementation could then be given as</p> <pre class="brush: csharp;"> public class TotalItemsPurchased : fit.ColumnFixture
{
private Bill _bill;
public TotalItemsPurchased ()
{
_bill = new Bill();
}
public string Sku
{
get
{
return _bill.LastItem.Sku;
}
set
{
_bill.Scan(value);
}
}
public string Subtotal()
{
return _bill.SubTotal.ToString("C");
}
public string Description()
{
return _bill.LastItem.Description;
}
public string Price()
{
return _bill.LastItem.Price.ToString("C");
}
}</pre>
<p></p>
<p>Where <em>Bill</em> is the system under test (or it is for this example anyway). There is nothing wrong with this. It’s a very clean, clear, and concise way to implement these requirements, and to Gregor’s point the implementation code isn’t so weird anymore.</p>
<p>For me though, writing acceptance tests like this becomes too much like programming. I’m moving towards making my acceptance tests read more like end-user documentation. I’d rather the acceptance tests be in the words of the customer. I’m even willing to threaten to publish the acceptance tests as the end-user documentation. </p>
<p>A better example of flow mode using plain-text tables would have been to take the actual words of the customer and make them directly executable.</p>
<p><a href="http://lh4.ggpht.com/_yJRO8Ay9w74/S2z64CiThZI/AAAAAAAABAY/rQFpu7yRNk8/s1600-h/totalitemsenduser3.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="total-items-end-user" border="0" alt="total-items-end-user" src="http://lh5.ggpht.com/_yJRO8Ay9w74/S2z65Oo4ewI/AAAAAAAABAc/nuMKtHLGLbo/totalitemsenduser_thumb1.png?imgmax=800" width="431" height="484" /></a> </p>
<p></p>
<p>The <em>Fitnesse</em> code for this test looks like:</p>
<pre class="brush: plain;">![ TotalItemsPurchased
The customer purchases items.
Those items are scanned.
The price of the item is put on the bill along with it's description. See figure 1.
The subtotal is calculated as the sum of the price of all items on the bill
and displayed at the bottom.
]!</pre>
<p> </p>
<p>However, the underlying fixture looks weird again (e.g., <code>The_price_of_the_item_is_put_on_the_bill_along_with_it_s_description_See_figure_1.</code> Honestly I'm ok with that. I can accept the role of the fixture as the bridge between the wiki and the test automation if it means the author of the test can freely communicate the intent of the feature in his/her own words. The automation code itself is free to be separate from the fixture code in this regard.</p>
<p>As far as parameterizing the tests, for the purpose of making the fixture code more re-useable and programmer friendly, that’s ok, if that’s what you’re into, and as my commenter points out Fitnesse gives you more than a few choices (e.g., <em>ScenarioTable, ScriptTable, ActionFixture, DoFixture,</em> et. al.). </p>
<p>In fact, you can parameterize a statement like, “The description of the item is “Bubbly Yummy” and costs “$0.79” in flow-mode and a plain-text table like this:</p>
<pre class="brush: plain;">![" TotalItemsPurchased
The description of the item is "Bubbly Yummy" and costs "$0.79"
]!</pre>
<p>This can be implemented in a fixture like this:</p>
<pre class="brush: csharp;"> public class TotalItemsPurchased
{
public bool The_description_of_the_item_is_and_costs(string description, string cost)
{
// Fire up the API and do some testing
}
}</pre>
<p>It still looks a little weird, but it avoids hard-coding the values in the function names.</p>
<p>My personal goal with acceptance tests is to get the acceptance tests to feed a TDD cycle. In the standard red-green-refactor cycle is where I’ll worry about the code structure of the test infrastructure and the the application. I want to follow the cycle as depicted in <a title="Growing Object-Oriented Software" href="http://www.amazon.com/Growing-Object-Oriented-Software-Guided-Tests/dp/0321503627/ref=sr_1_1?ie=UTF8&s=books&qid=1265432005&sr=8-1" target="_blank">Growing Object-Oriented Software, Guided by Tests</a>:</p>
<p><a href="http://lh6.ggpht.com/_yJRO8Ay9w74/S2z65gvjO0I/AAAAAAAABAo/AwR9jigLUrA/s1600-h/test-cycle%5B6%5D.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="test-cycle" border="0" alt="test-cycle" src="http://lh4.ggpht.com/_yJRO8Ay9w74/S2z66Jsn4iI/AAAAAAAABAs/pL-T4Qr1Iz4/test-cycle_thumb%5B4%5D.png?imgmax=800" width="433" height="257" /></a> </p>
<p>I don’t want to pressure the writing of the acceptance criteria with implementation concerns. As a result, having fixtures that are mere connectors between the implementation and acceptance criteria is palatable in my book. I’m digging flow-mode style Fitnesse tests because there is a lot of freedom afforded the author of the acceptance test.</p> Jeff Kwakhttp://www.blogger.com/profile/07550255824949903087noreply@blogger.com0tag:blogger.com,1999:blog-927504443739918596.post-85069560683808316312010-01-29T00:18:00.003-05:002010-02-15T11:41:08.663-05:00Setting Up Fitnesse for .net<p>I promised (myself) that this blog would be more of a notebook; a stream of consciousness  describing my own discoveries. I’m not sure if what I’m going over is old hat for the Fitnesse veteran, or if organizing acceptance tests and unit tests in this way is anything of value to anyone other than myself. Although there are tutorials of setting up Fitnesse for .net already out there, I’m putting down my own personal take on the matter as what I found wasn’t exactly what I was looking for all in one place. It’s what I’m involved with at the moment.</p><p>This was all sparked when I attended <a href="http://msuarz.blogspot.com/2010/01/fitnesse-in-flow-mode.html">Maykel Suarez’s presentation on Fitnesse in flow mode</a>. I’ve learned a lot from Mike on testing and software in general since I’ve had the privilege of working with him. I was put off from Fitnesse because of some of the misuse and abuse I’ve seen in the wild. My main beef was that folk were using it as a scripting platform. This became a tangled mess of imperative goo, and the textarea provides a poor IDE in my opinion. After attending Mike’s presentation I realized I could use the wiki to document the intention of the test, and that there was already support from like minded people to make this happen.</p><p>Checkout the acceptance test I wrote for a hypothetical POS system. Notice, there’s nothing techie in there. In fact, it even looks like user documentation. A sign, that perhaps this is a good acceptance test.</p><p><a href="http://lh6.ggpht.com/_yJRO8Ay9w74/S2JvAU86MkI/AAAAAAAAA78/_LAqKWTkOkg/s1600-h/totalitemspurchased7.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Test Results for Total Items Purchased" border="0" alt="Test Results for Total Items Purchased" src="http://lh5.ggpht.com/_yJRO8Ay9w74/S2JvBquUHTI/AAAAAAAAA8A/JZBME8F_ZHI/totalitemspurchased_thumb3.png?imgmax=800" width="509" height="484" /></a> </p><p>For the Fitnesse guru’s; this particular example could probably have been written more efficiently using a good ol’ fashion ColumnFixture, but I wanted to illustrate the use of plain-text tables and how they can provide a very flexible test structure. You’ll see what the underlying Fitnesse code looks like in a second. I also could have taken the introduction text and put that inside the table to use as the driver for the test.</p><h4>Getting All the Pieces in Place</h4><h4></h4><ol><li>Go get the latest build of <a href="http://fitnesse.org/FrontPage.FitNesseDevelopment.DownLoad">Fitnesse</a>. Just download the jar file like it says (and if you don’t have Java installed you’ll need that as well). </li>
<li>Go get the latest <a href="http://www.syterra.com/FitSharp.html">fitsharp</a> library. This provides the runner and the hooks for <em>Fitnesse</em> to execute .net code. </li>
<li>Create a test project. I use <em>MSTest</em>, but whatever you’re into is cool. I like to name my test project something like <em>GoGoGrocer.Specifications</em>, where <em>GoGoGrocer</em> is the name of the system/application. </li>
<li>Create a folder to hold your acceptance tests. I name mine <em>AcceptanceTests</em>. Go figure. </li>
<li>Dump the fitnesse.jar file you downloaded directly into the <em>AcceptanceTests</em> folder. </li>
<li>Create a little batch file to handle starting up Fitnesse and put these options in it: <pre class="brush: plain">java -jar fitnesse.jar -p 8080 -e 0</pre>There are a lot of options to start Fitnesse, and a big help was to realize how useful the <a href="http://fitnesse.org/FitNesse.UserGuide.QuickReferenceGuide">Quick Reference</a> section was in the User Guide. The options above start the Fitnesse server on port 8080 (-p) and the turn off version history – you know the wiki thing (-e 0). </li>
<li>Create a <em>bin</em> folder under <em>AcceptanceTests</em> and put all the fitsharp files in there. Also change the project’s build settings to output into that folder as well. </li>
<li>Create additional folders under the project for <em>UnitTests</em> and <em>Fixtures.</em> I’ll explain the <em>Fixtures</em> in a second. </li>
<li>Create a file called <em>fitness.config</em> and put that in the <em>bin</em> folder. The contents of the file should be: <pre class="brush: xml;"><suiteConfig>
<ApplicationUnderTest>
<AddAssembly>
bin\GoGoGrocer.Specifications.dll
</AddAssembly>
<AddNamespace>fitlibrary</AddNamespace>
<AddNamespace>system</AddNamespace>
<AddNamespace>
GoGoGrocer.Specifications.Fixtures
</AddNamespace>
</ApplicationUnderTest>
<fitSharp.Fit.Application.FileExclusions>
<Add>^\.svn$</Add>
</fitSharp.Fit.Application.FileExclusions>
</suiteConfig></pre>This adds the test assembly into the runner, and also provides a place to reference the namespaces of your fixtures. This makes it easy for you to reference them in your <em>Fitnesse</em> code. <strong>UPDATE: If your tests hang, make sure this file is encoded as UTF-8 (XML...sigh)</strong></li>
<li>One more file to go. Open up the command prompt and run the <em>startFitnesse.bat</em> file. Among other things, this will install your <em>FitnesseRoot</em> and build the initial structure. Edit the <em>content.txt</em> file directly under the newly created <em>FitnesseRoot</em> folder. <pre class="brush: plain;">!*> using fitsharp
!define COMMAND_PATTERN {%m -c bin\fitnesse.config -r fitnesse.fitserver.FitServer,bin\fit.dll %p}
!define TEST_RUNNER {bin\Runner.exe}
*!
!*> defines
!define COLLAPSE_SETUP {true}
!define COLLAPSE_TEARDOWN {true}
*!</pre>Hint: use the “Show All Files” feature in the Solution Explorer and add all the relevant folders to your project. </li>
</ol><p>Now you’re ready to start using <em>Fitnesse</em>. When you’re all done with setup your project structure should look something like this:</p><p><a href="http://lh6.ggpht.com/_yJRO8Ay9w74/S2JvCN0HFVI/AAAAAAAAA8E/YXw_0XxEUlA/s1600-h/solution-explorer-acctests%5B4%5D.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="solution-explorer-acctests" border="0" alt="solution-explorer-acctests" src="http://lh6.ggpht.com/_yJRO8Ay9w74/S2JvDISvy-I/AAAAAAAAA8I/RUq8OZqIEL4/solution-explorer-acctests_thumb%5B2%5D.png?imgmax=800" width="403" height="484" /></a> </p><h4>Writing a Test in Flow Mode</h4><p>The following content file defines the “Total Items” test shown above:</p><pre class="brush: plain;">!2 Total Items Purchased
The customer purchases items. Those items are scanned. The price of the item is put on the
bill along with it's description. See figure 1. The subtotal is calculated as the sum of
the price of all items on the bill and displayed at the bottom.
!img-l http://sites.google.com/site/futureturnip/home/images/sub-total-receipt.png
![ TotalItemsPurchased
The cashier scans "Wonder Bread" costing $3.49
The description "Wonder Bread" is displayed on the bill
The bill shows that the "Wonder Bread" costs $3.49
The sub total shows $3.49
The cashier scans "Gallon Milk 2%" costing $3.89
The description "Gallon Milk 2%" is displayed on the bill
The bill shows the cost of "Gallon Milk 2%" is $3.89
The sub total shows $7.38
The cashier scans "Bubbly Yummy" costing $0.79
The description "Bubbly Yummy" is displayed on the bill
The bill shows the cost of "Bubbly Yummy" is $0.79
The sub total shows $8.17
]!</pre><p>The test is human-readable text, even in it’s wiki markup form. The trick is of course tying it to a <em>Fixture. </em>The fixture is a bridge between the <em>Fitnesse</em> runner and your code. The plain-text table ties itself to the <em>TotalItemsPurchased</em> class on it’s opening declaration. In that class a method is defined for every line in the text; replacing spaces with underscores and generally ignoring special characters like quotes or the percent sign (it did take a little experimentation to find that out). Here’s what fixture code might look like:</p><pre class="brush: csharp;">namespace GoGoGrocer.Specifications.Fixtures
{
public class TotalItemsPurchased
{
public bool The_cashier_scans_Wonder_Bread_costing_3_49()
{
// This method is just the hook.
// Fire up your API and test the SUT.
}
public bool The_description_Wonder_Bread_is_displayed_on_the_bill()
{
return true;
}</pre><p>The methods return <em>true</em> for a passing test. That’s a little quirky, and there are opportunities to improve the reporting, but that’s the bridge into your test code.</p><h4>Summary</h4><p>I still have some little issues with <em>Fitnesse, </em>and I still think the Ruby folk have us beat with Cucumber, but for .net <em>Fitnesse</em> offers a pretty-good solution for acceptance tests.</p><p>I also tried to “Export Template…” this, but the resulting template doesn’t install itself into Visual Studio. Haven’t figured that out yet, but I’ll share if I ever do.</p>Jeff Kwakhttp://www.blogger.com/profile/07550255824949903087noreply@blogger.com3tag:blogger.com,1999:blog-927504443739918596.post-64606714188384775862010-01-21T00:38:00.005-05:002010-01-21T00:49:59.741-05:00Functional Patterns for Refactoring in C#<p>Trying to work on a little filler presentation for my brown-bag sessions at work on a couple of new code smells that can be solved thanks to the small dose of functional programming afforded us by LINQ and C# 3.5 and greater.</p><p>I’m working from the refactoring example given in <a href="http://www.amazon.com/Agile-Principles-Patterns-Practices-C/dp/0131857258/ref=sr_1_1?ie=UTF8&s=books&qid=1264049788&sr=8-1">Agile Principles, Patterns, and Practices in C#</a> for the <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes">Sieve of Eratosthenes</a>. When this book was published LINQ wasn’t around, and in a 1.x world this is Uncle Bob’s final listing for the problem:</p><pre class="brush: csharp">public static int[] GeneratePrimeNumbers(int maxValue)
{
if(maxValue < 2)
return new int[0];
else
{
UncrossIntegersUpTo(maxValue);
CrossOutMultiples();
PutUncrossedIntegersIntoResult();
return result;
}
}
</pre><p>This is fine. It reads well. I’ll get into the implementation of some of the methods in a second, but here’s my final implementation of the same method:</p><pre class="brush: csharp">public static int[] GeneratePrimeNumbers(int maxValue)
{
return
Primes
.TakeWhile(prime => prime <= maxValue)
.ToArray();
}
</pre><br />
<h4>When Generating a Sequence Return <code>IEnumerable<T></code></h4><p>I would like to drop the call to <code>ToArray</code>, but then I would break the interface from the original problem. However, whenever you see a sequence being generated, use <code>IEnumerable<T></code> unless you need the indexing, and use an iterator if you can get away with it. Take my implementation of <code>Primes</code> for example:</p><pre class="brush: csharp">public static IEnumerable<int> Primes
{
get
{
var remaining = Integers.Where(i => i >= 2);
while (true)
{
int prime = remaining.First();
yield return prime;
remaining = remaining.Where(num => num % prime != 0);
}
}
}
</pre><p>There’s no need for any result arrays or other collectors. Just generate the sequence and let the caller tell stop pulling values when they’re ready. This is all about deferred execution and lazy evaluation.</p><p>Likewise, my implementation of Integers is:</p><pre class="brush: csharp">public static IEnumerable<int> Integers
{
get
{
int count = 0;
do
{
yield return count++;
} while (true);
}
}
</pre><h4>Replace Loops with Filters, and Use Aggregates</h4><p>Something you ended up doing a lot in 1.x code was writing a function like this (again from Uncle Bob’s original example):</p><pre class="brush: csharp">private static int NumberOfUncrossedIntegers()
{
int count = 0;
for (int i = 2; i < crossedOut.Length; i++)
{
if (NotCrossed(i))
count++; // bump count
}
return count;
}
</pre><p>Basically, this counts the number of elements in the boolean array crossedOut that are false. In the case of this algorithm, we have to skip the first two. In LINQ this becomes:</p><pre class="brush: csharp">private static int NumberOfUncrossedIntegers()
{
return crossedOut.Skip(2).Where(x => x == false).Count();
}</pre>The where statement provides a filter and the count provides the counting. I in-lined the NotCrossed function in the lambda. <h4>Summary</h4><p>I’m not knocking Uncle Bob’s original implementation. I think it’s groovy. I’m just saying that now that LINQ is around it can let us leverage some pretty powerful syntax to refactor our loops and generators.</p>Jeff Kwakhttp://www.blogger.com/profile/07550255824949903087noreply@blogger.com0tag:blogger.com,1999:blog-927504443739918596.post-45335204601055423872010-01-13T00:55:00.001-05:002010-01-13T00:55:32.933-05:00Oh no! It’s you Again.<p>So it’s January, and my New Year’s resolution was to suck less than I did the year before. My blogging, and my desire to blog have waned over the last year or couple of years. So, new blog; fresh start; time to rekindle the love of programming and creation of software in general. So in the spirit of my resolution, I’m committing to blogging again.</p><br />
<p>The old blog had to die. I was paying a nominal fee to keep it alive and entertain the 17 readers I had collected. The content attempted too much at times. I was put off from posting frequently because most of the posts were articles and not log entries. Some of the content was useful (to me at least), but it’s best to make a clean break.</p><br />
<p>The new blog is a place to store my eclectic bits of techie-software related nuggets. It will be more of a journal. Things I’m working on, as I’m working on them. I’ll try to post the whitepapers somewhere else (but probably not at all).</p><br />
<p><code>//TODO: Insert Blog Post Here</code></p>Jeff Kwakhttp://www.blogger.com/profile/07550255824949903087noreply@blogger.com0