<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"><channel><description>Morten Christiansen's technology blog.</description><link>http://www.without-precedence.dk/archive</link><title>Without Precedence Blog RSS Feed</title><item><title>Booky: Beta 2 Released</title><link>http://www.without-precedence.dk/blog/04-02-09/booky-beta-2-released</link><guid>http://www.without-precedence.dk/blog/04-02-09/booky-beta-2-released</guid><pubDate>Wed, 04 Feb 2009 21:37:00 +0100</pubDate><description><![CDATA[

<p>A long while has passed since the first beta version of Booky became publicly available so it's with great joy I can announce the next release. You can get your hands on the new version at the Booky <a title="Booky the Bookmark Manager" href="/projects/booky-the-bookmark-manager">project page</a> (Windows only).</p>
<p>Booky is a bookmark manager which allows you to store and search your favorites by tags rather than browse a huge folder hierarchy as is (unfortunately) the standard in current browsers. It sits in the system tray and thus works independently of your browser choice.</p>
<p>The new version is much improved and is now what I would call a stable program. The first difference one will encounter is the addition of an installer. This is a very simple installer, one I aim to improve a lot in the future when I learn more about the WiX toolset. Continuing with the more obvious improvements, a number of nifty features have also been added to the interface, including a drop-down menu for matching tags and a context menu for the systray icon for quickly relaunching bookmarks. Apart from that, a number of smaller fixes to the interface and stability fixes have been introduced.</p>
<p><img class="center" title="Booky Beta 2 Screenshot" src="/images/booky-beta-2.png" alt="Booky Beta 2 Screenshot" width="338" height="135" /></p>
<p>For a look at what the next version of the program will bring, I plan on improving the installer in a number of ways (e.g., integrate the installation of the .NET framework) and to introduce an options dialog for different settings and bookmark exporting.</p>
<p>Don't forget to report any bugs or other feedback you may have to <em>withoutprecedence@gmail.com.</em></p> ]]></description></item><item><title>Renaissance</title><link>http://www.without-precedence.dk/blog/01-02-09/renaissance</link><guid>http://www.without-precedence.dk/blog/01-02-09/renaissance</guid><pubDate>Sun, 01 Feb 2009 14:31:00 +0100</pubDate><description><![CDATA[

<p>This post marks the rebirth of the Without Precedence website as it is the first post after the site disappeared this December. Going back, it started innocently enough, I thought, when my website was one day unavailable. My web host had not had a stellar performance record previously so I paid it no heed. A couple of days later, though, the severity of the situation hit me when I visited my local geek news dealer - my we host (Needhost) had been one of the most recent victims of the downturn and they had to turn the key.</p>
<p>There was no information to be had from Needhost itself and it seemed that all data was lost. I must admit I was a little&nbsp; panicked at this point, after establishing that I could find no backup of any of my data, not to speak of the website code itself. Before continuing this tale of woe, I should point out that this old website code was anything but pretty. It was my first ever attempt at a non-static website and it showed. With the exception of a few includes for a page header, footer and menu, the code consisted of one huge php file with a lot of conditional statements in it. Ugh.</p>
<p>Anyways, I decided that the time was due for a new foundation to be built. Having just finished another website project, I was ready to get my hands dirty and from those efforts did this page appear. I have built the entire page from the ground up, avoiding existing frameworks and components. One might argue that this is an unnecessary effort but it's a good learning experience and the freedom it provides is not to be scoffed at either - I only hope that it hasn't resulted in too many bugs.</p>
<p>As a result of this effort I have produced a sort of lightweight website framework, slightly influenced by CakePHP (which I spent about 30 minutes finding out I din't want to use). As I get the framework code cleaned out I will be posting it here so that others might get some use out of it.</p>
<p>This whole experience has given me the kick needed to produce a proper website and it has also given me a chance to revisit the purpose and focus of the site. And of course, I have learned the timeless lesson of the value of backups.</p>
<p>In all fairness to my old web host, I should mention that they later not only offered access the people's data but had also made a transition deal with another host, which would allow you to transfer your lost subscription fee and forego the initial signup fee. But alas, this news came too late for me to take advantage of.</p> ]]></description></item><item><title>PHP Framework I: The Database</title><link>http://www.without-precedence.dk/blog/11-02-09/php-framework-i-the-database</link><guid>http://www.without-precedence.dk/blog/11-02-09/php-framework-i-the-database</guid><pubDate>Wed, 11 Feb 2009 20:35:00 +0100</pubDate><description><![CDATA[

<p>This is the first of a series of posts describing the PHP framework I mentioned in a <a title="Renaissance" href="/blog/01-02-09/renaissance">previous post</a>. I start out by introducing the original first feature of the framework, one that lies at the heart of most websites - database querying. <em>Disclaimer: I'm still learning my way around proper PHP architecture so take this with as many grains of salt as you like.</em></p>
<p>For any website beyond the most simple, you are bound to be doing a lot of database queries to present the website data. This can quickly grow to become a large mess of database connections, SQL query strings, sanitizing and result sets. When I began work on the project, I hadn't worked with SQL for some time and I couldn't remember any but the most simple queries. To solve this I would wrap SQL queries into PHP objects and functions for easy access. Perhaps inspired a bit by LINQ I decided on a composable set of query functions on an SQL object which can be called thusly:</p>
<ol class="code">
<li>//(SQL): SELECT name, age FROM users WHERE age = 18;</li>
<li>$result = SQL::select("name","age")-&gt;from("users")-&gt;where("age","18")-&gt;query();</li>
<li>&nbsp;</li>
<li>//(SQL): INSERT INTO users VALUES ('John', 'Doe', '23');</li>
<li>SQL::insertInto("users")-&gt;values("John","Doe","23")-&gt;query();</li>
</ol>
<p><span class="mono">$result</span> is a standard MySQL result set as returned by the <span class="mono">mysql_query </span>function. Alternatively, you can fetch a row of the result set with the query:</p>
<ol class="code">
<li>$row = SQL::select("name","age")-&gt;from("users")-&gt;where("age","18")-&gt; queryRow();</li>
<li>$name = $row['name'];</li>
<li>$age = $row['age'];</li>
</ol>
<p>Each method (except the query methods) returns an object which aggregates the query data. If you have an editor which supports intellisense this will allow you to easily compose many different SQL queries without having to remember the exact syntax. While it is infeasible for me to support all possible SQL queries the most common are supported and the model can easily be expanded. Below you can see a simple example of how a method on the <span class="mono">InnerHtml</span> class can decorate a query with the FROM clause:</p>
<ol class="code">
<li>function from($table){</li>
<li>&nbsp;&nbsp;&nbsp; $this-&gt;sql .= " FROM ". $table;</li>
<li>&nbsp;&nbsp;&nbsp; return $this;</li>
<li>}</li>
</ol>
<p>What we have now is a simple model for constructing SQL queries but it gives us something even more powerful. We are now free to incapsulate all the details about such issues as connection management and parameter sanitization. Management of the connection to the database (MySQL in this case, but it should be simple to change due to the isolation) is provided by the singleton class <span class="mono">DatabaseConnection</span>.</p>
<ol class="code">
<li>class DatabaseConnection{</li>
<li>&nbsp;&nbsp;&nbsp; private static $dc = null;</li>
<li>&nbsp;&nbsp;&nbsp; private static $connection = null;</li>
<li>&nbsp;&nbsp;&nbsp; </li>
<li>&nbsp;&nbsp;&nbsp; private function __construct(){</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; self::$connection = mysql_connect(Settings::$dbPath, Settings::$loadUser,Settings::$loadPass);</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; if (!self::$connection)</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; die('Could not connect: ' . mysql_error());</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; mysql_select_db(Settings::$dbName, self::$connection);</li>
<li>&nbsp;&nbsp;&nbsp; }</li>
<li>&nbsp;&nbsp;&nbsp; </li>
<li>&nbsp;&nbsp;&nbsp; static function get(){</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; if(self::$connection == null){</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; self::$dc = new DatabaseConnection();</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; return self::$connection;</li>
<li>&nbsp;&nbsp;&nbsp; }</li>
<li>&nbsp;&nbsp;&nbsp; </li>
<li>&nbsp;&nbsp;&nbsp; //Call this at the end of each page using DB calls</li>
<li>&nbsp;&nbsp;&nbsp; static function close(){</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; if(self::$connection != null){</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; mysql_close(self::$connection);</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; self::$connection = null;</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</li>
<li>&nbsp;&nbsp;&nbsp; }</li>
<li>}</li>
</ol>
<p>This code is used by the <span class="mono">query</span> methods of the SQL query object.</p>
<ol class="code">
<li>function query(){</li>
<li>&nbsp;&nbsp;&nbsp; DatabaseConnection::get();</li>
<li>&nbsp;&nbsp;&nbsp; return mysql_query($this-&gt;sql);</li>
<li>}</li>
</ol>
<p>To dispose the connection the <em>close</em> function must be called at the bottom of every page (using DB queries). The result of the above code is that as long as you can remember to include the <span class="mono">DatabaseConnection::close()</span> call at the bottom of each page you never have to think about connections again. With regards to sanitizing the input this is just a question of cleaning any function parameters before they are added to the inner SQL string.</p>
<ol class="code">
<li>//Params: Arbitrary number of field-value pairs</li>
<li>function where(){</li>
<li>&nbsp;&nbsp;&nbsp; $firstWhere = true;</li>
<li>&nbsp;&nbsp;&nbsp; for ($i = 0; $i &lt; func_num_args(); $i += 2) {</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; $field = func_get_arg($i);</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; //Cleaning the input values</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; $val = Database::cleanInputString(func_get_arg($i+1));</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; if ($firstWhere){</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; $this-&gt;sql .= " WHERE ".$field." = '".$val."'";</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; $firstWhere = false;</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }else{</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; $this-&gt;sql .= " AND ".$field." = '".$val."'";</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</li>
<li>&nbsp;&nbsp;&nbsp; }</li>
<li>&nbsp;&nbsp;&nbsp; return $this;</li>
<li>}</li>
<li>&nbsp;</li>
<li>...</li>
<li>&nbsp;</li>
<li>class Database{</li>
<li>&nbsp;&nbsp;&nbsp; static function cleanInputString($string){</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; if (get_magic_quotes_gpc())</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; $string = stripslashes($string);</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; $string = mysql_real_escape_string($string, DatabaseConnection::get());</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; return $string;</li>
<li>&nbsp;&nbsp;&nbsp; }</li>
<li>}</li>
</ol>
<p>I hope that I didn't miss anything critical in that sanitizing function since I don't have web security 100% down in PHP yet. The only problem (or maybe not?) with relying on the database classes to handle input cleaning is that if you end up constructing your own SQL strings for the more advanced queries this code can't handle, you must manually clean all the input. I find that this code has really made database operations much easier but you don't have to take my word for it - go <a title="PHP Framework" href="/files/phpframework.zip">check it out</a> yourself. The file will be expanded to contain the other features of the framework as I get it cleaned up.</p> ]]></description></item><item><title>PHP Framework II: Page Request Dispatcher</title><link>http://www.without-precedence.dk/blog/18-02-09/php-framework-ii-page-request-dispatcher</link><guid>http://www.without-precedence.dk/blog/18-02-09/php-framework-ii-page-request-dispatcher</guid><pubDate>Wed, 18 Feb 2009 23:24:00 +0100</pubDate><description><![CDATA[

<p>Having built the foundation for working with the <a title="PHP Framework I: The Database" href="/blog/11-02-09/php-framework-i-the-database">database</a> I move on to the main logic of dispatching page requests. The strategy I have used is to treat the retrieval of pages as a <a title="How I Explained REST to My Wife" href="http://tomayko.com/writings/rest-to-my-wife">RESTful</a> API where the request url becomes a parameter to a dispatcher.</p>
<p>Rather than having the url hiearchy of the website map directly to the server-side file hierarchy, all requests are routed through a single php file using url rewriting. This can be done simply by modifying the .htaccess file like this:</p>
<ol class="code">
<li>#Options +FollowSymlinks</li>
<li>RewriteEngine on</li>
<li>&nbsp;</li>
<li>RewriteRule \.(js|ico|gif|jpg|JPG|png|css|txt|xml)$&nbsp; -&nbsp; [L]</li>
<li>RewriteRule ^(.*)$ index.php</li>
</ol>
<p>The .htaccess file is configured to allow image files and other such resources through as normal. You can also allow other types of files to be treated as normal by adding their extension to the list. For a great introduction to all the useful things you can do with the .htaccess file, click <a title=".htaccess tips and tricks" href="http://corz.org/serv/tricks/htaccess.php">here</a>.</p>
<p>The main purpose of the dispatcher is to pick the requested url apart and ask the proper components to construct a response view. Speaking of views, I use the MVP pattern to split up the responsibility of the components. Thus, each first level subdirectory of the website matches a controller instance which handles validation and presentation of the view. When you request an url, the dispatcher checks for the existance of a controller class with the name of the subdirectory. If one such exists, the remainder of the url is passed to it as a parameter to validate whether it is a legal url. To illustrate how this work, consider the following url to a blog post on this site:</p>
<ol class="code">
<li>http://www.without-precedence.dk/blog/01-02-09/renaissance</li>
</ol>
<p>The <span class="mono">blog</span> part of the url tells the dispatcher that it should look for a class called <span class="mono">BlogController</span> in a file called <span class="mono">blog.php</span>. All controllers implement the <span class="mono">IController</span> interface which provides a method for validating the url and presenting the view.</p>
<ol class="code">
<li>interface IController{</li>
<li>&nbsp;&nbsp;&nbsp; public function show($param);</li>
<li>&nbsp;&nbsp;&nbsp; public function validateParam($param);</li>
<li>}</li>
</ol>
<p>The rest of the url contains a date and an url-encoded blog title. These are first passed to the <span class="mono">validateParam</span> method to make sure the post exists and then to the <span class="mono">show</span> method to render the blog post.</p>
<p>If no controller is found or the controller does not validate the url, the standard error page is shown - which is just another controller being invoked. Controllers can also be made to handle urls which does not correspond to normal pages such as AJAX requests and file downloads. This design is what I was referring to when I was talking about the RESTful API, where each url request can be seen as an API call that can be handled in an arbitrary fashion.</p>
<p>Whenever you want another sub-page or provide some service (such as RSS feeds, the creation of which I will be blogging about in the not too distant future) you must simply create a controller with the proper file and class-names and you're in business. This might be simplifying things a bit, as you would most likely need to also create a model class and a view class to interact with the database and construct the page view, respectively, but I'm sure you'll forgive that minor slight.</p>
<p>On a final note, this design might not be ideal for handling deeply nested urls, as the controllers can become very complex but there's nothing stopping you from implementing a nested controller structure. I ran into a spot of trouble when I attempted to create a sub-hierarchy of admin pages within a single controller, which I can't recommend.</p>
<p>The framework code has been updated to contain the functionality described in this post and it can be found <a title="PHP Framework" href="/files/phpframework.zip">here</a>.</p> ]]></description></item><item><title>Musings on Language Design</title><link>http://www.without-precedence.dk/blog/02-03-09/musings-on-language-design</link><guid>http://www.without-precedence.dk/blog/02-03-09/musings-on-language-design</guid><pubDate>Mon, 02 Mar 2009 23:02:00 +0100</pubDate><description><![CDATA[

<p>A few years ago, at the university, we were working on a project under the theme of programming languages and compilers. After much debating and brainstorming we decided to develop <a title="The Card Game Language" href="/projects/the-card-game-language">a little language for describing card games</a> and an interpreter which could tranlate such a game into a playable version. For practical reasons the language ended up being limited to solitaire games but never the less it remains one of the coolest pieces of software I have had the pleasure of working on.</p>
<p>Creating a language is an interesting experience and it is not often an excuse comes along for making one. After long discussions about whether and how to include loops and such, you get a certain amount of appreciation for the work that has gone into the languages you use on a daily basis. It is a balancing act to get all the factors right, especially if you both want an expressive and elegant language which also facilitates efficient writing of code.</p>
<p>In the case of our language, I had come up with the initial idea which was to describe the card game as closely as possible to how you would think about a real card game. This meant that you would designate card piles, events for clicking them and rules for moving and turning cards. In essense we maintain a state machine for the playing field with legal state changes matching those of the real world; in other words, you cannot magically conjure up new cards and otherwise create a game state which does not make sense. I quickly grew attached to this idea and envisioned the language as a conceptually pure language which would more or less only use these card abstractions to define behavior. The others group members, on the other hand, looked at the language with more practical eyes and wanted more traditional control logic to be included as well such as conditional branching and looping structures. After much discussion and arguing we settled on the practical version of the language which, in hindsight, I think was a crucial choice.</p>
<h3>Dusting off the old bits<br /></h3>
<p>Recently I got it into my head to bring out the interpreter again, shine it up and repackage it in some Silverlight goodness. I hadn't tried Silverlight yet but I've made <a title="Booky the Bookmark Manager" href="/projects/booky-the-bookmark-manager">another</a> program in WPF and that's close enough I guess.</p>
<p>The original code was some dusty old C# 2.0 code which I merrily began refactoring away at and I have now brought it up-to-date with shiny C# 3.0 features. To be honest, it was quite easy to port the code to Silverlight, though not without a couple of strange bugs. The biggest hurdle was to replace the legacy code which no longer worked in Silverlight. Who needs ArrayLists anyway? Here, you can see how the Card Game Simulator shapes up:</p>
<p><img class="center" title="Card Game Simulator" src="/images/card_game_simulator.jpg" alt="Card Game Simulator" width="450" height="435" />The simulator is in a constant state of change as I work on improvements and you can always find the current version <a title="Silverlight Card Game Simulator" href="/apps/card-game-simulator">here</a>. I will be posting a guide to develop your own card games in the near future, so stay tuned.</p> ]]></description></item><item><title>The Importance of Following the Tutorial</title><link>http://www.without-precedence.dk/blog/05-03-09/the-importance-of-following-the-tutorial</link><guid>http://www.without-precedence.dk/blog/05-03-09/the-importance-of-following-the-tutorial</guid><pubDate>Thu, 05 Mar 2009 09:58:00 +0100</pubDate><description><![CDATA[

<p>Last night I spent a good hour and a half trying to use a custom font for a Silverlight application without luck. It was supposed to be a simple matter, just include a font file in the project, set its build action to Resource and reference it in the XAML. But for some reason it refused to recognize the presence of the font file no matter what I tried.</p>
<p>After several different fonts and going through most of the possible build actions for them I gave up, attributing it to some strange fluke in my particular development environment. A little later I figured I should go over one of the tutorials one more time to see if there was some tiny point I'd missed. It turned out there was.</p>
<p><img class="center" title="Add Existing Item" src="/images/existing_item.png" alt="Add Existing Item" width="416" height="170" />All the tutorials which I'd followed instructed me to add the font file to the project using the Add New Item option shown above. Not giving this much thought I just dragged the font file unto the project which seemed to work fine. While there is no apparent difference between the two methods, switching to the prescribed approach solved my problems. Who would have known?</p> ]]></description></item><item><title>EVE Online Cards</title><link>http://www.without-precedence.dk/blog/08-03-09/eve-online-cards</link><guid>http://www.without-precedence.dk/blog/08-03-09/eve-online-cards</guid><pubDate>Sun, 08 Mar 2009 00:16:00 +0100</pubDate><description><![CDATA[

<p>I just updated the <a title="The CGL interpreter" href="/apps/card-game-simulator">CGL interpreter</a> to support card themes, specifically a cool EVE Online sci-fi theme. In case you were wondering, <a title="The EVE Online website" href="http://www.eveonline.com/">EVE Online </a>is a cool sandbox-style MMORPG I have played on-and-off for a couple of years.</p>
<p><img class="center" title="Eve Online CGL Theme" src="/images/eve_card_theme.jpg" alt="Eve Online CGL Theme" width="450" height="376" />An unfortunate side effect of this theme is that it about tripled the download size to over 1.3 megs but I hope you'll manage. For more information about the Card Game Language, <a title="The Card Game Language" href="/projects/the-card-game-language">click here</a>.</p> ]]></description></item><item><title>PHP Framework III: Page Construction</title><link>http://www.without-precedence.dk/blog/24-03-09/php-framework-iii-page-construction</link><guid>http://www.without-precedence.dk/blog/24-03-09/php-framework-iii-page-construction</guid><pubDate>Tue, 24 Mar 2009 22:38:00 +0100</pubDate><description><![CDATA[

<p>In the <a title="PHP Framework II: Page Request Dispatcher" href="/blog/18-02-09/php-framework-ii-page-request-dispatcher">previous part</a> of my little PHP framework walkthrough, I covered how an url was turned into a page controller being instantiated. Now I'll describe how the page gets constructed and turned into HTML. The main steps in this process are (starting from where we left off):</p>
<ol>
<li>The <span class="mono">show</span> method on the controller gets called with any supplied parameters.</li>
<li>The controller retrieves the model of the page to be shown.</li>
<li>The controller uses the model to create a view of the page.</li>
<li>The view is used to create a page object, which can be customized as needed for the page (This step only applies if the page is an ordinary HTML page).</li>
<li>The page source is sent to the client.</li>
</ol>
<p>The <span class="mono">show</span> method handles all the steps involved in constructing the requested page. While the process differs somewhat depending on the page to be shown the above steps describe the typical case.</p>
<p>The first task when constructing the page is to retrieve its model. This model is the model-part of the MVC pattern used by the framework to separate data, presentation and control logic. The model contains information which is to be presented on the website. This could include such information as blog posts, news items or user-generated content, all of which is normally stored in a database. The model class is named similarly as the controller class only it is stored in the model directory instead. The job of the model class is to create a PHP object representation of the data to be shown.</p>
<p>So far the <span class="mono">show</span> method in the controller could look something like this:</p>
<ol class="code">
<li>public function show($param){</li>
<li>&nbsp;&nbsp; $posts = MainModel::read();</li>
<li>}</li>
</ol>
<p>The next step is to create a view of the page which is the main content that the client will recieve. Similar to the model, there is a view class which is used to generate the code to send to the client, usually HTML. The view class extends a class called <span class="mono">Template</span> which just specifies a member called <span class="mono">html</span> and a method, <span class="mono">get</span>, to retrieve it.</p>
<ol class="code">
<li>class MainView extends Template{</li>
<li>&nbsp;&nbsp;&nbsp; public function MainView($posts){</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; $html = Header::create();</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; $html .= MainContent::create(PostList::create($posts), ItemList::create());</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; $html .= Footer::create();</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; </li>
<li>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; parent::Template($html);</li>
<li>&nbsp;&nbsp;&nbsp; }</li>
<li>}</li>
</ol>
<p>View templates use a number of modules to build up the page; <span class="mono">Header</span>,<span class="mono"> PostList</span>, <span class="mono">ItemList</span> and <span class="mono">Footer</span> in the above example. These modules make up different parts of a page and can take parts of the model as parameters as is the case here. Combined, the modules produce the desired HTML for the page. It should be mentioned that there is no specific reason that the view must output HTML, it can just as well be XML of some format.</p>
<p>With these additions the  <span class="mono">show</span> method in the controller now looks something like this:</p>
<ol class="code">
<li>public function show($param){</li>
<li>&nbsp;&nbsp; $posts = MainModel::read();</li>
<li>&nbsp;&nbsp; $template = new MainView($posts);</li>
<li>}</li>
</ol>
<p>The next step only applies if you're constructing an ordinary HTML page. If not, you can just return the code generated by the view. The framework has a utility class called <span class="mono">Page</span> which makes it easier to create all the parts which make up a standard HTML page, including meta tags, styles and scripts. You might want to modify the class to suit your needs as it is not prepared for all possible contingencies. The class uses the template created by the view to create the page:</p>
<ol class="code">
<li>public function show($param){</li>
<li>&nbsp;&nbsp; $posts = MainModel::read();</li>
<li>&nbsp;&nbsp; $template = new MainView($posts);</li>
<li>&nbsp;&nbsp; $page = Page::create($template,"Demo Page")</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; -&gt;addStyle("default.css")</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp; -&gt;setDescription("This is a default page description.")</li>
<li>&nbsp;&nbsp;&nbsp; &nbsp; -&gt;setKeywords("these, are, example, keywords");</li>
<li>&nbsp;&nbsp; echo $page-&gt;getHtml();</li>
<li>}</li>
</ol>
<p>This example creates a page with the title "Demo Page" and sets the stylesheet as well as the meta information for description and keywords. Each of the functions on the page returns the page object so you can easily chain the page configuration calls as done above.</p>
<p>This is basically what it takes to create a page, though as I hinted at, it is possible to change the approach for special types of views such as XML feeds or an AJAX API. Some pages might not need a model or even a view and as such the term 'page' applies in a very loose sense. In upcoming posts I'll provide examples of alternative page types.</p>
<p>I've updated the <a title="PHP Framework" href="/files/phpframework.zip">framework code</a> to use the example used in this post and the style for it is now based on one of the free styles from <a title="Free CSS Templates" href="http://www.freecsstemplates.org/">Free CSS Templates</a>, which also supplied the style for this site.</p> ]]></description></item><item><title>The Joy of Ray Tracing</title><link>http://www.without-precedence.dk/blog/15-04-09/the-joy-of-ray-tracing</link><guid>http://www.without-precedence.dk/blog/15-04-09/the-joy-of-ray-tracing</guid><pubDate>Wed, 15 Apr 2009 18:35:00 +0200</pubDate><description><![CDATA[

<p>During the last few weeks I have been very busy with an old project I have taken up again. The project is a ray tracer called Rend, which is written in C#. Ray tracing is a way of rendering 3D images by simulating how light travels through a scene. Despite the heavy use of math and theory this requires, it is possibly the most rewarding and addictive project I have worked on. It is incredibly fascinating to model some physical phenomenon and then watch as it gets rendered on the screen. Even failures can provide for very entertaining and beautiful pictures.</p>
<p>Mostly ray tracing is done in C++ these days as it is a very compute intensive task but you can get equally beatiful images in C# with but a bit of patience. If you can tolerate a some trigonometry and vector math and have the least bit of interest in computer graphics I cannot recommend it enough to try and build your own ray tracer. The central rendering algorithm is not very complex and beyond the math it is easy to integrate different effects into the engine.</p>
<p>For Rend I have set up a <a title="Rend - A Managed Ray Tracing Engine" href="http://without-precedence.dk/projects/rend-a-managed-ray-tracing-engine">project page</a> where I will be maintaining a list of its primary features as well as a showcase of the most interesting effects I have rendered with it. I plan on making a version of Rend available for download but I don't feel it is quite ready for public scrutiny at the moment.</p>
<p>For a peak at what you can do with Rend, here is an image:</p>
<p><img class="center" title="A mountain 3D model" src="http://without-precedence.dk/images/raytracing/raytracing - mountain.jpg" alt="A mountain 3D model" width="450" height="250" /></p> ]]></description></item><item><title>Performance Tuning a .NET Application</title><link>http://www.without-precedence.dk/blog/05-05-09/performance-tuning-a-net-application</link><guid>http://www.without-precedence.dk/blog/05-05-09/performance-tuning-a-net-application</guid><pubDate>Tue, 05 May 2009 23:10:00 +0200</pubDate><description><![CDATA[

<p>I have been working on a ray tracing engine in C# and working on it is a constant battle for performance. Performance is literally the currency of ray tracing - each time your optimize your code, you get to implement some new effect. This optimization cycle has led to some interesting insights into performance tuning in .NET, and C# specifically.</p>
<p>If there's one thing you need to realize it's this: the more you think you know, the less you really know. You may think that some clever little hack or algorithm you make will increase performance but there is only one way to tell - measure! I cannot recount all the times which I thought I had made an optimization only to discover that performance was the same if not actually worse. How can this be? You might see a piece of code which appears to have some obvious optimization but the thing that will catch you unaware in many (and surprisingly subtle) cases is CPU cache. Cache stores the most recent data you've accessed very close to the CPU. It has this wonderful ability to make performance tuning seem a very non-deterministic job at times, when something you just did a few line<img class="left" title="Chip" src="/images/chip.jpg" alt="Chip" width="220" height="153" />s of code earlier indirectly affects the performance of the executing code. At the level of micro optimizations, cache makes the abstraction that each instruction has a specific cost <a title="The Law of Leaky Abstractions" href="http://www.joelonsoftware.com/articles/LeakyAbstractions.html">leaky</a>, along with other features of modern CPUs such as out-of-order execution and branch prediction.</p>
<p>The most important aspect of performance tuning, and you'll hear this advice again and again, is that you have to measure the actual performance. You can single out different operations and measure them in a tight loop but what I find the most useful is using a profiler. This allows you to get the most realistic image of the performance of the application where different pieces of code gets to influence how the cache is populated which <em>will </em>cause unforeseen side effects. I use the profiler shipping with the Visual Studio Team System edition and I'm afraid I have to point you to Google for any free alternatives.</p>
<p><img class="right" title="Measure!" src="/images/ruler.jpg" alt="Measure!" width="220" height="187" />Regardless of whether you have access to a profiler, there is a point&nbsp; which you have to keep in mind when you use Visual Studio. There are basically three modes to run your program in during development: debug mode, release mode and outside Visual Studio. For some reason it took me a while before I realized the obvious fact that running in release mode was faster than debug mode, where a lot of optimizations are disabled and debugging code is inserted into your program. This switch alone almost doubled the performance of my ray tracer. What I didn't realize was that release mode still has some performance impacts, such as the lack of method inlining. This little fact had caused me to make some optimizations which would turn out to be redundant once the code ran outside of VS (where the performance about doubled once again). For ray tracing I have a Vector class which I use very heavily during computations and I had found that turning public properties into read-only fields to avoid the extra layer of indirection gave about 10-15% increase in performance. Do not waste your time with such optimizations which the compiler will do for you (and that without hurting the design of your application).</p>
<p>There is a particular downside when optimizing .NET code, an aspect which is also one of the strengths of the platform. There has been much discussion on the web regarding the speed of .NET code vs. C++ code and it turns out that in some cases .NET code runs just as fast if not faster than the native C++ code. This is due to its use of JIT compilation which allows the runtime to optimize for the specific PC as well as perform increasingly better optimizations as the framework is improved. This essentially means that you get continous free optimizations of all your .NET applications with each realease of the runtime. The reason this can be a bit of a pain is that it makes it difficult to tell how relevant older articles regarding performance tuning are. I have experimented with different performance techniques which appear to no longer have any effect, probably because the problems they were supposed to solve have been fixed. To make a concrete example, in Service Pack 1 for .NET 3.5, a lot of optimizations were introduced for structs such as inlining of functions which the compiler, previously, only did for classes. This change made any prior articles on the performance characteristics of structs, if not worthless, then at least unlikely to be accurate.</p>
<p>When developing a ray tracer, you sometimes need to face the reality that the precision of floating point values is finite and at a time I was experimenting with the use of doubles rather than floats for most of the operations in the engine. There was a clear performance penalty for for this (around 25% if I recall correctly), and the main reasons for this are that the memory bandwidth and cache size is effectively halved when dealing with doubles. Other factors such as the different instructions used for operating on floats and doubles affect the performance as well but here I must admit my knowledge of the subject comes up a bit short.<img class="center" title="Space Flight" src="http://without-precedence.dk/images/raytracing/raytracing - space flight.jpg" alt="Space Flight" width="450" height="250" /></p>
<p>One of the casualties when you wage the war for performance long enough inescapably seems to be the design and readability of your code. For my ray tracer I have on numerous occasions found myself having to make the choice between good, high-level abstractions and performance. Each layer of indirection you create in your system to increase readability and maintainability has an adverse effect on performance. Since their introduction, I have been very fond of lambda expressions in C# and these are a prime example of how you can keep your code clean and succinct at the cost of performance. I admit that in this case I have been sinful and haven't acutally tested their performance but tests I have read indicated a not insignificant penalty for calling delegates compared to ordinary function calls and therefore I have tried to avoid them in the more trafficked parts of the engine.</p>
<p>To keep your code clean an elegant while still keeping a strong focus on performance, my main advice would be to isolate the more arcane optimizations to very specific places that other code only interacts with indirectly. Also, make sure to identify the hot parts of your code and optimize them aggresively while being more lax in other parts. For example, most of the execution time in my ray tracer somehow concerns the Vector class so this is were I have kept a lot of focus. One common thing to do with this class is retrieving the value of a specific axis so to get a bit of performance increase I turned to unsafe pointer arithmetic:</p>
<ol class="code">
<li>public float this[byte axis]</li>
<li>{</li>
<li>&nbsp;&nbsp; get</li>
<li>&nbsp;&nbsp; {</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; unsafe</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; fixed (float* pX = &amp;_x)</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return *(pX + axis);</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</li>
<li>&nbsp;&nbsp; }</li>
<li>}</li>
</ol>
<p>This is not the most pretty and readable code you're likely to find in any C# program but it is isolated in the Vector class and other classes remain unaware of the implementation since it does not change the interface of the class.</p>
<p>To round off this lengthy article, I recall a story I read somewhere about a team who weren't happy with the performance of their application. Profiling the application led them to a peice of code which took up a huge amount of the CPU time. The team really labored to optimize this code as best they could, with unrolling and inlining and the like until someone realized their folly - they had been optimizing the idle loop!</p> ]]></description></item><item><title>Hidden Features of C#</title><link>http://www.without-precedence.dk/blog/31-05-09/hidden-features-of-c</link><guid>http://www.without-precedence.dk/blog/31-05-09/hidden-features-of-c</guid><pubDate>Sun, 31 May 2009 20:28:00 +0200</pubDate><description><![CDATA[

<p>I just want to highlight a fantastic post over on the Stack Overflow site for anyone who would call themselves a C# programmer - whether novice or expert. Named 'Hidden Features of C#', the question provides exactly what it says on the tin: a huge compilation of hidden language features and constructs as well as some less-than-obvious patterns the language allows for.</p>
<p>The tips are ordered by how interesting and useful people have found them so you get a huge amount of value for the time you spend reading it. I'm sure you will find that you know many of the provided tips, but I doubt that few programmers, even experts, would know (or at least remember) all the advice gathered there. But enough talking, go <a title="Hidden Features of C#" href="http://stackoverflow.com/questions/9033/hidden-features-of-c">check it out</a>.</p> ]]></description></item><item><title>An Era Ends, Another Begins</title><link>http://www.without-precedence.dk/blog/28-06-09/an-era-ends-another-begins</link><guid>http://www.without-precedence.dk/blog/28-06-09/an-era-ends-another-begins</guid><pubDate>Sun, 28 Jun 2009 13:48:00 +0200</pubDate><description><![CDATA[

<p>For the last five years I have laboriously been stumbling towards the distant goal of becoming a software engineer and completing my education. As of this week the process has come to completion and I stand a certified engineer and Master of Science.</p>
<p>It is a strange feeling, as if bursting through some invisible membrane protecting me from the worries of the future and the difficulties that lie ahead. In fact, the day after my final exam I was more worried than I was on the actual day, as it turned out I had postponed quite a lot of worries. The bulk of these revolved the business I have planned on starting with some of my fellow students. Will we make it? Can we make enough money? Can we make a good product? How should we proceed? These are just some of the questions that troubled me. It has been a couple of days now and I've managed to calm myself dow a bit as things have become a bit more clear.</p>
<p>One thing is certain, though, and that is an uncertain future. It goes without saying that none of us have experience with the type of venture we're about to undertake so there is really no knowing where it will take us. Perhaps we strike gold and become the newest in Internet fame, or perhaps we won't make a dime and shamefully be forced to go find some real jobs. However it turns out, it will be an interesting ride I'm sure. I will report our continued experiences and progress, though it is unclear how much time I will have for my usual hobby projects.</p> ]]></description></item><item><title>Resizing Images and Coder's Laziness</title><link>http://www.without-precedence.dk/blog/28-10-09/resizing-images-and-coders-laziness</link><guid>http://www.without-precedence.dk/blog/28-10-09/resizing-images-and-coders-laziness</guid><pubDate>Wed, 28 Oct 2009 21:32:00 +0100</pubDate><description><![CDATA[

<p>I have long had the feeling that I would enjoy being a photographer, a theory which I've now been validating since around mid summer. Borrowing a decent camera from my parents I've been running around town and the surrounding countryside trying to take some great pictures.</p>
<p>Obviously it's no fun just looking at your pictures all by your lonesome so I had to upload them to the web. Flickr seemed a natural choice and I've been <a href="http://www.flickr.com/photos/mochri/">uploading</a> the most interesting photos from each set. Now if you go look at them you might notice a pattern in the size of the images, namely that the maximum dimension of each picture is 1200 pixels. This is just a measure to keep the file size down but it is something of a bother to do and while it's not a huge issue it did prompt my Coder's Laziness. Coder's Laziness is what I call that useful feeling a good programmer will get when he is faced with a repetitive task that leads him to code up an app or script to do it for him. And that is what I did.</p>
<p>I find the ability to just sit down and create a tool that will bend the computer to my will and solve some problem I have to be one of the greatest rewards of being a programmer. Taking the case of the resizing app I needed, I ended up with a working solution after about 30 minutes work - it even had a few bonus features such as a progress bar and settings for compression quality for the Jpg encoding. In fact, the C# code is so small and simple I provide it to you in its entirety:</p>
<ol class="code">
<li>public partial class ResizeForm : Form</li>
<li>{</li>
<li>&nbsp; &nbsp;public ResizeForm()</li>
<li>&nbsp; &nbsp;{</li>
<li>&nbsp; &nbsp; &nbsp; InitializeComponent();</li>
<li>&nbsp; &nbsp;}</li>
<li>&nbsp;</li>
<li>&nbsp; &nbsp;private void resizeButton_Click(object sender, EventArgs e)</li>
<li>&nbsp; &nbsp;{</li>
<li>&nbsp; &nbsp; &nbsp; progressBar.Value = 0;</li>
<li>&nbsp;</li>
<li>&nbsp; &nbsp; &nbsp; string url = urlBox.Text;</li>
<li>&nbsp; &nbsp; &nbsp; int maxDimension = int.Parse(dimensionBox.Text);</li>
<li>&nbsp; &nbsp; &nbsp; int quality = (int)qualityScale.Value;</li>
<li>&nbsp;</li>
<li>&nbsp; &nbsp; &nbsp; var dir = new DirectoryInfo(url);</li>
<li>&nbsp; &nbsp; &nbsp; if (!dir.Exists)</li>
<li>&nbsp; &nbsp; &nbsp; {</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;MessageBox.Show("No such directory exists!");</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return;</li>
<li>&nbsp; &nbsp; &nbsp; }</li>
<li>&nbsp;</li>
<li>&nbsp; &nbsp; &nbsp; var resizedDir = new DirectoryInfo(Path.Combine(url, "resized/"));</li>
<li>&nbsp; &nbsp; &nbsp; if (!resizedDir.Exists) resizedDir.Create();</li>
<li>&nbsp;</li>
<li>&nbsp; &nbsp; &nbsp; var jpegs = dir.GetFiles().Where(file =&gt; file.Extension == ".jpg").ToList();</li>
<li>&nbsp;</li>
<li>&nbsp; &nbsp; &nbsp; int current = 0;</li>
<li>&nbsp; &nbsp; &nbsp; foreach (var imageFile in jpegs)</li>
<li>&nbsp; &nbsp; &nbsp; {</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;var original = new Bitmap(imageFile.FullName);</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Image resized = ResizeImage(original, maxDimension);</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;string savename = resizedDir.FullName + imageFile.Name;</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;SaveJpg(resized, savename, quality);</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;current++;</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;progressBar.Value = (int)(current / (float)jpegs.Count) * 100;</li>
<li>&nbsp; &nbsp; &nbsp; }</li>
<li>&nbsp; &nbsp;}</li>
<li>&nbsp;</li>
<li>&nbsp; &nbsp;private static Image ResizeImage(Image originalBitmap, int maxDimension)</li>
<li>&nbsp; &nbsp;{</li>
<li>&nbsp; &nbsp; &nbsp; float aspectX = maxDimension / (float)originalBitmap.Width;</li>
<li>&nbsp; &nbsp; &nbsp; float aspectY = maxDimension / (float)originalBitmap.Height;</li>
<li>&nbsp; &nbsp; &nbsp; float actualAspect = Math.Min(aspectX, aspectY);</li>
<li>&nbsp;</li>
<li>&nbsp; &nbsp; &nbsp; int sourceWidth = (int)(originalBitmap.Width * actualAspect);</li>
<li>&nbsp; &nbsp; &nbsp; int sourceHeight = (int)(originalBitmap.Height * actualAspect);</li>
<li>&nbsp;</li>
<li>&nbsp; &nbsp; &nbsp; var resized = new Bitmap(sourceWidth, sourceHeight);</li>
<li>&nbsp;</li>
<li>&nbsp; &nbsp; &nbsp; Graphics g = Graphics.FromImage(resized);</li>
<li>&nbsp; &nbsp; &nbsp; g.DrawImage(originalBitmap, new Rectangle(0, 0, resized.Width, resized.Height));</li>
<li>&nbsp; &nbsp; &nbsp; return resized;</li>
<li>&nbsp; &nbsp;}</li>
<li>&nbsp;</li>
<li>&nbsp; &nbsp;private static ImageCodecInfo GetEncoderInfo(String mimeType)</li>
<li>&nbsp; &nbsp;{</li>
<li>&nbsp; &nbsp; &nbsp; return ImageCodecInfo.GetImageEncoders().FirstOrDefault(codecInfo =&gt; codecInfo.MimeType == mimeType);</li>
<li>&nbsp; &nbsp;}</li>
<li>&nbsp;</li>
<li>&nbsp; &nbsp;private void SaveJpg(Image image, string fileName, long quality)</li>
<li>&nbsp; &nbsp;{</li>
<li>&nbsp; &nbsp; &nbsp; EncoderParameters parameters = new EncoderParameters(1);</li>
<li>&nbsp; &nbsp; &nbsp; parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);</li>
<li>&nbsp; &nbsp; &nbsp; ImageCodecInfo codecInfo = GetEncoderInfo("image/jpeg");</li>
<li>&nbsp; &nbsp; &nbsp; image.Save(fileName, codecInfo, parameters);</li>
<li>&nbsp; &nbsp;}</li>
<li>}&nbsp;</li>
</ol>
<p>If you want to look at the GUI or just play around with the code you can <a title="Resizer Project" href="/files/Resizer.zip">download the project</a> and do with it what you want. Enjoy.</p>
<p><strong>Update:</strong> The project has been replaced with a newer version.</p> ]]></description></item><item><title>Creating a DSL Parser in C#</title><link>http://www.without-precedence.dk/blog/08-11-09/creating-a-dsl-parser-in-c</link><guid>http://www.without-precedence.dk/blog/08-11-09/creating-a-dsl-parser-in-c</guid><pubDate>Sun, 08 Nov 2009 20:31:00 +0100</pubDate><description><![CDATA[

<p>I was listening to the Herding Code podcast <a href="http://herdingcode.com/?p=216">with Louis DeJardin</a> on the Spark View Engine and Louis mentioned an old blog entry he'd made on parsing DSLs. It immediately caught my interest as I've been looking for a better way to do this for a while, to use with my <a href="/projects/the-card-game-language">Card Game Language</a>, and I went and <a href="http://whereslou.com/2008/05/15/creating-a-domain-specific-language-for-parsing">looked it up</a>.</p>
<p>The reason I've been looking for another way of parsing the Card Game Language is that it relies on the generation of code files from a grammar file which is not very flexible when you want to make small changes to the language. This new approach, however, works all in C# code which seems to be much easier to work with - of cause there is more to running the code than just parsing it, but I'll have to look into that later.</p>
<p>To illustrate how the code works, take a look at the following code:</p>
<ol class="code">
<li>public class PhoneGrammar : Grammar</li>
<li>{</li>
<li>&nbsp; &nbsp; public PhoneGrammar()</li>
<li>&nbsp; &nbsp; {</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; var number = </li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Rep(Ch(char.IsNumber))</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Build(hit =&gt; new string(hit.ToArray()));</li>
<li>&nbsp;</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; var localNumber = </li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; number.If(hit=&gt;hit.Length == 3)</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .And(Ch('-'))</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .And(number.If(hit=&gt;hit.Length == 4))</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Build(hit =&gt; new PhoneNumber</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Prefix = hit.Left.Left,</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Body = hit.Down</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });</li>
<li>&nbsp;</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; var longDistanceNumber = </li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Ch('(')</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .And(number.If(hit=&gt;hit.Length == 3))</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .And(Ch(')'))</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .And(localNumber)</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Build(hit =&gt; new PhoneNumber </li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; AreaCode = hit.Left.Left.Down,</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Prefix = hit.Down.Prefix,</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Body = hit.Down.Body</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });</li>
<li>&nbsp;</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; ParsePhoneNumber = localNumber.Or(longDistanceNumber);</li>
<li>&nbsp;</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; var phoneNumberIgnoringWhitespace = </li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Rep(Ch(' '))</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .And(ParsePhoneNumber)</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .And(Rep(Ch(' ')))</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Build(hit =&gt; hit.Left.Down);</li>
<li>&nbsp;</li>
<li>&nbsp; &nbsp; &nbsp; &nbsp; ParsePhoneNumberList = Rep(phoneNumberIgnoringWhitespace);</li>
<li>&nbsp; &nbsp; }</li>
<li>&nbsp;</li>
<li>&nbsp; &nbsp; public ParseAction&lt;PhoneNumber&gt; ParsePhoneNumber;</li>
<li>&nbsp; &nbsp; public ParseAction&lt;IList&lt;PhoneNumber&gt;&gt; ParsePhoneNumberList;</li>
<li>}&nbsp;</li>
</ol>
<p>The code defines a grammar for parsing phone numbers. The way the grammar is constructed is by building up the patterns describing a valid phone number, starting from the definition of a number and then adding structure to the formatting of the number based on whether the phone number is long distance. Each pattern maps the matched string to the desired object it represents. In the blog post Louis also demonstrates how a grammar can be created to parse XML code. This is actually the basis for the parsing code found in the Spark View Engine which uses XML notation.</p>
<p>I find this approach very interesting and I'm looking forward to seeing how well it will work as a replacement for the Grammatica library I'm currently using. Now I just need to find that extra spare time it requires. If you find this stuff interesting you should definitely go check of Louis' blog post.</p> ]]></description></item><item><title>Making the Most of Your Time</title><link>http://www.without-precedence.dk/blog/26-11-09/making-the-most-of-your-time</link><guid>http://www.without-precedence.dk/blog/26-11-09/making-the-most-of-your-time</guid><pubDate>Thu, 26 Nov 2009 21:01:00 +0100</pubDate><description><![CDATA[

<p>I just wanted to point you to an awesome video that I stumbled across a few days ago. It's a keynote from the &Oslash;redev conference in Sweden and it's held by Scott Hanselman, a blogger on technology and generally just interesting person.</p>
<p>In the video he gives a host of tips and tricks on how to be more effective and &nbsp;efficient with your time and how you process information. The tips include tools for managing information and measuring how much time you spend on unproductive websites during the day as well as techniques for information filtering.</p>
<p>It clocks in at just under an hour but it's well worth the time - and Scott's a great presenter to boot. So <a title="Information Overload and Managing the Flow: Effectiveness and Efficiency" href="http://www.hanselman.com/blog/OredevKeynoteInformationOverloadAndManagingTheFlowEffectivenessAndEfficiency.aspx">go check it out</a>.</p> ]]></description></item><item><title>Learning New Stuff During the Daily Commute</title><link>http://www.without-precedence.dk/blog/12-11-09/learning-new-stuff-during-the-daily-commute</link><guid>http://www.without-precedence.dk/blog/12-11-09/learning-new-stuff-during-the-daily-commute</guid><pubDate>Thu, 12 Nov 2009 13:43:00 +0100</pubDate><description><![CDATA[

<p>Save for those of us who work from home we all have a daily commute, so why not take advantage of that fact and use this time to learn some useful stuff? For quite a while I've been using these daily 2x20 minutes to learn about all sorts of different technologies and tools through the wonderful medium of the podcast. It's just a matter of finding enough interesting shows to provide enough content for your commute. If you have several hours of traveling time each day you might have to look around a bit more, though.</p>
<p>Personally, I have three core shows I follow as well as a couple of others when I'm out of content. They've helped me get to know about all sorts of different technologies I would never have heard of otherwise and to hear other people's perspective on the stuff that I think I know provides tremendous value as well.</p>
<h4>The Stack Overflow Podcast&nbsp;</h4>
<p>The <a title="Stack Overflow Podcast" href="http://blog.stackoverflow.com/category/podcasts/">Stack Overflow podcast</a> is a weekly hour of random chat between the two founders of Stack Overflow, Jeff Atwood and Joel Spolsky. The seriousness and level of actual content varies but its fun and interesting to listen to none the less. It leans a bit more towards entrepreneurial stuff than the other shows as it has been used to document the thoughts and ideas behind the development of the Stack Overflow site itself. They are mostly just the two of them but they occasionally bring in a guest to interview.</p>
<h4>The .NET Rocks! Podcast&nbsp;</h4>
<p>&nbsp;Second, there is the <a title=".NET Rocks" href="http://dotnetrocks.com/default.aspx">.NET Rocks podcast</a> which deals with all things .NET related, each week seeing one or more guests. This show is hosted by Carl Franklin and Richard Campbell, two very experienced and entertaining guys. They are currently at their 498th show, so they know how to handle a technical interview. This show is highly recommended for anyone working with the .NET stack or who are just interested in seeing what it is all about. More exotic topics such as GPU computing, robotics and home automation are also covered.</p>
<h4>Herding Code</h4>
<p><a title="Herding Code" href="http://herdingcode.com/">Herding code</a> is a weekly &nbsp;discussion between K. Scott Allen, Kevin Dente, Scott Koon, and Jon Galloway. They discuss all sorts of interesting technologies with their guests, with no particular technology or company bias. They provide a lot of interesting views on practical things from working in the industry - to a greater degree than other shows with fewer hosts.</p>
<h4>The Rest</h4>
<p>Other interesting shows include <a title="Hanselminutes Podcast" href="http://www.hanselminutes.com/">Hanselminutes</a> and <a title="Spaghetti Code" href="http://feeds2.feedburner.com/SpaghettiCodePodcasts">Spaghetti Code</a> and for a more comprehensive list, <a title="Good Technology Podcasts" href="http://stackoverflow.com/questions/1644/what-good-technology-podcasts-are-out-there">go here</a>.</p> ]]></description></item><item><title>Compiler Series: Introduction</title><link>http://www.without-precedence.dk/blog/03-12-09/compiler-series-introduction</link><guid>http://www.without-precedence.dk/blog/03-12-09/compiler-series-introduction</guid><pubDate>Thu, 03 Dec 2009 15:55:00 +0100</pubDate><description><![CDATA[

<p>I <a title="Creating a DSL Parser in C#" href="/blog/08-11-09/creating-a-dsl-parser-in-c">previously mentioned</a> my interest in a technique for developing a language parser in C#, an interest that has now led to me working on what will be the third implementation of the Card Game Language (CGL). Presently, I have a more or less working compiler that can turn the language into an object model but there is still plenty of work left. Instead of just implementing the compiler and hiding it away in an app, I'm going to try to turn the project into a series of articles explaining the basic principles and most interesting aspects of the implementation. This both serves to educate others as well as forcing me to reflect upon my work and be a bit more thorough in my design efforts.</p>
<p>As with the previous CGL implementation, I'm working towards three specific end products:</p>
<ul class="highlighted">
<li>An improved version of the CGL</li>
<li>A Silverlight environment for executing CGL games</li>
<li>An environment for writing CGL code (Either a Silverlight application or something else)</li>
</ul>
<p>While one of the motivations for the project is simply because its fun, there are a couple of goals I have in mind:</p>
<ul class="highlighted">
<li>Being able to easily change the language, both for the current implementation but also for future work</li>
<li>Make the language simpler, more streamlined and more intuitive (facilitated by the point above)</li>
<li>A richer development experience though intelligent error messages, syntax highlighting and other improvements possible when reimplementing the compiler for the bottom up</li>
<li>Fewer runtime errors due to compile-time type checking</li>
<li>Improved performance (this isn't really needed, but a very nice bonus we get for free)</li>
<li>A reusable tool set for developing future language parsers</li>
<li>A more polished game experience</li>
</ul>
<p>It should be clear that there are a lot of benefits to this new implementation, but also that most of them are to the advantage of the developer and not the players. As the last point states, I plan on polishing up the game graphics and UI to some unknown extend, just to make the whole thing feel new. We don't want to make the mistake they made with Microsoft Calculator in Vista, where they rewrote the guts of the application but 'forgot' to change the UI. The result? No one noticed, and people complained that Microsoft kept shipping the same crufty, old apps.</p>
<p>The first article, which is to follow soon, gives an overview of the language itself and, as such, does not contain any implementation details, but I feel that it is necessary to better understand the big picture, going forward. Links to all the articles will be posted on the <a title="The Card Game Language" href="/projects/the-card-game-language">project page for CGL</a>.</p> ]]></description></item><item><title>Resizer 1.1 - New and Improved</title><link>http://www.without-precedence.dk/blog/18-11-09/resizer-11-new-and-improved</link><guid>http://www.without-precedence.dk/blog/18-11-09/resizer-11-new-and-improved</guid><pubDate>Wed, 18 Nov 2009 13:16:00 +0100</pubDate><description><![CDATA[

<p>I guess it comes as no surprise that when you use half an hour to throw together an application, it won't come across as all that polished. In <a title="Resizer" href="/blog/28-10-09/resizing-images-and-coders-laziness">creating Resizer</a> I failed to miss what was actually a very important feature when creating pictures for uploading to Flickr. The image service has some very neat features for presenting some of the <a title="EXIF" href="http://en.wikipedia.org/wiki/Exif">EXIF</a> information embedded in the image by the camera, including such stats as camera model, exposure time, and ISO. My app just copied the image itself and accidentally ended up discarding all the meta data. Oops.</p>
<p>As other small issues had appeared I figured that I might as well fix them all up and publish the new version.</p>
<p>Version 1.1 changelog:</p>
<ul class="highlighted">
<li>Option for copying all meta data to new image.</li>
<li>Button for setting the active directory to the app directory.</li>
<li>Fixed issue where the jpg extension had to be all lowercase.</li>
<li>Options used are now saved and automatically carried over between each use of the app.</li>
</ul>
<p>As before, you can get the source code to play around with <a title="Resizer Visual Studio Project" href="/files/Resizer.zip">here</a>. If you don't want to compile the code yourself you can get the binary <a title="Resizer App" href="/files/Resizer.exe">here</a>. Enjoy.</p> ]]></description></item><item><title>Compiler Series Part I: An Overview of CGL</title><link>http://www.without-precedence.dk/blog/07-12-09/compiler-series-part-i-an-overview-of-cgl</link><guid>http://www.without-precedence.dk/blog/07-12-09/compiler-series-part-i-an-overview-of-cgl</guid><pubDate>Mon, 07 Dec 2009 15:23:00 +0100</pubDate><description><![CDATA[

<p>This is the first part in a series of articles on implementing a custom .NET compiler for a card game language called CGL. The project page for CGL, and a list of all the articles in the series can be found <a href="/projects/the-card-game-language">here</a>.</p>
<p>For you to get a sense of the project I'm undertaking, i'll start out by stepping through the language. At this point in time the language hasn't been fully implemented so there's bound to be a number of changes to it before the end of this project, but I'll make sure to keep this article up to date as a reference document for anyone wanting to learn the language.</p>
<p>The approach taken in CGL is to describe the structure of a card game, as one would see it if observing the game being played with real cards, with snippets of behavior logic imbedded in different areas. In this sense it actually resembles the structure of an XML document, as the game is built up of a tree structure of areas and piles with a number of attributes.</p>
<p>The first bit of code you will need for any game is a game declaration inside which all the content will go:</p>
<ol class="code">
<li>game:Solitaire</li>
<li>&nbsp;</li>
<li>game</li>
</ol>
<p>All the structural declarations follow this syntax, where the name becomes a variable reference you can use later (this becomes relevant with areas and piles).</p>
<p>The first thing found inside the game declaration must always be the info and the init declarations:</p>
<ol class="code">
<li>game:Solitaire</li>
<li>&nbsp;&nbsp;&nbsp;info "Classic Solitaire game, with one card turned from the pile at a time."</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp;&nbsp;init sourcepile:mainDeck = GetShuffledDeck();</li>
<li>game</li>
</ol>
<p>The info declaration specifies a descriptive string which can be presented to the player of the game and has no impact on the game itself. The init declaration is used to declare source piles to be used during the initialization phase of the game. They simply represent the cards available for the setup of the game, and would typically consist of a single shuffled deck. This is the only point at which cards can be created from nothing, as an important principle of the language is to follow the same restraints as a normal game where cards can't just disappear or appear out of nowhere. This should also serve to make the code easier to follow, and not result in very confused players. The init declaration is actually a block which means that it would normally also end with <span class="mono">init</span>, but some blocks types doesn't need the closing tag if there is only a single statement in the block.</p>
<p>Moving on, we come to our first part of the actual playing setup. To define common logic for a set of related piles, you group them into an area. Areas doesn't have to match any physical or logical layout but they make it easier to define related types of piles. So lets take a look at the code for declaring an area:</p>
<ol class="code">
<li>area:deckArea</li>
<li>&nbsp;&nbsp;&nbsp;Position = {10, 10};</li>
<li>&nbsp;&nbsp;&nbsp;&lt;- mainDeck;</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp;&nbsp;pile:deck</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;CardOffset = {1, 10};</li>
<li>&nbsp;&nbsp;&nbsp;pile</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp;&nbsp;clicked</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// snip</li>
<li>&nbsp;&nbsp;&nbsp;clicked</li>
<li>area</li>
</ol>
<p>This code captures the three types of declarations you can make inside an area: initializers, pile declarations and event handlers. Initializers take the form of property assignments, functions and card movements that apply to all the piles in the area. Property assignments take the form of integer pairs in brackets as they represent positional logic such as pile offsets (between each pile). The arrow <span class="mono">&lt;-</span> is an operator for moving cards from one pile to another. It generally has the form of <span class="mono">target &lt;- source</span> but when used in initializers the target is implicitly resolved. When using the move operator as an area initializer, the cards are distributed across all its piles. Other ways to use the move operator are introduced later in the article.</p>
<p>After any initializers, an area must always have at least one pile declaration, though it needs not have any body as is the case above. Piles can have most of the same types of initializers as areas, though if a property has been specified in both a pile and its parent area, the pile property either takes precedenc or becomes relative to the property on the area. If more than a single initializer is used in the pile declaration, a closing pile tag is required.</p>
<p>Finally, an area can implement one of two event handlers, <span class="mono">clicked</span> and <span class="mono">doubleclicked</span>. They are executed each time the user interacts with pile elements of the area and provides access to the three variables <span class="mono">Hand</span>, <span class="mono">ClickedCard</span> and <span class="mono">ClickedPile</span>. The hand is a virtual pile type that also acts much as a card and is used as a means to select one or more cards for performing some action. The other two variables are just what they seem. A <span class="mono">clicked</span> event handler could look like the following:</p>
<ol class="code">
<li>clicked</li>
<li>&nbsp;&nbsp;&nbsp;if deck.Size != 0</li>
<li>&nbsp;&nbsp;&nbsp;{</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ReturnFromHand();</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;theTurnedCards &lt;- deck : 1;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;theTurnedCards.TopCard.Turn();</li>
<li>&nbsp;&nbsp;&nbsp;}</li>
<li>&nbsp;&nbsp;&nbsp;else</li>
<li>&nbsp;&nbsp;&nbsp;{</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;deck &lt;- 1 &lt;- theTurnedCards;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;deck.Turn();</li>
<li>&nbsp;&nbsp;&nbsp;}</li>
<li>clicked</li>
</ol>
<p>This code checks whether there are any cards left in the clicked pile (In this case <span class="mono">deck</span> and <span class="mono">ClickedPile</span> will always refer to the same instance as there is only one pile in the area). If there are, a single card is moved from the top of the pile to the pile <span class="mono">theTurnedCards</span>. The additional parameter to the move operator <span class="mono">: 1</span> specifies the number of cards to move. The default is just to move all the cards. <span class="mono">ReturnFromHand()</span> takes any cards put into the hand and removes them (Note that they are not actually moved, just no longer registered as being stored in the hand). If the pile is empty, all the cards are returned to the <span class="mono">deck</span> pile and turned backside up. Instead of just moving the pile ordinarily, the optional extra pile operator specifies how many cards to move at a time. In this case we only move a single card at a time, effectively reversing the order of the pile.</p>
<p>If we take a look at the game declaration again we get the full picture of how a game can look:</p>
<ol class="code">
<li>game:Solitaire</li>
<li>&nbsp;&nbsp;&nbsp;info "Classic Solitaire game, with one card turned from the pile at a time."</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp;&nbsp;init sourcepile:mainDeck = GetShuffledDeck();</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp;&nbsp;area:area1</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp;// snip</li>
<li>&nbsp;&nbsp;&nbsp;area</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp;&nbsp;area:area2</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp;// snip</li>
<li>&nbsp;&nbsp;&nbsp;area</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp;&nbsp;end</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp;// snip</li>
<li>&nbsp;&nbsp;&nbsp;end</li>
<li>game</li>
</ol>
<p>As you can see, the game consists of some initializations, a number of areas and something called the <span class="mono">end</span> block. This block contains code that is executed much like the event handlers inside areas. The difference is that it is executed each time another event has finished to determine if the end conditions for the game has been met. There is nothing special about the code that is performed here except that you cannot move cards (This would effectively mean that cards would move themselves, which users would not expect). You just need to call one of the functions&nbsp;<span class="mono">Win()</span> or <span class="mono">Lose()</span> to end the game, as shown below (You might not need a condition for losing, but you should always have a winning condition).</p>
<ol class="code">
<li>end</li>
<li>&nbsp;&nbsp;&nbsp;if hearts.Size + spades.Size + diamonds.Size + clubs.Size == 52</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;win();</li>
<li>end</li>
</ol>
<p>The philosophy behind the executing code in event handlers and the end block is to keep it as simple and readable as possible and stay close to the concepts of real card games. I want the developer to be thinking in terms of how he would play the game and it should be easy to identify what parts of the game rules a specific line of code represents. Because of these requirements you will find that common operations and control structures are not included in the language such as local variables and looping control flow. Hopefully, all the places you would need these types of constructs, I have managed to create functions and operators that can replace them. The truth is, only through creating many, many card games would I know if this is the case, and I may be forced to introduce them again (the examples both existed in the previous version of CGL, but I found no need for them to stay).</p>
<p>An interesting feature of the language that I haven't found anywhere else (hopefully not for a good reason) is the ability to write the following and having it evaluate as you would logically think:</p>
<ol class="code">
<li>if 10 &lt; deck.Size &lt; 20</li>
<li>&nbsp;</li>
<li>// Equivalent C# version</li>
<li>if (10 &lt; deck.Size &amp;&amp; deck.Size &lt; 20)</li>
</ol>
<p>I can't count the number of times that I've cursed other languages for not working this way, so I'm happy to introduce the feature into CGL. It's not that I've actually found a need for it in the language, I just couldn't let the opportunity pass by :) Of course, changing the behavior of known constructs and introducing new operators such as the move operator all makes it harder for people to get into the language, but I hope they prove to be worthwhile. After all, you only have to learn them once but can benefit from them countless times, thereafter.</p>
<p>This should cover the structure of a game and the only thing missing, except perhaps for some semantic details here and there, is a reference documentation for all the properties and functions supported. These are still a bit into the air right now, so I won't add them here but when they're done I'll put them up in their own document and link to them.</p>
<p>Resources:</p>
<ul>
<li>The <a href="/files/gypsy.cgl">source code</a> for a simple solitaire game I've invented, called Gypsy Eye</li>
<li>Solitaire terminology: <a href="http://en.wikipedia.org/wiki/Solitaire_terminology">http://en.wikipedia.org/wiki/Solitaire_terminology</a></li>
<li>List of solitaire games: <a href="http://en.wikipedia.org/wiki/List_of_solitaire_card_games">http://en.wikipedia.org/wiki/List_of_solitaire_card_games</a></li>
</ul>
<p>In the next article we'll take a look at how to put together a grammar and parse a piece of source code.</p> ]]></description></item><item><title>Compiler Series Part II: Compiler Basics</title><link>http://www.without-precedence.dk/blog/25-12-09/compiler-series-part-ii-compiler-basics</link><guid>http://www.without-precedence.dk/blog/25-12-09/compiler-series-part-ii-compiler-basics</guid><pubDate>Fri, 25 Dec 2009 23:08:00 +0100</pubDate><description><![CDATA[

<p>This is the second part in a series of articles on implementing a custom .NET compiler for a card game language called CGL. The project page for CGL, and a list of all the articles in the series can be found <a title="The Card Game Language" href="/projects/the-card-game-language">here</a>.</p>
<p><img class="center" title="Coffee mug" src="http://without-precedence.dk/images/blog/mug.jpg" alt="Coffee mug" width="450" height="166" /></p>
<p>In this article I'll introduce the concepts used as building blocks for the compiler and how they can be composed to match complex textual patterns. At the end of this article we'll be able to parse ordered bits of text and turn them into managed objects.</p>
<p>There are a number of ways to approach creating a compiler, but the one we'll be exploring here is a simple recursive decent parser where the grammar for the language is encoded in C# code rather than being described using formats such as EBNF. This is not really a theoretical series so I won't be going into detail on the type of compiler or discuss topics such as formal semantics, just the practical bits.</p>
<p>The main concept I'm building my compiler around is a delegate for parsing source code which returns a parse result of an arbitrary C# type. A number of these can then be composed together to match complex patterns and create a whole object graph. This concept is not something I've invented myself, it's based on a blog post by Louis DeJardin, the guy behind the Spark View Engine for ASP.NET MVC. This post is very similar to Louis', which can be found <a title="Creating a Domain Specific Language for Parsing" href="http://whereslou.com/2008/05/15/creating-a-domain-specific-language-for-parsing">here</a>, but in the next article and forward we use it for our own specialized grammar.</p>
<p>To get started we'll define the interfaces of the basic concepts we're going to need:</p>
<ol class="code">
<li>public delegate ParseResult&lt;TValue&gt; ParseAction&lt;TValue&gt;(Position position);</li>
<li>&nbsp;</li>
<li>public class ParseResult&lt;TValue&gt;</li>
<li>{</li>
<li>&nbsp;&nbsp; &nbsp;public Position Rest { get; }</li>
<li>&nbsp;&nbsp; &nbsp;public TValue Value { get; }</li>
<li>&nbsp;&nbsp; &nbsp;public ParseError Error { get; }</li>
<li>}</li>
<li>&nbsp;</li>
<li>public class Position</li>
<li>{</li>
<li>&nbsp;&nbsp; &nbsp;public int Line { get; }</li>
<li>&nbsp;&nbsp; &nbsp;public int Column { get; }</li>
<li>&nbsp;&nbsp; &nbsp;public string Context { get; }</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp; &nbsp;public char Peek();</li>
<li>&nbsp;&nbsp; &nbsp;public string Peek(int length);</li>
<li>&nbsp;&nbsp; &nbsp;public Position Advance(int offset);</li>
<li>}</li>
<li>&nbsp;</li>
<li>public class ParseError</li>
<li>{</li>
<li>&nbsp;&nbsp; &nbsp;public int Line { get; }</li>
<li>&nbsp;&nbsp; &nbsp;public int Column { get; }</li>
<li>&nbsp;&nbsp; &nbsp;public string Message { get; }</li>
<li>}<span style="font-family: 'Segoe UI', 'Trebuchet MS', Arial, Helvetica, sans-serif; font-size: small; line-height: normal;">&nbsp;</span></li>
</ol>
<p>The <span class="mono">ParseAction</span> delegate is a function which, given a position in the source code, yields either a result of the generic type or a parse error if the pattern did not match. The result of the parser is stored in a <span class="mono">ParseResult</span> object which hold either of the possible outcomes. It also contains the position in the source code where a subsequent parser would start off from. The <span class="mono">Position</span> object is an immutable description of a point in the source code and it can potentially wrap a source that is more complex than a string if needed.</p>
<p>Using these classes we can begin to create a <span class="mono">Grammar</span> class where we define the most basic patterns we want to match.</p>
<ol class="code">
<li><span style="line-height: normal;">public class Grammar</span></li>
<li><span style="line-height: normal;">{</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp;public static ParseAction&lt;char&gt; Ch(char match)</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp;{</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;return delegate(Position input)</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;{</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (input.Peek() == match)</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return new ParseResult&lt;char&gt;(input.Advance(1), match);</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return new ParseResult&lt;char&gt;("Encountered unexpected char", input.Line, input.Column);</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;};</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp;}</span></li>
<li><span style="line-height: normal;">&nbsp;</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; public static ParseAction&lt;IList&lt;TValue&gt;&gt; Rep&lt;TValue&gt;(ParseAction&lt;TValue&gt; parser)</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp;{</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;return delegate(Position input)</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;{</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Position rest = input;</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;List&lt;TValue&gt; list = new List&lt;TValue&gt;();</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;var results = new List&lt;ParseResult&lt;TValue&gt;&gt;();</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;results.Add(parser(input));</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;while (!results.Last().HasError)</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;list.Add(results.Last().Value);</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;rest = results.Last().Rest;</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;results.Add(parser(rest));</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return new ParseResult&lt;IList&lt;TValue&gt;&gt;(rest, list);</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;};</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp;}</span></li>
<li><span style="line-height: normal;">&nbsp;</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp;public static ParseAction&lt;TValue&gt; Or&lt;TValue&gt;(ParseAction&lt;TValue&gt; parser1, ParseAction&lt;TValue&gt; parser2)</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp;{</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;return delegate(Position input)</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;{</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;var result1 = parser1(input);</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (result1.HasError) return parser2(input);</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return result1;</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;};</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp;}</span></li>
<li><span style="line-height: normal;">&nbsp;</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; public static ParseAction&lt;Chain&lt;TValue1, TValue2&gt;&gt; And&lt;TValue1, TValue2&gt;(ParseAction&lt;TValue1&gt; parser1, ParseAction&lt;TValue2&gt; parser2)</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp;{</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp;return delegate(Position input)</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;{</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;var result1 = parser1(input);</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (result1.HasError)</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return new ParseResult&lt;Chain&lt;TValue1, TValue2&gt;&gt;(result1.Error);</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;var result2 = parser2(result1.Rest);</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (result2.HasError)</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return new ParseResult&lt;Chain&lt;TValue1, TValue2&gt;&gt;(result2.Error);</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;var value = new Chain&lt;TValue1, TValue2&gt;(result1.Value, result2.Value);</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return new ParseResult&lt;Chain&lt;TValue1, TValue2&gt;&gt;(result2.Rest, value);</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;};</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp;}</span></li>
<li><span style="line-height: normal;">}</span></li>
</ol>
<p>Each of the above methods generate a <span class="mono">ParseAction</span> for a specific, useful purpose. The first matches a specific <span class="mono">char</span> while <span class="mono">Rep</span> matches a repeated sequence of a pattern. Using these, we can write the following code (I've removed the references to the <span class="mono">Grammar</span> class from the method calls to simplify the example):</p>
<ol class="code">
<li><span style="line-height: normal;">var parseChar = Ch('c');</span></li>
<li><span style="line-height: normal;">var parseChars = Rep(parseChar);</span></li>
<li><span style="line-height: normal;">&nbsp;</span></li>
<li><span style="line-height: normal;">var result1 = parseChar(new Position("c"));</span></li>
<li><span style="line-height: normal;">var result2 = parseChars(new Position("cccc"));</span></li>
</ol>
<p>As you can see, we used one parser to create another. The <span class="mono">Rep</span> function keeps using the <span class="mono">Ch('c')</span> parser to match characters, which it stuffs into a <span class="mono">List&lt;char&gt;</span>. The methods <span class="mono">Or</span> and <span class="mono">And</span> does the same for matching one pattern or another, or one pattern followed by another, respectively. As a side note, you can see that I have supplied none of the type arguments for the generic function. This is because of the powerful type inference capability of the C# compiler.</p>
<ol class="code">
<li><span style="line-height: normal;">var parseAnotherChar = Ch('k');</span></li>
<li><span style="line-height: normal;">var parseEitherChar = Rep(Or(parseChar, parseAnotherChar));</span></li>
<li><span style="line-height: normal;">var parseBothChars = Rep(And(parseChar, parseAnotherChar));</span></li>
<li><span style="line-height: normal;">&nbsp;</span></li>
<li><span style="line-height: normal;">var result1 = parseEitherChar(new Position("kkkckckc"));</span></li>
<li><span style="line-height: normal;">var result2 = parseBothChars(new Position("ckckckckck"));&nbsp;</span></li>
</ol>
<p>Here, we define two parsers that matches series of characters. The one using <span class="mono">Or</span> matches a sequence where each <span class="mono">char</span> can either be <span class="mono">c</span>&nbsp;or <span class="mono">k</span> where the one using <span class="mono">And</span> matches only sequences of <span class="mono">c</span>s followed by a <span class="mono">k</span>. To end up with more fluent code, we can define a few useful extension methods:</p>
<ol class="code">
<li><span style="line-height: normal;">public static class GrammarExtensions</span></li>
<li><span style="line-height: normal;">{</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp;public static ParseAction&lt;TValue&gt; Or&lt;TValue&gt;(this ParseAction&lt;TValue&gt; parser1, ParseAction&lt;TValue&gt; parser2)</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp;{</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;return Grammar.Or(parser1, parser2);</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp;}</span></li>
<li><span style="line-height: normal;">&nbsp;</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp;public static ParseAction&lt;Chain&lt;TValue1, TValue2&gt;&gt; And&lt;TValue1, TValue2&gt;(this ParseAction&lt;TValue1&gt; parser1, ParseAction&lt;TValue2&gt; parser2)</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp;{</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;return Grammar.And(parser1, parser2);</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp;}</span></li>
<li><span style="line-height: normal;">}</span></li>
<li><span style="line-height: normal;">&nbsp;</span></li>
<li><span style="line-height: normal;">// Allows for the following</span></li>
<li><span style="line-height: normal;">var parseEitherChar = Rep(parseChar.Or(parseAnotherChar));</span></li>
<li><span style="line-height: normal;">var parseBothChars = Rep(parseChar.And(parseAnotherChar));</span></li>
</ol>
<p>As you might have noticed, the <span class="mono">And</span> parser returns an object of the type <span class="mono">Chain</span>. This is simply a container for the results of the two parse actions. However, it introduces the problem of creating increasingly complex result types as your parsers become more complex. To reduce this problem we introduce the <span class="mono">Build</span> function which translates a complex result into a simpler one. It basically just takes the result of a parser and applies a function to it.</p>
<ol class="code">
<li><span style="line-height: normal;">public static ParseAction&lt;TValue2&gt; Build&lt;TValue1, TValue2&gt;(ParseAction&lt;TValue1&gt; parser, Func&lt;TValue1, TValue2&gt; builder)</span></li>
<li><span style="line-height: normal;">&nbsp;{</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp;return delegate(Position input)</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp;{</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;var result = parser(input);</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;if (result.HasError) return new ParseResult&lt;TValue2&gt;(result.Error);</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;try</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;{</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return new ParseResult&lt;TValue2&gt;(result.Rest, builder(result.Value));</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;}</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;catch (ParseException e)</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;{</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return new ParseResult&lt;TValue2&gt;(e.Message, input.Line, input.Column);</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }</span></li>
<li><span style="line-height: normal;">&nbsp;&nbsp; &nbsp;};</span></li>
<li><span style="line-height: normal;">}</span></li>
<li><span style="line-height: normal;">&nbsp;</span></li>
<li><span style="line-height: normal;">var parseBothChars = And(parseChar, parseAnotherChar).Build(hit =&gt; hit.Left + hit.Down);&nbsp;</span></li>
</ol>
<p>In this case, we use <span class="mono">Build</span> to change the result type from <span class="mono">Chain&lt;char,char&gt;</span> to <span class="mono">string</span>. Once again, the type inferral of the C# compiler comes to our rescue, providing us with proper intellisense on the properties on the <span class="mono">Chain</span> object. This will save your sanity when building from more complex chains. Also notice that we catch <span class="mono">ParseException</span> errors, a custom exception type which we can use to signal that some parse rule was broken when trying to build the object.</p>
<p>These, and more, are common building blocks for any grammar and, therefore, our primary job is now to create a <span class="mono">Grammar</span> class which holds all the basic parsers. To create a more specialized grammar you simply inherit from <span class="mono">Grammar</span> and add new parsers.</p>
<p>We're getting to the end of this article but hopefully you got the idea of how this all works. If not, I urge you to go read up on Louis' blog on the same topic. I've also <a title="Compiler Series Part II Code" href="/files/compiler-series/part2-code.zip">uploaded some of the code</a> from my compiler so you can see some of the other parsers to put in the <span class="mono">Grammar</span> class. The code won't compile as it relies on some other code of mine, but it should be possible to understand it regardless.</p>
<p>In the next article we'll begin to create a more specialized grammar for the CGL language using the building blocks presented here.</p> ]]></description></item><item><title>Writing Clean Code</title><link>http://www.without-precedence.dk/blog/09-01-10/writing-clean-code</link><guid>http://www.without-precedence.dk/blog/09-01-10/writing-clean-code</guid><pubDate>Sat, 09 Jan 2010 18:19:00 +0100</pubDate><description><![CDATA[

<p>Every once in a while, you come across a book that really resonates with you. For me, this recently happened with the book&nbsp;<a title="Clean Code: A Handbook of Agile Software Craftsmanship" href="http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/">Clean Code: A Handbook of Agile Software Craftsmanship</a>, by Robert C. Martin and Co. The book is all about recognizing, writing and modifying readable and maintainable code, from an agile perspective with a particular focus on tests and test-driven development. The message it brings is quite simple: <em>It is not enough to create working code in order to succeed in the long run, you need to build high quality software or be crushed under the weight of code that is hard if not impossible to modify and maintain.</em> The proposed solution is a series of craftsmanship principles and best practices, backed by plenty of examples.</p>
<p><img style="float: right; margin-left: 5px; margin-top:0px;" title="Clean Code cover" src="http://without-precedence.dk/images/blog/cleancode.jpg" alt="Clean Code cover" width="162" height="215" /> Clean Code is one of the best programming books I've read in a long while. It is based on many of the same guiding principles I have for software development, such as the central role of readable code and the need to continually improve yourself as a craftsman, beyond the standard requirements of your job.</p>
<p>Some of the practices presented in the book weren't new to me and, indeed, some of them were a bit too idealistic, but apart from that it was truly an insightful read.</p>
<p>One of the more eye opening concepts was a way to write code so that it can be read much like you would read a newspaper. The first step in this process is to separate your code into lots of small functions. Essentially there should be no functions larger than about 4 lines and they should do one thing and one thing only. This thing should be captured accurately and unambiguously in the function name. A function should read like a sentence - <em>to do x</em> (the function name), <em>you must&nbsp;</em><em>do a, b and c</em><em>&nbsp;</em>(lines of code). Note that it is important that the contents of the function should be at the same level of abstraction and that this level of abstraction should be one level lower than that of the function name. The point to all of this is to make it trivially easy to see what a function does. Consider the following code I recently wrote for resizing images:</p>
<ol class="code">
<li>public enum ResizeStrategy</li>
<li>{</li>
<li>&nbsp;&nbsp; &nbsp;Stretch,</li>
<li>&nbsp;&nbsp; &nbsp;BestFit,</li>
<li>}</li>
<li>&nbsp;</li>
<li>public static class ImageFormatter</li>
<li>{</li>
<li>&nbsp;&nbsp; &nbsp;public static Image ScaleImage(Image originalBitmap, int maxDimension)</li>
<li>&nbsp;&nbsp; &nbsp;{</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;float aspectX = maxDimension / (float)originalBitmap.Width;</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;float aspectY = maxDimension / (float)originalBitmap.Height;</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;float actualAspect = Math.Min(aspectX, aspectY);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;int sourceWidth = (int)(originalBitmap.Width * actualAspect);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;int sourceHeight = (int)(originalBitmap.Height * actualAspect);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;var resized = new Bitmap(sourceWidth, sourceHeight);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;Graphics g = Graphics.FromImage(resized);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;g.DrawImage(originalBitmap, new Rectangle(0, 0, resized.Width, resized.Height));</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;return resized;</li>
<li>&nbsp;&nbsp; &nbsp;}</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp; &nbsp;public static Image ScaleImage(Image originalImage, float scale)</li>
<li>&nbsp;&nbsp; &nbsp;{</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;int width = (int)(originalImage.Width * scale);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;int height = (int)(originalImage.Height * scale);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;var resized = new Bitmap(width, height);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;Graphics g = Graphics.FromImage(resized);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;g.DrawImage(originalImage, new Rectangle(0, 0, resized.Width, resized.Height));</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;return resized;</li>
<li>&nbsp;&nbsp; &nbsp;}</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp; &nbsp;public static Image ScaleImage(Image originalImage, float scaleWidth, float scaleHeight)</li>
<li>&nbsp;&nbsp; &nbsp;{</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;int width = (int)(originalImage.Width * scaleWidth);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;int height = (int)(originalImage.Height * scaleHeight);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;var resized = new Bitmap(width, height);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;Graphics g = Graphics.FromImage(resized);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;g.DrawImage(originalImage, new Rectangle(0, 0, resized.Width, resized.Height));</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;return resized;</li>
<li>&nbsp;&nbsp; &nbsp;}</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp; &nbsp;public static Image ResizeImage(Image originalImage, int width, int height, ResizeStrategy thumbnailFormat)</li>
<li>&nbsp;&nbsp; &nbsp;{</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;Image thumbnail = new Bitmap(width, height);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;switch (thumbnailFormat)</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;{</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;case ResizeStrategy.Stretch:</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;RenderStretchedThumbnail(originalImage, thumbnail);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;break;</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;case ResizeStrategy.BestFit:</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;RenderBestFitThumbnail(originalImage, thumbnail);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;break;</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;default:</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;throw new ArgumentException("Thumbnail format not valid");</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;}</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;return thumbnail;</li>
<li>&nbsp;&nbsp; &nbsp;}</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp; &nbsp;private static void RenderBestFitThumbnail(Image originalImage, Image thumbnail)</li>
<li>&nbsp;&nbsp; &nbsp;{</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;float aspectX = thumbnail.Width / (float)originalImage.Width;</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;float aspectY = thumbnail.Height / (float)originalImage.Height;</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;float actualAspect = Math.Max(aspectX, aspectY);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;int sourceWidth = (int)(thumbnail.Width / actualAspect);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;int sourceHeight = (int)(thumbnail.Height / actualAspect);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;Graphics g = Graphics.FromImage(thumbnail);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;g.DrawImage(originalImage, new Rectangle(0, 0, thumbnail.Width, thumbnail.Height), new Rectangle(0, 0, sourceWidth, sourceHeight), GraphicsUnit.Pixel);</li>
<li>&nbsp;&nbsp; &nbsp;}</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp; &nbsp;private static void RenderStretchedThumbnail(Image originalImage, Image thumbnail)</li>
<li>&nbsp;&nbsp; &nbsp;{</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;Graphics g = Graphics.FromImage(thumbnail);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;g.DrawImage(originalImage, 0, 0, thumbnail.Width, thumbnail.Height);</li>
<li>&nbsp;&nbsp; &nbsp;}</li>
<li>}</li>
</ol>
<p>I don't consider this code bad in any particular way, but lets see what happens if we rewrite it, using the above guidelines:</p>
<ol class="code">
<li>public enum ResizeStrategy</li>
<li>{</li>
<li>&nbsp;&nbsp; &nbsp;Stretch,</li>
<li>&nbsp;&nbsp; &nbsp;BestFit</li>
<li>}</li>
<li>&nbsp;</li>
<li>public class ImageFormatter</li>
<li>{</li>
<li>&nbsp;&nbsp; &nbsp;private Image _workingImage;</li>
<li>&nbsp;&nbsp; &nbsp;private Image _originalImage;</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp; &nbsp;public Image ResizeImage(Image originalImage, int width, int height, ResizeStrategy resizeStrategy)</li>
<li>&nbsp;&nbsp; &nbsp;{</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;_originalImage = originalImage;</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;PrepareImage(width, height);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;switch (resizeStrategy)</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;{</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;case ResizeStrategy.Stretch:</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;RenderStretchedImage();</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;break;</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;case ResizeStrategy.BestFit:</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;RenderBestFitThumbnail();</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;break;</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;default:</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;throw new ArgumentException("Thumbnail format not valid");</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;}</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;return _workingImage;</li>
<li>&nbsp;&nbsp; &nbsp;}</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp; &nbsp;private void PrepareImage(int width, int height)</li>
<li>&nbsp;&nbsp; &nbsp;{</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;_workingImage = new Bitmap(width, height);</li>
<li>&nbsp;&nbsp; &nbsp;}</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp; &nbsp;private void RenderStretchedImage()</li>
<li>&nbsp;&nbsp; &nbsp;{</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;Graphics g = Graphics.FromImage(_workingImage);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;g.DrawImage(_originalImage, GetTargetDrawingRectangle());</li>
<li>&nbsp;&nbsp; &nbsp;}</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp; &nbsp;private Rectangle GetTargetDrawingRectangle()</li>
<li>&nbsp;&nbsp; &nbsp;{</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;return new Rectangle(0, 0, _workingImage.Width, _workingImage.Height);</li>
<li>&nbsp;&nbsp; &nbsp;}</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp; &nbsp;private void RenderBestFitThumbnail()</li>
<li>&nbsp;&nbsp; &nbsp;{</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;float scale = CalculateMaximumScaleNotCroppingBothDimensions();</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;Rectangle source = CalculateRectangleFromScaledWorkingImage(scale);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;RenderPartialImage(source);</li>
<li>&nbsp;&nbsp; &nbsp;}</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp; &nbsp;private float CalculateMaximumScaleNotCroppingBothDimensions()</li>
<li>&nbsp;&nbsp; &nbsp;{</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;float xScale = _workingImage.Width / (float)_originalImage.Width;</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;float yScale = _workingImage.Height / (float)_originalImage.Height;</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;return Math.Max(xScale, yScale);</li>
<li>&nbsp;&nbsp; &nbsp;}</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp; &nbsp;private Rectangle CalculateRectangleFromScaledWorkingImage(float scale)</li>
<li>&nbsp;&nbsp; &nbsp;{</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;int width = (int)(_workingImage.Width / scale);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;int height = (int)(_workingImage.Height / scale);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;return new Rectangle(0, 0, width, height);</li>
<li>&nbsp;&nbsp; &nbsp;}</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp; &nbsp;private void RenderPartialImage(Rectangle source)</li>
<li>&nbsp;&nbsp; &nbsp;{</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;Graphics g = Graphics.FromImage(_workingImage);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;g.DrawImage(_originalImage, GetTargetDrawingRectangle(), source, GraphicsUnit.Pixel);</li>
<li>&nbsp;&nbsp; &nbsp;}</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp; &nbsp;public Image ResizeImage(Image originalImage, int maxDimension)</li>
<li>&nbsp;&nbsp; &nbsp;{</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;_originalImage = originalImage;</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;float scale = CalculateScaleForFixedMaxDimension(maxDimension);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;return ScaleImage(originalImage, scale);</li>
<li>&nbsp;&nbsp; &nbsp;}</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp; &nbsp;private float CalculateScaleForFixedMaxDimension(int lengthOfMaxDimension)</li>
<li>&nbsp;&nbsp; &nbsp;{</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;float xScale = lengthOfMaxDimension / (float)_originalImage.Width;</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;float yScale = lengthOfMaxDimension / (float)_originalImage.Height;</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;return Math.Min(xScale, yScale);</li>
<li>&nbsp;&nbsp; &nbsp;}</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp; &nbsp;public Image ScaleImage(Image originalImage, float scale)</li>
<li>&nbsp;&nbsp; &nbsp;{</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;_originalImage = originalImage;</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;PrepareScaledImage(scale);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;RenderStretchedImage();</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;return _workingImage;</li>
<li>&nbsp;&nbsp; &nbsp;}</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp; &nbsp;private void PrepareScaledImage(float scale)</li>
<li>&nbsp;&nbsp; &nbsp;{</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;int width = (int)(_originalImage.Width * scale);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;int height = (int)(_originalImage.Height * scale);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;_workingImage = new Bitmap(width, height);</li>
<li>&nbsp;&nbsp; &nbsp;}</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp; &nbsp;public Image ScaleImage(Image originalImage, float widthScale, float heightScale)</li>
<li>&nbsp;&nbsp; &nbsp;{</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;_originalImage = originalImage;</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;PrepareScaledImage(widthScale, heightScale);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;RenderStretchedImage();</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;return _workingImage;</li>
<li>&nbsp;&nbsp; &nbsp;}</li>
<li>&nbsp;</li>
<li>&nbsp;&nbsp; &nbsp;private void PrepareScaledImage(float widthScale, float heightScale)</li>
<li>&nbsp;&nbsp; &nbsp;{</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;int width = (int)(_originalImage.Width * widthScale);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;int height = (int)(_originalImage.Height * heightScale);</li>
<li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;_workingImage = new Bitmap(width, height);</li>
<li>&nbsp;&nbsp; &nbsp;}</li>
<li>}</li>
</ol>
<p>One of the first thing you might notice is that the code has grown from 75 lines to 117. This is just a price you have to pay, but I believe that readability should almost always outweigh brevity.</p>
<p>In the first method, I violate the principle of function size, but that is, unfortunately, necessary when using switch statements. You'll notice that the actions performed in the function is relegated to other functions, which is the main way this technique requires code to be structured.</p>
<p>The functions are topologically sorted, such that a given function is directly followed by the functions used in its body, which again are followed by their own dependencies, etc. Think of it as a stack that, as you read through the file, pushes the most relevant functions to the top as needed. Thus, the first <span class="mono">ResizeImage</span> function is followed by the function <span class="mono">PrepareImage</span>, which is its first dependency. If this function had had any dependencies, they would have followed immediately after before continuing with the dependencies of&nbsp;<span style="color: #ffffff; font-family: consolas, monospace; font-weight: bold;">ResizeImage<span style="color: #cccccc; font-family: 'Segoe UI', 'Trebuchet MS', Arial, Helvetica, sans-serif; font-weight: normal;">.</span></span></p>
<p>Apart from creating a very literate piece of code, the transformation also revealed a few cases of repeated code which was turned into reusable functions. Where before I might not have bother with looking for such similarities in the code, it becomes more obvious when splitting everything into its essential parts.</p>
<p>When I read about this approach, it struct me as a very clever way to structure your code, but there are a few caveats that I'm not too sure about, yet. I find that the resulting code can be a bit overwhelming to look at as its structure has become more homogeneous and, as mentioned above, there are just more lines of code to read. It might help, though, if the IDE would highlight the public functions, so you could quickly navigate to the part of the code you need. Regardless of these issues, I find the approach very interesting and I'm looking forward to seeing how well it works for me.</p>
<p>If you found the technique interesting, I'm sure you'll love the book, as it's filled with little nuggets like this.</p> ]]></description></item><item><title>Resizer 1.2 - More Goodness</title><link>http://www.without-precedence.dk/blog/27-12-09/resizer-12-more-goodness</link><guid>http://www.without-precedence.dk/blog/27-12-09/resizer-12-more-goodness</guid><pubDate>Sun, 27 Dec 2009 11:59:00 +0100</pubDate><description><![CDATA[

<p>Once again, I've felt the need to upgrade my <a title="Resizing Images and Coder's Laziness" href="/blog/28-10-09/resizing-images-and-coders-laziness">image resizing application</a>, and I present to you version 1.2! The app seems to follow a natural evolution as I come up with more and more requirements for it, this time because I decided to put more images into my blog posts. These images must be no wider than 450 pixels so I thought it would be useful to have a feature specifying which dimension to resize after, instead of it being the biggest dimension.</p>
<p><img class="center" title="A totally unrelated plant" src="/images/blog/plant.jpg" alt="A totally unrelated plant" width="450" height="223" /></p>
<p>Version 1.2 changelog:</p>
<ul class="highlighted">
<li>Added options for setting length of the minimum, vertical and horizontal dimensions, instead of just the maximum dimension.</li>
<li>The resizing work is now done in a background thread making the UI responsive while working.</li>
<li>Added support of cancelling work.</li>
<li>Removed a bug preventing the progress bar from being updated properly.</li>
</ul>
<p>Recently, I've been very interested in architectural patterns for improving modularity, testability and other such desirable properties. The Model View Presenter pattern (The Supervising Controller variant) is one of these, and after reading an introduction to it <a title="ASP.NET Supervising Controller (Model View Presenter) From Schematic To Unit Tests to Code" href="http://haacked.com/archive/2006/08/09/ASP.NETSupervisingControllerModelViewPresenterFromSchematicToUnitTestsToCode.aspx">by Phil Haack</a>, I've been playing around with it for the GUI of my <a title="Compiler Series: Introduction" href="/blog/03-12-09/compiler-series-introduction">card game compiler</a>. It provides a great way to keep the UI classes very thin and only deal with UI business, allowing us to maintain the single responsibility principle.</p>
<p>While it was hardly necessary, I implemented the MVP pattern for the single view in the Resizer app but I'm beginning to get the feeling that it will grow a lot in the future.</p>
<p>For those who are interested in architecting better apps, the&nbsp;<a title="Patterns For Building Composite Applications With WPF" href="http://msdn.microsoft.com/en-us/magazine/cc785479.aspx">Composite Application Guidance for WPF</a> (Code named Prism) is also a good read. Actually, it's more than just guidance, it's also a library that can help you get up to speed on these practices in no time and it includes very helpful code samples for all the important points. The project comes out of the <a title="Microsoft Patterns &amp; Practices" href="http://msdn.microsoft.com/en-us/practices/default.aspx">Microsoft Patterns &amp; Practices department</a> which provides guidance for all sorts of .NET development.</p>
<p>As usual, you can get the source code <a title="Resizer Source" href="/files/Resizer.zip">here</a> and the binary <a title="Resizer binary" href="/files/Resizer.exe">here</a>.</p> ]]></description></item><item><title>CGS Version 3.0</title><link>http://www.without-precedence.dk/blog/27-01-10/cgs-version-30</link><guid>http://www.without-precedence.dk/blog/27-01-10/cgs-version-30</guid><pubDate>Wed, 27 Jan 2010 22:51:00 +0100</pubDate><description><![CDATA[

<p>I've been meaning to continue my compiler series for a few weeks, but performance issues and general doubt about how best to structure the code has resulted in some delays. I suppose I'm also guilty of jumping forward to the fun bits and as a result I've finished a version of the Card Game Simulator using the compiler. As it stands, it's version 3.0 but I'll incrementally add more features and card games as I move forward (Currently, I'm adding the functionality required to support the game Spider).</p>
<p><img class="center" title="CGS Menu" src="http://without-precedence.dk/images/blog/cgs_menu.jpg" alt="CGS Menu" width="400" height="185" /></p>
<p>Apart from having it's guts totally replaced, the application has also recieved a graphical overhaul. It now features more and better animations and a new card design. The cards look a bit similar at the moment but I'll be making them a more distinguishable in the future. I'm still trying to figure out the best way to represent the face cards without ruining the style. As you can see I'm going for a worn, kind of old school look.</p>
<p><img class="center" title="CGS Cards" src="http://without-precedence.dk/images/blog/cgs_cards.jpg" alt="CGS Cards" width="400" height="195" /></p>
<p>You can try out the new version <a title="Card Game Simulator 3.0" href="http://without-precedence.dk/apps/card-game-simulator-3-0">here</a>. If you feel like it, you can also compare and contrast with <a title="Card Game Simulator 2" href="http://without-precedence.dk/apps/card-game-simulator">the old version 2</a>. As I mentioned, there are some performance issues with the new version and it actually loads games much slower than the old one. It appears that the strategy I'm using for the compiler is not very efficient and it already begins to show when compiling games of a few hundred lines of code, possibly due the massive amounts of recursion or the heavy use of reflection. When time permits, I'll scour the web for a good profiler and see if it seems fixable.</p> ]]></description></item></channel></rss>