<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

<title>aboutcode.net</title>
<link href="http://aboutcode.net/feed.atom" rel="self"/>
<link href="http://aboutcode.net/"/>
<updated>2014-06-11T02:12:54-07:00</updated>
<id>http://aboutcode.net/</id>
<author>
<name>Andrew Davey</name>
<email>andrew@equin.co.uk</email>
</author>


<entry>
<title>Automating Chrome on Windows with JavaScript using Selenium's WebDriverJS</title>
<link href="http://aboutcode.net/2013/12/02/automating-chrome-on-windows-with-javascript-using-selenium-webdriverjs.html"/>
<updated>2013-12-02T00:00:00-08:00</updated>
<id>http://aboutcode.net/2013/12/02/automating-chrome-on-windows-with-javascript-using-selenium-webdriverjs</id>
<content type="html">&lt;p&gt;
To test my web application, I&#39;m using web browser automation.
Getting this set up on Windows took a bit of trial and error, 
so I&#39;ve documented the process for future reference.
&lt;/p&gt;

&lt;p&gt;
Here&#39;s the list of tools you&#39;ll need to get up and running:
&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Java&lt;/li&gt;
  &lt;li&gt;Selenium&lt;/li&gt;
  &lt;li&gt;Chromedriver&lt;/li&gt;
  &lt;li&gt;NodeJS&lt;/li&gt;
  &lt;li&gt;selenium-webdriver via npm&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;Installing the tools&lt;/h2&gt;

&lt;p&gt;
Selenium runs on Java, so if you don&#39;t it installed yet, download it from 
&lt;a target=&quot;_blank&quot; href=&quot;http://www.java.com/en/download/manual.jsp&quot;&gt;http://www.java.com/en/download/manual.jsp&lt;/a&gt;.
&lt;/p&gt;

&lt;p&gt;
Check that Java is installed, by running the following from a command prompt:
&lt;/p&gt;
&lt;pre&gt;c:\&amp;gt;java -version&lt;/pre&gt;

&lt;p&gt;Here&#39;s what I get:&lt;/p&gt;

&lt;pre&gt;C:\Users\andrew&amp;gt;java -version
java version &quot;1.7.0_45&quot;
Java(TM) SE Runtime Environment (build 1.7.0_45-b18)
Java HotSpot(TM) 64-Bit Server VM (build 24.45-b08, mixed mode)
&lt;/pre&gt;

&lt;p&gt;
Next, you need to get Selenium.
It&#39;s enough to simply download the &quot;selenium-server-standalone&quot; jar file from
&lt;a target=&quot;_blank&quot; href=&quot;https://code.google.com/p/selenium/downloads/list&quot;&gt;https://code.google.com/p/selenium/downloads/list&lt;/a&gt;.
At the time of writing, the latest version was 
&lt;a target=&quot;_blank&quot; href=&quot;https://selenium.googlecode.com/files/selenium-server-standalone-2.37.0.jar&quot;&gt;selenium-server-standalone-2.37.0.jar&lt;/a&gt;.
&lt;/p&gt;

&lt;p&gt;
To allow Selenium to control Chrome, you&#39;ll need the &quot;chromedriver&quot;, available from here:
&lt;a target=&quot;_blank&quot; href=&quot;http://chromedriver.storage.googleapis.com/index.html&quot;&gt;http://chromedriver.storage.googleapis.com/index.html&lt;/a&gt;.
At the time of writing, the latest version was &lt;a target=&quot;_blank&quot; href=&quot;http://chromedriver.storage.googleapis.com/2.7/chromedriver_win32.zip&quot;&gt;2.7&lt;/a&gt;.
&lt;/p&gt;

&lt;p&gt;
Copy the selenium-server-standalone jar file and chromedriver.exe into your project&#39;s directory.
Open a new command prompt, change to your project directory and then start Selenium with the following command:
&lt;/p&gt;

&lt;pre&gt;c:\myproject&amp;gt;java -jar selenium-server-standalone-2.35.0.jar -Dwebdriver.chrome.driver=chromedriver.exe&lt;/pre&gt;

&lt;p&gt;
The server can be stopped by pressing Ctrl+C.
&lt;/p&gt;

&lt;p&gt;
To run JavaScript-based tests, you&#39;ll need to have NodeJS installed.
Download the installer from &lt;a target=&quot;_blank&quot; href=&quot;http://nodejs.org/&quot;&gt;http://nodejs.org/&lt;/a&gt;.
&lt;/p&gt;

&lt;p&gt;
Once NodeJS is installed, you can use the Node Package Manager (npm) to install the selenium-webdriver library:
&lt;/p&gt;

&lt;pre&gt;c:\myproject&amp;gt;npm install selenium-webdriver&lt;/pre&gt;

&lt;h2&gt;A basic browser automation script&lt;/h2&gt;

&lt;p&gt;
You can now create JavaScript files that will automate Chrome.
Here&#39;s a simple script, &lt;code&gt;test.js&lt;/code&gt;.
&lt;/p&gt;

&lt;pre class=&quot;brush: javascript&quot;&gt;var webdriver = require(&quot;selenium-webdriver&quot;);

function createDriver() {
    var driver = new webdriver.Builder()
        .usingServer(&#39;http://localhost:4444/wd/hub&#39;)
        .withCapabilities(webdriver.Capabilities.chrome())
        .build();
    driver.manage().timeouts().setScriptTimeout(10000);
    return driver;
}

var driver = createDriver();
driver.get(&quot;http://www.google.com&quot;);

driver.getTitle().then(function (title) {
    console.log(title);
});

driver.quit();&lt;/pre&gt;

&lt;p&gt;
Make sure the Selenium server is running.
Then run the script at the command prompt, using node:
&lt;/p&gt;

&lt;pre&gt;c:\myproject&amp;gt;node test.js&lt;/pre&gt;

&lt;p&gt;
You will see Chrome open and load the Google home page.
It will then quit, and at the command prompt you&#39;ll see the page title printed.
&lt;/p&gt;

&lt;h2&gt;Learning more&lt;/h2&gt;
&lt;p&gt;
The WebDriverJS library is documented here:
&lt;a href=&quot;https://code.google.com/p/selenium/wiki/WebDriverJs&quot; target=&quot;_blank&quot;&gt;https://code.google.com/p/selenium/wiki/WebDriverJs&lt;/a&gt;.
&lt;/p&gt;

&lt;p&gt;
The library makes great use of &quot;Promises&quot; to handle the asynchronous nature of browser automation.
So it&#39;s essential to read the 
&lt;a href=&quot;https://code.google.com/p/selenium/wiki/WebDriverJs#Understanding_the_API&quot; target=&quot;_blank&quot;&gt;Understanding the API&lt;/a&gt;
section.
&lt;/p&gt;
</content>
</entry>

<entry>
<title>Saving my sanity with browser-automation testing?!</title>
<link href="http://aboutcode.net/2013/11/30/browser-automation-testing.html"/>
<updated>2013-11-30T00:00:00-08:00</updated>
<id>http://aboutcode.net/2013/11/30/browser-automation-testing</id>
<content type="html">&lt;p&gt;
In the rough-and-tumble world of creating a SaaS start-up, I find it all too easy to fall off the automated testing wagon.
It starts with a few quick-fixes, hacked in to meet a new customer need and before I know it, all my tests are nasty red, unmaintainable mess!
Then comes the dilemma: when do I spend precious feature development time paying down that technical debt?
&lt;/p&gt;

&lt;p&gt;
I need to be pragmatic about how and what I test in my application.
What do my customers care about?
They need to be able to log in, enter data and view various reports.
So a basic set of high-level, browser-automation tests that verify common customer scenarios should be a great start.
They&#39;ll give me the confidence to push code live, without worrying if it broke something essential!
&lt;/p&gt;

&lt;p&gt;
I&#39;m sure some kind of 80/20 rule applies.
80% of the application&#39;s usage can be covered by 20% of the tests.
So for now, I&#39;ll focus on getting that 20% in place.
&lt;/p&gt;

&lt;p&gt;
I&#39;m on a journey to restore sanity to my application&#39;s tests.
I&#39;ll be blogging here more about what I learn on the way.
&lt;/p&gt;

&lt;h2&gt;The set-up&lt;/h2&gt;

&lt;p&gt;
My web application uses AngularJS. 
The future of browser-automation testing for this lies with 
&lt;a href=&quot;https://code.google.com/p/selenium/wiki/WebDriverJs&quot;&gt;Selenium&#39;s WebDriverJS&lt;/a&gt;
and the &lt;a href=&quot;https://github.com/angular/protractor&quot;&gt;Protractor&lt;/a&gt; wrapper library.
&lt;/p&gt;

&lt;p&gt;
After a few false starts, and hours spelunking through half-finished documentation and library source code,
I&#39;ve managed to get a working environment for browser-automation tests.
&lt;/p&gt;

&lt;p&gt;
Currently, I&#39;m not using Jasmine, Mocha, or any other test runner.
I&#39;m yet to find one that makes WebDriverJS&#39;s promise-based approach to async testing feel natural.
I don&#39;t need fancy BDD DSLs and pretty output reports.
For now, it&#39;s enough to simply run &lt;code&gt;node my-scenario.js&lt;/code&gt; and see no exceptions :)
&lt;/p&gt;

&lt;p&gt;
Here&#39;s one of the first scenarios I got working.
It tests the login page of the application.
&lt;/p&gt;

&lt;pre class=&quot;brush: javascript&quot;&gt;var browserTest = require(&quot;../browserTest&quot;);
var LoginPage = require(&quot;../pages/LoginPage&quot;);
var db = require(&quot;../utils/db&quot;);

// browserTest is a helper that manages creating a WebDriverJS instance and wrapping it with Protractor.
browserTest(function (browser) {
    var loginPage;
    // Set up some basic data in my test database
    db.createSchool(&quot;1234567&quot;);
    db.createSchoolUser(&quot;user@school.com&quot;, &quot;1234567&quot;);

    // Login with invalid credentials
    loadLoginPage();
    loginPage.setEmailAddress(&quot;no@example.com&quot;);
    loginPage.setPassword(&quot;wrong&quot;);
    loginPage.clickLogin();
    loginPage.errorMessage().shouldBe(&quot;The email address or password you entered doesn&#39;t match our records. Please try again.&quot;);

    // Login with valid credentials
    loadLoginPage();
    loginPage.setEmailAddress(&quot;user@school.com&quot;);
    loginPage.setPassword(&quot;password&quot;);
    loginPage.clickLogin();
    // Should be redirected to school home page
    browser.getCurrentUrl().shouldBe(&quot;http://localhost/school/1234567&quot;);

    function loadLoginPage() {
        browser.get(&quot;http://localhost&quot;);
        loginPage = new LoginPage(browser);
    }
});&lt;/pre&gt;

&lt;p&gt;
UI tests have a tendency to be very brittle.
The slightest change to a page can result in every test failing!
&lt;/p&gt;

&lt;p&gt;
To keep my test code clean and maintainable I&#39;m making use of the &quot;Page Object&quot; pattern.
This abstracts away the messy business of interacting with the web page,
leaving the test code to be a clear expression of a user&#39;s intent.
&lt;/p&gt;

&lt;p&gt;
Here&#39;s the &lt;code&gt;LoginPage&lt;/code&gt; module.
&lt;/p&gt;

&lt;pre class=&quot;brush: javascript&quot;&gt;var protractor = require(&quot;protractor&quot;);

var LoginPage = function (browser) {
    this.browser = browser;
};

LoginPage.prototype = {

    setEmailAddress: function (emailAddress) {
        this.browser.findElement(protractor.By.input(&quot;emailAddress&quot;)).sendKeys(emailAddress);
    },

    setPassword: function (password) {
        this.browser.findElement(protractor.By.input(&quot;password&quot;)).sendKeys(password);
    },

    clickLogin: function () {
        this.browser.findElement(protractor.By.tagName(&quot;button&quot;)).click();
        this.browser.waitForAngular();
    },

    errorMessage: function () {
        return this.browser.findElement(protractor.By.css(&quot;.alert&quot;)).getText();
    }
};

module.exports = LoginPage;&lt;/pre&gt;

&lt;p&gt;
I&#39;d love to hear about your experiences with browser-automation testing.
What handy tools/libraries have you tried?
What&#39;s tripped you up?
&lt;/p&gt;
</content>
</entry>

<entry>
<title>Creating AngularJS controller classes with TypeScript</title>
<link href="http://aboutcode.net/2013/10/20/typescript-angularjs-controller-classes.html"/>
<updated>2013-10-20T00:00:00-07:00</updated>
<id>http://aboutcode.net/2013/10/20/typescript-angularjs-controller-classes</id>
<content type="html">&lt;p&gt;
    I recently learned of AngularJS&#39;s &quot;controller as&quot; syntax.
    It allows you to define an indentifier for the controller instance that is controlling your view.
    This means you can then access properties of that controller.
&lt;/p&gt;

&lt;pre&gt;&amp;lt;div ng-controller=&quot;&lt;strong&gt;ExampleController as example&lt;/strong&gt;&quot;&amp;gt;
    &amp;lt;input type=&quot;text&quot; ng-model=&quot;example.message&quot; /&amp;gt;
&amp;lt;/div&amp;gt;&lt;/pre&gt;

&lt;p&gt;
    This syntax is an alternative to the controller defining data directly on the scope.
    It is particularly useful when working with TypeScript or CoffeeScript, 
    which have a nice &lt;code&gt;class&lt;/code&gt; syntax.
    We can define a controller as a class, with properties for the data to display and 
    methods that handle UI events.
&lt;/p&gt;

&lt;p&gt;
    Here&#39;s an example AngularJS application, written in TypeScript:
&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/andrewdavey/7072745.js&quot;&gt;&lt;/script&gt;

&lt;p&gt;
    And here&#39;s the HTML for that application:
&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/andrewdavey/7072764.js&quot;&gt;&lt;/script&gt;

</content>
</entry>

<entry>
<title>Automatic JSON date parsing with AngularJS</title>
<link href="http://aboutcode.net/2013/07/27/json-date-parsing-angularjs.html"/>
<updated>2013-07-27T00:00:00-07:00</updated>
<id>http://aboutcode.net/2013/07/27/json-date-parsing-angularjs</id>
<content type="html">&lt;p&gt;JSON doesn&#39;t have a native date/time data-type. So you&#39;re most likely to see dates encoded as strings. A good choice of string format is &lt;a href=&quot;https://en.wikipedia.org/wiki/ISO_8601&quot;&gt;ISO 8601&lt;/a&gt;. It&#39;s easy to parse and relatively unambiguous.&lt;/p&gt;
&lt;p&gt;However, when it comes to working with dates in JavaScript, it&#39;s far better to work with the built-in &lt;code&gt;Date&lt;/code&gt; object, instead of strings. Client-side code will need to convert any date strings found in JSON responses into Date objects.&lt;/p&gt;
&lt;p&gt;Here&#39;s a function that recursively searches the properties of an object, replacing date/time strings with Date objects:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var regexIso8601 = /^(\d{4}|\+\d{6})(?:-(\d{2})(?:-(\d{2})(?:T(\d{2}):(\d{2}):(\d{2})\.(\d{1,})(Z|([\-+])(\d{2}):(\d{2}))?)?)?)?$/;

function convertDateStringsToDates(input) {
    // Ignore things that aren&#39;t objects.
    if (typeof input !== &quot;object&quot;) return input;

    for (var key in input) {
        if (!input.hasOwnProperty(key)) continue;

        var value = input[key];
        var match;
        // Check for string properties which look like dates.
        if (typeof value === &quot;string&quot; &amp;amp;&amp;amp; (match = value.match(regexIso8601))) {
            var milliseconds = Date.parse(match[0])
            if (!isNaN(milliseconds)) {
                input[key] = new Date(milliseconds);
            }
        } else if (typeof value === &quot;object&quot;) {
            // Recurse into object
            convertDateStringsToDates(value);
        }
    }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Instead of using this function manually each time we make an AJAX call, we&#39;d rather wire it into the default AJAX processing i.e. &quot;set it and forget it&quot;. AngularJS makes this easy by using HTTP response interceptors.&lt;/p&gt;
&lt;p&gt;First, let&#39;s assume we have a basic AngularJS application module:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var app = angular.module(&quot;app&quot;, []);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can configure the &lt;code&gt;$httpProvider.defaults&lt;/code&gt; by adding our response transformer, so it&#39;ll be used everytime an HTTP request is made using the &lt;code&gt;$http&lt;/code&gt; service.
    Note that this is also how Angular is able to parse JSON response strings into objects for us.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;app.config([&quot;$httpProvider&quot;, function ($httpProvider) {
     $httpProvider.defaults.transformResponse.push(function(responseData){
        convertDateStringsToDates(responseData);
        return responseData;
    });
}]);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
    We can now make HTTP requests using the &lt;code&gt;$http&lt;/code&gt; service and 
    know that any date-strings will have already been converted into Date objects.
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;app.controller(&quot;MyController&quot;, [&quot;$scope&quot;, &quot;$http&quot;, function($scope, $http) {
    $scope.go = function() {
        $http.get(&quot;/foo&quot;).then(function(response) {
            // date-string properties of `response.data` will now be Date objects.
        };
    };
}]);&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Working Demo&lt;/h2&gt;
&lt;iframe width=&quot;100%&quot; height=&quot;300&quot; src=&quot;http://jsfiddle.net/kQZw8/embedded/result,js,html&quot; allowfullscreen=&quot;allowfullscreen&quot; frameborder=&quot;0&quot;&gt;&lt;/iframe&gt;

&lt;p&gt;
    Check out the AngularJS 
    &lt;a href=&quot;http://docs.angularjs.org/api/ng.$http#transformingrequestsandresponses&quot;&gt;$http documentation&lt;/a&gt; 
    for more details about transforming HTTP requests and responses.
&lt;/p&gt;

</content>
</entry>

<entry>
<title>Twitter Bootstrap control-group directive for AngularJS</title>
<link href="http://aboutcode.net/2013/07/13/twitter-bootstrap-control-group-directive-for-angularjs.html"/>
<updated>2013-07-13T00:00:00-07:00</updated>
<id>http://aboutcode.net/2013/07/13/twitter-bootstrap-control-group-directive-for-angularjs</id>
<content type="html">&lt;p&gt;
    Twitter Bootstrap makes it easy to create great looking forms.
    However, you may find yourself repeating the same &lt;code&gt;control-group&lt;/code&gt; boilerplate markup.
&lt;/p&gt;

&lt;pre&gt;&amp;lt;div class=&quot;control-group&quot;&amp;gt;
    &amp;lt;label class=&quot;control-label&quot; for=&quot;example&quot;&amp;gt;Example&amp;lt;/label&amp;gt;
    &amp;lt;div class=&quot;controls&quot;&amp;gt;
        &amp;lt;input type=&quot;text&quot; id=&quot;example&quot; /&amp;gt;
    &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;&lt;/pre&gt;

&lt;p&gt;
    With AngularJS, we can refactor this UI pattern into a directive, 
    and use it like this:
&lt;/p&gt;

&lt;pre&gt;&amp;lt;div control-group label=&quot;Example&quot;&amp;gt;
    &amp;lt;input type=&quot;text&quot; id=&quot;example&quot; /&amp;gt;
&amp;lt;/div&amp;gt;&lt;/pre&gt;

&lt;p&gt;
    The directive generates the boilerplate &lt;code&gt;div&lt;/code&gt;s and &lt;code&gt;label&lt;/code&gt; elements.
    It then &lt;em&gt;transcludes&lt;/em&gt; the &lt;code&gt;input&lt;/code&gt; element you provided inside the generated elements.
&lt;/p&gt;

&lt;p&gt;
    Here&#39;s the basic &lt;code&gt;control-group&lt;/code&gt; directive:
&lt;/p&gt;


&lt;pre&gt;var app = angular.module(&quot;app&quot;, []);

app.directive(&quot;controlGroup&quot;, function() {
    return {
        template: 
        &#39;&amp;lt;div class=&quot;control-group&quot;&amp;gt;\
            &amp;lt;label class=&quot;control-label&quot; for=&quot;{{for}}&quot;&amp;gt;{{label}}&amp;lt;/label&amp;gt;\
            &amp;lt;div class=&quot;controls&quot; ng-transclude&amp;gt;&amp;lt;/div&amp;gt;\
        &amp;lt;/div&amp;gt;&#39;,

        replace: true,
        transclude: true,

        scope: {
            label: &quot;@&quot; // Gets the string contents of the `label` attribute.
        },

        link: function (scope, element) {
            // The &amp;lt;label&amp;gt; should have a `for` attribute that links it to the input.
            // Get the `id` attribute from the input element
            // and add it to the scope so our template can access it.
            var id = element.find(&quot;:input&quot;).attr(&quot;id&quot;);
            scope.for = id;
        }
    };
});&lt;/pre&gt;


&lt;p&gt;
    The directive specifies &lt;code&gt;transclude: true&lt;/code&gt;.
    This means it can use the &lt;code&gt;ng-transclude&lt;/code&gt; directive within its template to insert the child elements
    of the source markup into the &lt;code&gt;&amp;lt;div class=&quot;controls&quot;&amp;gt;&lt;/code&gt; element.
&lt;/p&gt;

&lt;h2&gt;Validation styling&lt;/h2&gt;
&lt;p&gt;
    Bootstrap provides classes to indicate invalid inputs.
    Adding the &lt;code&gt;error&lt;/code&gt; class to the &lt;code&gt;control-group&lt;/code&gt; element will make the 
    label, input and other help text red to alert the user to the problem. 
&lt;/p&gt;
&lt;p&gt;
    Since we are using AngularJS, let&#39;s leverage the existing &lt;code&gt;ng-model&lt;/code&gt; and &lt;code&gt;form&lt;/code&gt; validation behaviors.
    Here&#39;s a simple form with an input data-bound to a scope property.
    The input also has the &lt;code&gt;required&lt;/code&gt; attribute to trigger some basic AngularJS validation.
&lt;/p&gt;

&lt;pre&gt;&amp;lt;form name=&quot;form&quot; class=&quot;form-horizontal&quot; ng-controller=&quot;ExampleController&quot;&amp;gt;
    &amp;lt;div control-group label=&quot;Example&quot;&amp;gt;
        &amp;lt;input type=&quot;text&quot; ng-model=&quot;data.example&quot; id=&quot;example&quot; name=&quot;example&quot; required /&amp;gt;
    &amp;lt;/div&amp;gt;
&amp;lt;/form&amp;gt;&lt;/pre&gt;

&lt;p&gt;
    Assume the &lt;code&gt;ExampleController&lt;/code&gt; is simply initialising the scope.
&lt;/p&gt;

&lt;pre&gt;app.controller(&quot;ExampleController&quot;, [&quot;$scope&quot;, function($scope) {
    $scope.data = {
        example: &quot;&quot;
    };
}]);&lt;/pre&gt;

&lt;p&gt;
    To toggle the &lt;code&gt;error&lt;/code&gt; class whenever the input is invalid, 
    we can use &lt;code&gt;ng-class&lt;/code&gt; directive within the control group template.
&lt;/p&gt;


&lt;pre&gt;&amp;hellip;
template: 
&#39;&amp;lt;div class=&quot;control-group&quot; &lt;strong&gt;ng-class=&quot;{ error: isError }&quot;&lt;/strong&gt;&amp;gt;\
    &amp;lt;label class=&quot;control-label&quot; for=&quot;{{for}}&quot;&amp;gt;{{label}}&amp;lt;/label&amp;gt;\
    &amp;lt;div class=&quot;controls&quot; ng-transclude&amp;gt;&amp;lt;/div&amp;gt;\
&amp;lt;/div&amp;gt;&#39;,
&amp;hellip;&lt;/pre&gt;


&lt;p&gt;
    The directive&#39;s &lt;code&gt;link&lt;/code&gt; function will need to managed this new &lt;code&gt;isError&lt;/code&gt; property.
    To do this it&#39;s need to access the input&#39;s validation state, which is kept by the form.
    Adding the following &lt;code&gt;require&lt;/code&gt; property to the directive defintion will give us access to the &lt;code&gt;NgFormController&lt;/code&gt; in the &lt;code&gt;link&lt;/code&gt; function.
&lt;/p&gt;

&lt;pre&gt;&amp;hellip;
replace: true,
transclude: true,
&lt;strong&gt;require: &quot;^form&quot;,&lt;/strong&gt; // Tells Angular the control-group must be within a form
&amp;hellip;
link: function(scope, element, attrs, &lt;strong&gt;formController&lt;/strong&gt;) {
&amp;hellip;&lt;/pre&gt;

&lt;p&gt;
    The validation status of an input is stored in the scope like this: &lt;code&gt;scope.{form-name}.{input-name}.$invalid&lt;/code&gt;.
    Note that the &lt;code&gt;form&lt;/code&gt; and &lt;code&gt;input&lt;/code&gt; elements must have &lt;code&gt;name&lt;/code&gt; attributes for this to work.
&lt;/p&gt;

&lt;p&gt;
    Our directive definition has &lt;code&gt;scope: { label: &quot;@&quot; }&lt;/code&gt;, which means it will create an isolated scope.
    So the form validation information is actually in the parent scope i.e. &lt;code&gt;scope.$parent&amp;hellip;&lt;/code&gt; 
&lt;/p&gt;

&lt;p&gt;
    Here&#39;s the updated &lt;code&gt;link&lt;/code&gt; function:
&lt;/p&gt;

&lt;pre&gt;&amp;hellip;    
link: function(scope, element, attrs, formController) {
    // The &amp;lt;label&amp;gt; should have a `for` attribute that links it to the input.
    // Get the `id` attribute from the input element
    // and add it to the scope so our template can access it.
    var id = element.find(&quot;:input&quot;).attr(&quot;id&quot;);
    scope.for = id;

    // Get the `name` attribute of the input
    var inputName = element.find(&quot;:input&quot;).attr(&quot;name&quot;);
    // Build the scope expression that contains the validation status.
    // e.g. &quot;form.example.$invalid&quot;
    var errorExpression = [formController.$name, inputName, &quot;$invalid&quot;].join(&quot;.&quot;);
    // Watch the parent scope, because current scope is isolated.
    scope.$parent.$watch(errorExpression, function(isError) {
        scope.isError = isError;
    });
}
&amp;hellip;&lt;/pre&gt;

&lt;h2&gt;Other improvements&lt;/h2&gt;
&lt;p&gt;
    If you don&#39;t use the &lt;code&gt;input&lt;/code&gt;&#39;s &lt;code&gt;id&lt;/code&gt; attribute anywhere else in your application, 
    then it only exists to link it to the &lt;code&gt;label&lt;/code&gt;.
    You could remove the attribute from your mark-up and make the directive generate a unique ID instead
    and set it on the &lt;code&gt;input&lt;/code&gt; element.
&lt;/p&gt;
&lt;p&gt;
    Auto-generated unique IDs are very useful when your UI widgets may be inserted into pages where you can&#39;t 
    guarantee uniqueness of manually defined IDs.
&lt;/p&gt;
&lt;p&gt;
    Another useful directive I use is to show validation error messages.
    Here&#39;s an example of it in use:
&lt;/p&gt;
&lt;pre&gt;&amp;lt;div control-group label=&quot;Example&quot;&amp;gt;
    &amp;lt;input type=&quot;text&quot; ng-model=&quot;data.example&quot; name=&quot;example&quot; required/&amp;gt;
    &amp;lt;span validation-error-for=&quot;required&quot;&amp;gt;This input is required&amp;lt;/span&amp;gt;
&amp;lt;/div&amp;gt;&lt;/pre&gt;
&lt;p&gt;
    It expands into the following mark-up:
&lt;/p&gt;
&lt;pre&gt;&amp;lt;div control-group label=&quot;Example&quot;&amp;gt;
    &amp;lt;input type=&quot;text&quot; ng-model=&quot;data.example&quot; name=&quot;example&quot; required/&amp;gt;
    &amp;lt;span class=&quot;help-inline&quot; ng-show=&quot;form.example.$error.required&quot;&amp;gt;This input is required&amp;lt;/span&amp;gt;
&amp;lt;/div&amp;gt;&lt;/pre&gt;
&lt;p&gt;
    I&#39;ll leave the implementation as an exercise to the reader, or perhaps a future post! ;)
&lt;/p&gt;

&lt;h2&gt;Demo&lt;/h2&gt;
&lt;p&gt;
Here&#39;s a JSFiddle with a demo of the code.
&lt;/p&gt;
&lt;div style=&quot;padding-bottom: 2em&quot;&gt;
&lt;iframe width=&quot;100%&quot; height=&quot;300&quot; src=&quot;http://jsfiddle.net/andrewdavey/aJH84/embedded/result,html,js&quot; allowfullscreen=&quot;allowfullscreen&quot; frameborder=&quot;0&quot;&gt;&lt;/iframe&gt;
&lt;/div&gt;

</content>
</entry>

<entry>
<title>eBook Review - Twitter Bootstrap Web Development How-To</title>
<link href="http://aboutcode.net/2013/01/10/ebook-review-twitter-bootstrap-web-development-how-to.html"/>
<updated>2013-01-10T00:00:00-08:00</updated>
<id>http://aboutcode.net/2013/01/10/ebook-review-twitter-bootstrap-web-development-how-to</id>
<content type="html">&lt;p&gt;
I was recently given a copy of a &lt;a href=&quot;http://www.packtpub.com/twitter-bootstrap-web-development/book&quot;&gt;Twitter Bootstrap Web Development How-To&lt;/a&gt; to review.
&lt;/p&gt;
&lt;p&gt;
The book provides an introduction to &lt;a href=&quot;http://twitter.github.com/bootstrap/index.html&quot;&gt;Twitter Bootstrap&lt;/a&gt;.
Its step-by-step style walks the reader through the basics of getting started.
You&#39;ll learn how to create and customize a variety of different page layouts and enhance these using some of
Bootstrap&#39;s built-in jQuery plugins.
&lt;/p&gt;
&lt;p&gt;
If you&#39;re new to web development and find online documentation a bit terse when learning new libraries, 
then this book is worth a quick read.
&lt;/p&gt;
</content>
</entry>

<entry>
<title>Load images with jQuery Deferred</title>
<link href="http://aboutcode.net/2013/01/09/load-images-with-jquery-deferred.html"/>
<updated>2013-01-09T00:00:00-08:00</updated>
<id>http://aboutcode.net/2013/01/09/load-images-with-jquery-deferred</id>
<content type="html">&lt;p&gt;
Have you ever needed to know the dimensions of an image in JavaScript?
In the past, you may have used code like this:
&lt;/p&gt;
&lt;pre class=&quot;brush: js&quot;&gt;var image = new Image();
image.onload = function() {
  alert(&quot;Loaded image: &quot; + image.width + &quot;x&quot; + image.height);
};
image.src = &quot;/my-image.png&quot;;&lt;/pre&gt;
&lt;p&gt;
This is okay for very basic scenarios, but it becomes tricky to handle things like:
&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Notifying more than one part of your application when the image is loaded&lt;/li&gt;
  &lt;li&gt;Error handling&lt;/li&gt;
  &lt;li&gt;Loading multiple images in parallel&lt;/li&gt;
  &lt;li&gt;Chaining together a sequence of asynchronous operations&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
I also dislike the backwards nature of writing the callback function &lt;em&gt;before&lt;/em&gt;
assigning the &lt;code&gt;src&lt;/code&gt; property. This is essential however, because 
image loading is asynchronous and could potentially finish before your callback was
assigned to &lt;code&gt;onload&lt;/code&gt;.
&lt;/p&gt;
&lt;p&gt;
Fortunately, there is a cleaner way to handle this.
&lt;/p&gt;

&lt;h2&gt;Using jQuery Deferred&lt;/h2&gt;
&lt;p&gt;
The jQuery &lt;a href=&quot;http://api.jquery.com/category/deferred-object/&quot;&gt;deferred object&lt;/a&gt; is perfect for wrapping up asynchronous operations, such as image loading.
The deferred object provides a consistent API for adding callbacks and chaining operations.
It results in very readable code.
&lt;/p&gt;
&lt;p&gt;
Here&#39;s what it&#39;s like to load an image using a jQuery deferred object.
&lt;/p&gt;
&lt;pre class=&quot;brush: js&quot;&gt;$.loadImage(&quot;/my-image.png&quot;)
.done(function(image) {
  alert(&quot;Loaded image: &quot; + image.width + &quot;x&quot; + image.height);
})
.fail(function(image) {
  alert(&quot;Failed to load image&quot;);
});&lt;/pre&gt;

&lt;p&gt;
jQuery deferred&#39;s are easy to chain together using the &lt;code&gt;pipe&lt;/code&gt; function.
For example, imagine we need the dimensions of a user&#39;s avatar image.
But first we need to the image URL from a profile retrieved via ajax...
&lt;/p&gt;
&lt;pre class=&quot;brush: js&quot;&gt;var avatarDimensions = $.get(&quot;/user-profile&quot;)
  .pipe(function(profile) {
    return $.loadImage(profile.avatarUrl);
  })
  .pipe(function(avatarImage) {
    return { width: avatarImage.width, height: avatarImage.height };
  });

// avatarDimensions is a deferred object.
avatarDimensions.done(function(dimensions) {
  console.log(dimensions);
});&lt;/pre&gt;

&lt;h2&gt;Implementing $.loadImage&lt;/h2&gt;
&lt;p&gt;
Here&#39;s the code for &lt;code&gt;$.loadImage&lt;/code&gt;.
It assumes you have already included jQuery 1.5 or newer in your page.
&lt;/p&gt;
&lt;pre class=&quot;brush: js&quot;&gt;$.loadImage = function(url) {
  // Define a &quot;worker&quot; function that should eventually resolve or reject the deferred object.
  var loadImage = function(deferred) {
    var image = new Image();
    
    // Set up event handlers to know when the image has loaded
    // or fails to load due to an error or abort.
    image.onload = loaded;
    image.onerror = errored; // URL returns 404, etc
    image.onabort = errored; // IE may call this if user clicks &quot;Stop&quot;
    
    // Setting the src property begins loading the image.
    image.src = url;
    
    function loaded() {
      unbindEvents();
      // Calling resolve means the image loaded sucessfully and is ready to use.
      deferred.resolve(image);
    }
    function errored() {
      unbindEvents();
      // Calling reject means we failed to load the image (e.g. 404, server offline, etc).
      deferred.reject(image);
    }
    function unbindEvents() {
      // Ensures the event callbacks only get called once.
      image.onload = null;
      image.onerror = null;
      image.onabort = null;
    }
  };
  
  // Create the deferred object that will contain the loaded image.
  // We don&#39;t want callers to have access to the resolve() and reject() methods, 
  // so convert to &quot;read-only&quot; by calling `promise()`.
  return $.Deferred(loadImage).promise();
};&lt;/pre&gt;
</content>
</entry>

<entry>
<title>Google Chrome extensions using KnockoutJS</title>
<link href="http://aboutcode.net/2013/01/06/knockout-chrome-extension.html"/>
<updated>2013-01-06T00:00:00-08:00</updated>
<id>http://aboutcode.net/2013/01/06/knockout-chrome-extension</id>
<content type="html">&lt;p&gt;
Attempting to use KnockoutJS within a Google Chrome extension will swiftly
result in the following error message.
&lt;/p&gt;
&lt;pre&gt;Uncaught Error: Unable to parse bindings.
Message: Error: Code generation from strings disallowed for this context;&lt;/pre&gt;
&lt;p&gt;
This is due to Chrome&#39;s &lt;a href=&quot;http://code.google.com/chrome/extensions/contentSecurityPolicy.html&quot;&gt;Content Security Policy&lt;/a&gt;
for extensions. Essentially, it blocks the use of &lt;code&gt;eval&lt;/code&gt; and 
&lt;code&gt;new Function&lt;/code&gt;, which means features like Knockout&#39;s template 
engine and data-bindings won&#39;t work.
&lt;/p&gt;

&lt;h2&gt;Sandboxing your application&lt;/h2&gt;
&lt;p&gt;
The solution to using KnockoutJS in a Google Chrome extension is to &lt;em&gt;sandbox&lt;/em&gt; the extension&#39;s HTML page and javascript.
This isolates them from the rest of the extension and allows the use of previously 
restricted features.
&lt;/p&gt;
&lt;p&gt;
To sandbox an HTML page, we need to mention it in the extension&#39;s &lt;code&gt;manifest.json&lt;/code&gt; file.
Here&#39;s an example manifest that sandboxes a file named &lt;code&gt;app.html&lt;/code&gt;.
&lt;/p&gt;
&lt;pre class=&quot;brush: js&quot;&gt;{
  &quot;name&quot;: &quot;Knockout Chrome Extension&quot;,
  &quot;version&quot;: &quot;0.1&quot;,
  &quot;manifest_version&quot;: 2,
  &quot;description&quot;: &quot;An example extension that uses KnockoutJS&quot;,
  &quot;sandbox&quot;: {
    &quot;pages&quot;: [&quot;app.html&quot;]
  },
  ...
}&lt;/pre&gt;
&lt;p&gt;
The &lt;code&gt;app.html&lt;/code&gt; page can now reference &lt;code&gt;knockout.js&lt;/code&gt; and your other scripts. These referenced files are then also sandboxed.
However, it can no longer be loaded directly into your extension&#39;s browser action pop-up, or be displayed in a tab.
&lt;/p&gt;

&lt;h2&gt;Loading the sandboxed application&lt;/h2&gt;
&lt;p&gt;
A sandboxed HTML page needs to be loaded from a non-sandboxed page, using an &lt;code&gt;&amp;lt;iframe&amp;gt;&lt;/code&gt;.
&lt;/p&gt;
&lt;p&gt;
For example, the extension can have a browser action pop-up, 
specified by the following part of the &lt;code&gt;manifest.json&lt;/code&gt;:
&lt;/p&gt;
&lt;pre class=&quot;brush: js&quot;&gt;{
  ...
  &quot;browser_action&quot;: {
    &quot;default_popup&quot;: &quot;popup.html&quot;,
    &quot;default_title&quot;: &quot;Knockout Chrome Extension&quot;,
    &quot;default_icon&quot;: {
      &quot;19&quot;: &quot;icon19.png&quot;,
      &quot;38&quot;: &quot;icon38.png&quot;
    }
  },
  ...
}&lt;/pre&gt;
&lt;p&gt;
The &lt;code&gt;popup.html&lt;/code&gt; page serves as a container for the sandboxed application page.
&lt;/p&gt;
&lt;pre class=&quot;brush: html&quot;&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
  &amp;lt;head&amp;gt;
    &amp;lt;script src=&quot;popup.js&quot;&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;head&amp;gt;
  &amp;lt;body style=&quot;padding: 0&quot;&amp;gt;
    &amp;lt;iframe src=&quot;app.html&quot; id=&quot;app&quot; seamless&amp;gt;&amp;lt;/iframe&amp;gt;
  &amp;lt;body&amp;gt;
&amp;lt;html&amp;gt;&lt;/pre&gt;
&lt;p&gt;
Note the handy HTML5 &lt;code&gt;seamless&lt;/code&gt; attribute on the &lt;code&gt;&amp;lt;iframe&amp;gt;&lt;/code&gt; tag.
This removes all borders and scrollbars.
&lt;/p&gt;

&lt;h2&gt;Communicating with the application&lt;/h2&gt;
&lt;p&gt;
Anything loaded by a sandboxed page, such as scripts, are also sandboxed.
This means your application script won&#39;t be able to use any of the Chrome
APIs.
&lt;/p&gt;
&lt;p&gt;
Scripts loaded by the un-sandboxed &lt;code&gt;popup.html&lt;/code&gt; do have access
to the Chrome APIs. Therefore, if your application needs to interact with
Chrome, it has to get the un-sandboxed script to do so.
&lt;/p&gt;
&lt;p&gt;
To communicate between sandboxed and un-sandboxed windows, you have to use messages.
&lt;/p&gt;
&lt;p&gt;
Here&#39;s a snippet from &lt;code&gt;popup.js&lt;/code&gt;, loaded by &lt;code&gt;popup.html&lt;/code&gt;, 
which calls a Chrome API and then posts a message to the application.
&lt;/p&gt;
&lt;pre class=&quot;brush: js&quot;&gt;var appWindow = document.getElementById(&quot;app&quot;).contentWindow;
chrome.topSites.get(function(topSites) {
  appWindow.postMessage({ displayLinks: topSites }, &quot;*&quot;);
});&lt;/pre&gt;
&lt;p&gt;
MDN has great documentation about the &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/DOM/window.postMessage&quot;&gt;window.postMessage method&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
In the application script, we can listen for this message:
&lt;/p&gt;
&lt;pre class=&quot;brush: js&quot;&gt;var app = {
  links: ko.observableArray()
};

window.addEventListener(
  &quot;message&quot;,
  function(event) {
    if (event.data.displayLinks) {
      app.links(event.data.displayLinks);
    }
  },
  false
);

ko.applyBindings(app);&lt;/pre&gt; 
&lt;p&gt;
Similarly, the application can post messages to the un-sandboxed script via
the &lt;code&gt;parent&lt;/code&gt; window property. For example:
&lt;/p&gt;
&lt;pre class=&quot;brush: js&quot;&gt;window.parent.postMessage({ example: true }, &quot;*&quot;)&lt;/pre&gt;

&lt;h2&gt;Full sample code&lt;/h2&gt;
&lt;p&gt;
To get the full sample code for a simple extension that uses KnockoutJS, join my 
web development mailing list. I&#39;ll give you access to a GitHub repository
containing code samples, which you can copy and use in your own projects.
&lt;/p&gt;
</content>
</entry>

<entry>
<title>Twitter Bootstrap Modals and Knockout.js</title>
<link href="http://aboutcode.net/2012/11/15/twitter-bootstrap-modals-and-knockoutjs.html"/>
<updated>2012-11-15T00:00:00-08:00</updated>
<id>http://aboutcode.net/2012/11/15/twitter-bootstrap-modals-and-knockoutjs</id>
<content type="html">&lt;p&gt;
    Displaying modal dialog boxes directly from your Knockout view models turns your
    application into unmaintainable jQuery spaghetti. Your once clean view model, 
    is now fighting with the DOM and dragging you into callback hell.
&lt;/p&gt;
&lt;p&gt;
    Imagine instead maintaining a clear separation of concerns between your view models
    and your UI. Views models only need to collaborate with other view models, never with the DOM.
&lt;/p&gt;
&lt;p&gt;
    Keep your code clean and elegant - just like your application!
&lt;/p&gt;

&lt;h2&gt;What you&#39;ll learn&lt;/h2&gt;
&lt;p&gt;
    This post will teach you how to use Twitter Bootstrap modals in a Knockout.js application,
    while keeping your code clean and simple.
&lt;/p&gt;
&lt;p&gt;
    You&#39;ll learn how to use Knockout&#39;s built-in function, &lt;code&gt;ko.renderTemplate&lt;/code&gt;, 
    to generate a modal dialog box UI, on-demand, from a template.
&lt;/p&gt;
&lt;p&gt;
    This post will also show how jQuery&#39;s Deferred object can neatly manage the asynchronous
    nature of displaying a modal dialog and waiting for its result.
&lt;/p&gt;

&lt;h2&gt;View model flow&lt;/h2&gt;
&lt;p&gt;
    In this post, we&#39;ll be discussing the interaction between an application&#39;s root view model, 
    which is data-bound to the page, and a separate view model, data-bound to a modal dialog.
&lt;p&gt;
    The flow of interaction when displaying a modal is shown below.    
&lt;/p&gt;
&lt;figure&gt;
    &lt;img src=&quot;/images/modal-flow.png&quot; alt=&quot;Modal interaction&quot;/&gt;
    &lt;figcaption&gt;The viewmodel/view interaction of a modal dialog&lt;/figcaption&gt;
&lt;/figure&gt;

&lt;h2&gt;Twitter Bootstrap Modal&lt;/h2&gt;
&lt;p&gt;
    Twitter Bootstrap provides a very nice looking &lt;a href=&quot;http://twitter.github.com/bootstrap/javascript.html#modals&quot;&gt;modal component&lt;/a&gt;.
    However, using the simple &lt;code&gt;$.fn.modal&lt;/code&gt; jQuery plugin
    directly from a Knockout view model can result in DOM code 
    creeping in where it doesn&#39;t belong.
&lt;/p&gt;
&lt;p&gt;
    The Bootstrap modal plugin requires there to be an element in the
    page which it will display as a modal dialog. This element will
    look something like the following:
&lt;/p&gt;
&lt;figure&gt;
    &lt;a href=&quot;/images/modal.png&quot;&gt;&lt;img src=&quot;/images/modal.png&quot; alt=&quot;Modal Dialog Screenshot&quot;/&gt;&lt;/a&gt;
    &lt;figcaption&gt;Screenshot of the modal dialog&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;
    This UI is created by the following HTML.
&lt;/p&gt;
&lt;pre class=&quot;brush: xml&quot;&gt;&amp;lt;div class=&quot;modal hide fade&quot;&amp;gt;
    &amp;lt;div class=&quot;modal-header&quot;&amp;gt;
        &amp;lt;button type=&quot;button&quot; class=&quot;close&quot; aria-hidden=&quot;true&quot; data-bind=&quot;click: cancel&quot;&amp;gt;&amp;amp;times;&amp;lt;/button&amp;gt;
        &amp;lt;h3&amp;gt;Add Note&amp;lt;/h3&amp;gt;
    &amp;lt;/div&amp;gt;
    &amp;lt;div class=&quot;modal-body&quot;&amp;gt;
        &amp;lt;form action=&quot;#&quot; data-bind=&quot;submit: add&quot;&amp;gt;
            &amp;lt;div class=&quot;control-group&quot;&amp;gt;
                &amp;lt;label class=&quot;control-label&quot;&amp;gt;New note:&amp;lt;/label&amp;gt;
                &amp;lt;div class=&quot;controls&quot;&amp;gt;
                    &amp;lt;textarea data-bind=&quot;value: text&quot;&amp;gt;&amp;lt;/textarea&amp;gt;
                &amp;lt;/div&amp;gt;
            &amp;lt;/div&amp;gt;
            &amp;lt;div class=&quot;control-group&quot;&amp;gt;
                &amp;lt;div class=&quot;controls&quot;&amp;gt;
                    &amp;lt;label class=&quot;checkbox&quot;&amp;gt;&amp;lt;input type=&quot;checkbox&quot; data-bind=&quot;checked: important&quot; /&amp;gt;Important&amp;lt;/label&amp;gt;
                &amp;lt;/div&amp;gt;
            &amp;lt;/div&amp;gt;
        &amp;lt;/form&amp;gt;
    &amp;lt;/div&amp;gt;
    &amp;lt;div class=&quot;modal-footer&quot;&amp;gt;
        &amp;lt;a href=&quot;#&quot; class=&quot;btn btn-primary&quot; data-bind=&quot;click: add&quot;&amp;gt;Add Note&amp;lt;/a&amp;gt;
        &amp;lt;a href=&quot;#&quot; class=&quot;btn&quot; data-bind=&quot;click: cancel&quot;&amp;gt;Cancel&amp;lt;/a&amp;gt;
    &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;&lt;/pre&gt;
&lt;p&gt;
    We need a way to dynamically generate this HTML at runtime and also
    data bind it to a separate view model. Luckily Knockout provides
    &lt;code&gt;ko.renderTemplate&lt;/code&gt; to do exactly this.
&lt;/p&gt;
        
&lt;h2&gt;Rendering modal templates&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;ko.renderTemplate&lt;/code&gt; accepts five arguments:&lt;/p&gt;
&lt;table&gt;
    &lt;tr&gt;
        &lt;td&gt;templateName&lt;/td&gt;
        &lt;td&gt;The ID of the template to render&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
        &lt;td&gt;viewModel&lt;/td&gt;
        &lt;td&gt;The view model to data bind to the template&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
        &lt;td&gt;options&lt;/td&gt;
        &lt;td&gt;Additional options passed to the rendering engine. We&#39;ll be providing an &lt;code&gt;afterRender&lt;/code&gt; callback here.&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
        &lt;td&gt;target&lt;/td&gt;
        &lt;td&gt;Where to render the template, such as a &lt;code&gt;&amp;lt;div&amp;gt;&lt;/code&gt; element.&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
        &lt;td&gt;renderMode&lt;/td&gt;
        &lt;td&gt;When this is &lt;code&gt;&quot;replaceNode&quot;&lt;/code&gt; the target element is replaced with the rendered output.&lt;/td&gt;
    &lt;/tr&gt;
&lt;/table&gt;
&lt;p&gt;
    The rendered elements do not necessarily appear in the DOM 
    immediately. We have to provide an &lt;code&gt;afterRender&lt;/code&gt; 
    callback function via the options argument.
&lt;/p&gt;
&lt;pre class=&quot;brush: js&quot;&gt;ko.renderTemplate(
    &quot;mytemplate&quot;,
    viewModel,
    {
        afterRender: function(renderedElement) {
            console.log(&quot;rendered!&quot;);
        }
    },
    target,
    &quot;replaceNode&quot;
);&lt;/pre&gt;
        
&lt;p&gt;
    Let&#39;s wrap up this complexity in helper function that returns a
    jQuery Deferred. This will make it easy to chain together
    rendering of templates with code that uses the output.
&lt;/p&gt;
&lt;pre class=&quot;brush: js&quot;&gt;var createModalElement = function(templateName, viewModel) {
    var temporaryDiv = addHiddenDivToBody();
    var deferredElement = $.Deferred();
    ko.renderTemplate(
        templateName,
        viewModel,
        // We need to know when the template has been rendered,
        // so we can get the resulting DOM element.
        // The resolve function receives the element.
        {
            afterRender: function (nodes) {
                // Ignore any #text nodes before and after the modal element.
                var elements = nodes.filter(function(node) {
                     return node.nodeType === 1; // Element
                });
                deferredElement.resolve(elements[0]);
            }
        },
        // The temporary div will get replaced by the rendered template output.
        temporaryDiv,
        &quot;replaceNode&quot;
    );
    // Return the deferred DOM element so callers can wait until it&#39;s ready for use.
    return deferredElement;
};

var addHiddenDivToBody = function() {
    var div = document.createElement(&quot;div&quot;);
    div.style.display = &quot;none&quot;;
    document.body.appendChild(div);
    return div;
};&lt;/pre&gt;

&lt;h2&gt;The view models&lt;/h2&gt;
&lt;p&gt;
    An application view model will be responsible for initiating the
    display of a modal. It will create a separate view model object for the
    modal and call a helper function to show the modal.
&lt;/p&gt;
&lt;p&gt;
    Here&#39;s a simple application view model that shows a modal:
&lt;/p&gt;
&lt;pre class=&quot;brush: js&quot;&gt;var AppViewModel = function() {
    this.notes = ko.observableArray();
};

AppViewModel.prototype.addNote = function() {
    showModal({
        viewModel: new AddNoteViewModel(),
        context: this // Set context so we don&#39;t need to bind the callback function
    }).then(this._addNoteToNotes);
};

AppViewModel.prototype._addNoteToNotes = function(newNote) {
    this.notes.push(newNote);
};&lt;/pre&gt;
&lt;p&gt;
    This view model provides a method that can be bound to the click event of a button or link. 
    It shows the modal dialog UI, which is data-bound to the given view model.
    Then it waits for the modal to be closed with some result data.
&lt;/p&gt;
&lt;p&gt;
    We&#39;ll dive into the &lt;code&gt;showModal&lt;/code&gt; function soon. 
    For now, note that it is returning &lt;strong&gt;deferred object&lt;/strong&gt; that is resolved when the 
    modal has been closed. The modal is able to pass back a result, which in 
    this case the application view model is adding to its notes array.
&lt;/p&gt;

&lt;p&gt;
    Here&#39;s the &lt;code&gt;AddNoteViewModel&lt;/code&gt;, which will be data bound to the 
    modal UI:
&lt;/p&gt;
&lt;pre class=&quot;brush: js&quot;&gt;var AddNoteViewModel = function() {
    this.text = ko.observable();
    this.important = ko.observable();
};
    
// The name of the template to render
AddNoteViewModel.prototype.template = &quot;AddNote&quot;;

AddNoteViewModel.prototype.add = function () {
    var newNote = {
        text: this.text(),
        important: this.important()
    };
    // Close the modal, passing the new note object as the result data.
    this.modal.close(newNote);
};

AddNoteViewModel.prototype.cancel = function () {
    // Close the modal without passing any result data.
    this.modal.close();
};&lt;/pre&gt;

&lt;p&gt;
    The &lt;code&gt;AddNoteViewModel&lt;/code&gt; provides the name of the template to 
    render. This will be used by the &lt;code&gt;showModal&lt;/code&gt; function.
&lt;/p&gt;
&lt;p&gt;
    The view model is also in control of when to close the modal.
    It assumes that a &lt;code&gt;modal&lt;/code&gt; property has been attached to itself.
    This object contains a &lt;code&gt;close&lt;/code&gt; method that is used to close the
    modal and optionally pass a result.
&lt;/p&gt;

&lt;h2&gt;The &lt;code&gt;showModal&lt;/code&gt; function&lt;/h2&gt;
&lt;p&gt;Here&#39;s the &lt;code&gt;showModal&lt;/code&gt; function:&lt;/p&gt;
&lt;pre class=&quot;brush: js&quot;&gt;var showModal = function(options) {
    if (typeof options === &quot;undefined&quot;) throw new Error(&quot;An options argument is required.&quot;);
    if (typeof options.viewModel !== &quot;object&quot;) throw new Error(&quot;options.viewModel is required.&quot;);

    var viewModel = options.viewModel;
    var template = options.template || viewModel.template;
    var context = options.context;
        
    if (!template) throw new Error(&quot;options.template or options.viewModel.template is required.&quot;);
        
    return createModalElement(template, viewModel)
        .pipe($) // jQueryify the DOM element
        .pipe(function($ui) {
            var deferredModalResult = $.Deferred();
            addModalHelperToViewModel(viewModel, deferredModalResult, context);
            showTwitterBootstrapModal($ui);
            whenModalResultCompleteThenHideUI(deferredModalResult, $ui);
            whenUIHiddenThenRemoveUI($ui);
            return deferredModalResult;
        });
};&lt;/pre&gt;
&lt;p&gt;
    After some standard pre-condition validation, the function starts the
    process of showing the modal. The &lt;code&gt;pipe&lt;/code&gt; method provides a nice
    way to chain together a set of deferred operations.
&lt;/p&gt;
&lt;p&gt;
    First, the modal element creation is started. Once Knockout has finished 
    updating the DOM, the next operation in the pipeline runs.
&lt;/p&gt;
&lt;p&gt;
    The call to &lt;code&gt;pipe($)&lt;/code&gt; is equivalent to:
&lt;/p&gt;
&lt;pre class=&quot;brush: js&quot;&gt;pipe(function(modalElement) {
    return $(modalElement);
})&lt;/pre&gt;
&lt;p&gt;
    Because this returns a non-deferred value, the next stage of the 
    pipeline executes immediately after.
&lt;/p&gt;
&lt;p&gt;
    The final stage of the pipline creates a new deferred object that will
    contain the result of the modal when it is closed. A helper object is
    attached to the view model so it is able to close the modal.
&lt;/p&gt;
&lt;pre class=&quot;brush: js&quot;&gt;var addModalHelperToViewModel = function (viewModel, deferredModalResult, context) {
    // Provide a way for the viewModel to close the modal and pass back a result.
    viewModel.modal = {
        close: function (result) {
            if (typeof result !== &quot;undefined&quot;) {
                deferredModalResult.resolveWith(context, [result]);
            } else {
                // When result is undefined, we don&#39;t want any `done` callbacks of
                // the deferred being called. So reject instead of resolve.
                deferredModalResult.rejectWith(context, []);
            }
        }
    };
};&lt;/pre&gt;
&lt;p&gt;
    The deferred object&#39;s &lt;code&gt;resolveWith&lt;/code&gt; method is used to provide a
    useful value for &lt;code&gt;this&lt;/code&gt; in any callback functions.
    The &lt;code&gt;context&lt;/code&gt; value was provided to the &lt;code&gt;showModal&lt;/code&gt;
    function via its options argument.
&lt;/p&gt;
&lt;p&gt;
    The signature of &lt;code&gt;resolveWith&lt;/code&gt; is similar to 
    &lt;code&gt;Function.prototype.apply&lt;/code&gt; i.e. the arguments must be passed as
    an array.
&lt;/p&gt;
&lt;p&gt;
    Sometimes a user will need to cancel a modal. To handle this case, 
    &lt;code&gt;close&lt;/code&gt; can be called with an undefined result. The deferred 
    modal result is then rejected, instead of resolved. This means that the
    &quot;happy path&quot; in the application view model doesn&#39;t need to check for a
    cancelled modal. Cancelling can be detected by providing a &lt;code&gt;fail&lt;/code&gt;
    callback instead.
&lt;/p&gt;
&lt;pre class=&quot;brush: js&quot;&gt;showModal({ viewModel: new ModalViewModel() })
    .done(function(result) {
        console.log(&quot;Modal closed with result: &quot; + result);
    })
    .fail(function() {
        console.log(&quot;Modal cancelled&quot;);
    });
&lt;/pre&gt;

&lt;p&gt;The remaining helper functions called by &lt;code&gt;showModal&lt;/code&gt; are listed below:&lt;/p&gt;
&lt;pre class=&quot;brush: js&quot;&gt;var showTwitterBootstrapModal = function($ui) {
    // Display the modal UI using Twitter Bootstrap&#39;s modal plug-in.
    $ui.modal({
        // Clicking the backdrop, or pressing Escape, shouldn&#39;t automatically close the modal by default.
        // The view model should remain in control of when to close.
        backdrop: &quot;static&quot;,
        keyboard: false
    });
};
    
var whenModalResultCompleteThenHideUI = function (deferredModalResult, $ui) {
    // When modal is closed (with or without a result)
    // Then always hide the UI.
    deferredModalResult.always(function () {
        $ui.modal(&quot;hide&quot;);
    });
};

var whenUIHiddenThenRemoveUI = function($ui) {
    // Hiding the modal can result in an animation.
    // The `hidden` event is raised after the animation finishes,
    // so this is the right time to remove the UI element.
    $ui.on(&quot;hidden&quot;, function() {
        // Call ko.cleanNode before removal to prevent memory leaks.
        $ui.each(function (index, element) { ko.cleanNode(element); });
        $ui.remove();
    });
};&lt;/pre&gt;
&lt;p&gt;
    When a modal is closed, it is removed from the DOM to free up memory.
    However, Twitter Bootstrap modal&#39;s &lt;code&gt;hide&lt;/code&gt; method will animate
    the hiding. Instant removal would prevent this nice effect.
&lt;/p&gt;
&lt;p&gt;
    A two-step approach is used to remove the modal once the deferred result 
    has been resolved or rejected. The Bootstrap modal &quot;hide&quot; method is called.
    This will raise the &quot;hidden&quot; event once the animation has finished. At that
    point we can remove the modal&#39;s DOM element.
&lt;/p&gt;

&lt;h2&gt;Extensions and ideas&lt;/h2&gt;
&lt;p&gt;
    The use of &lt;code&gt;ko.renderTemplate&lt;/code&gt; to dynamically generate UI can be
    generalised for other components. For example, 
    &lt;a target=&quot;_blank&quot; href=&quot;http://twitter.github.com/bootstrap/javascript.html#popovers&quot;&gt;Twitter Bootstrap Popovers&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
    Occasionally one modal will need to display another modal. There are two 
    possible flows to consider:
&lt;/p&gt;
&lt;ol&gt;
    &lt;li&gt;Close the first modal, then show the second.&lt;/li&gt;
    &lt;li&gt;Stack the second modal on top of the first.&lt;/li&gt;
&lt;/ol&gt;
&lt;aside&gt;
    Be careful, this is not always a great user experience.
    Avoid stacking up lots of modals on top of each other!
&lt;/aside&gt;
&lt;p&gt;
    In the first case, the modal&#39;s deferred result object must be passed onto
    the second modal. The application view model shouldn&#39;t resume until the 
    second modal has been closed.
&lt;/p&gt;
&lt;p&gt;
    The modal helper object assigned to view models could be extended to
    support this scenario. Here&#39;s a possible API:
&lt;/p&gt;
&lt;pre class=&quot;brush: js&quot;&gt;FirstViewModel.prototype.showSecond = function() {
    this.modal.closeCurrentAndShowModal(new SecondViewModel());
    // The first modal is now removed from the DOM.
};&lt;/pre&gt;
&lt;p&gt;
    The second case is somewhat simpler. A separate deferred result object is
    created for the second modal. The first modal remains in the background,
    ready handle the result when the second modal is closed.
&lt;/p&gt;
&lt;p&gt;
    Again, the modal helper object could be enhanced to support this behavior:
&lt;/p&gt;
&lt;pre class=&quot;brush: js&quot;&gt;FirstViewModel.prototype.showSecond = function() {
    this.modal.showNestedModal(new SecondViewModel());
    // The first modal is still loaded, but hidden until the second is closed.
};&lt;/pre&gt;
&lt;p&gt;
    To prevent Twitter Bootstrap adding multiple backdrop overlays to the page,
    the first modal could be hidden, but not removed, while the second modal is
    displayed.
&lt;/p&gt;

&lt;h2&gt;Full sample code&lt;/h2&gt;
&lt;p&gt;
To get the full sample code that accompanies this blog post, join my 
web development mailing list. I&#39;ll give you access to a private GitHub repository
containing code samples, which you can copy and use in your own projects.
&lt;/p&gt;

&lt;h2&gt;Thanks for reading&lt;/h2&gt;
&lt;p&gt;
    I hope you found this post useful. Let me know in the comments, or on twitter 
    &lt;a href=&quot;https://twitter.com/andrewdavey&quot;&gt;@andrewdavey&lt;/a&gt;.
    Feel free to copy, modify and use the code in your applications.
&lt;/p&gt;

</content>
</entry>

<entry>
<title>Zero Configuration Asp Net Modules And Handlers</title>
<link href="http://aboutcode.net/2012/01/15/zero-configuration-asp-net-modules-and-handlers.html"/>
<updated>2012-01-15T00:00:00-08:00</updated>
<id>http://aboutcode.net/2012/01/15/zero-configuration-asp-net-modules-and-handlers</id>
<content type="html">﻿---
title: Zero-configuration ASP.NET modules and handlers
layout: post
---
&lt;p&gt;A couple of my open source projects, &lt;a href=&quot;http://getcassette.net/&quot;&gt;Cassette&lt;/a&gt; and 
&lt;a href=&quot;https://github.com/andrewdavey/notfoundmvc&quot;&gt;Not Found MVC&lt;/a&gt;, 
add custom HTTP handlers and modules to the host application. 
Cassette, for example, can return bundled assets from a route added to the ASP.NET RouteTable. 
It does this without requiring any additions to Web.config or Application_Start in Global.asax.&lt;/p&gt;
&lt;p&gt;Removing the requirement of editing configuration or adding initialization code makes it simpler to use a library. 
A developer can just reference the library and they&#39;re ready to go.&lt;/p&gt;
&lt;p&gt;Achieving this simplicity requires two handy libraries, called &lt;a href=&quot;http://nuget.org/packages/WebActivator&quot;&gt;WebActivator&lt;/a&gt; 
and &lt;a href=&quot;http://nuget.org/packages/Microsoft.Web.Infrastructure&quot;&gt;Microsoft.Web.Infrastructure&lt;/a&gt;. 
Both are available via Nuget.&lt;/p&gt;
&lt;p&gt;Using WebActivator&#39;s &lt;code&gt;PreApplicationStartMethod&lt;/code&gt; attribute we can provide a method to run very early
 in the web application&#39;s start up process. The method can use &lt;code&gt;DynamicModuleUtility&lt;/code&gt;, 
 from the &lt;code&gt;Microsoft.Web.Infrastructure&lt;/code&gt; assembly, to register HTTP modules.&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;[assembly: WebActivator.PreApplicationStartMethod( typeof(Example.StartUp), &quot;PreApplicationStart&quot;)]
namespace Example
{
    public static class StartUp
    {
        public static void PreApplicationStart()
        {
            DynamicModuleUtility.RegisterModule(typeof(MyHttpModule));
        }
    }
}&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;HTTP modules are useful for adding functionality that applies to all requests. 
For example, Cassette uses an HTTP module to rewrite HTML output of pages. 
However, if you want to handle your own custom URLs you need to create an HTTP handler hooked up via the ASP.NET routing system.&lt;/p&gt;
&lt;p&gt;Adding custom routes needs to happen after the application itself has finished starting up. 
It&#39;s too early to add routes in the &lt;code&gt;PreApplicationStartMethod&lt;/code&gt;. 
Instead, use the &lt;code&gt;PostApplicationStartMethod&lt;/code&gt; attribute also provided by WebActivator.&lt;/p&gt;
&lt;p&gt;The method specified in &lt;code&gt;PostApplicationStartMethod&lt;/code&gt; is run after the web application&#39;s Application_Start method. 
It&#39;s the ideal place to modify the route table.&lt;/p&gt;
&lt;p&gt;This is the attribute:&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;[assembly: WebActivator.PostApplicationStartMethod( typeof(Example.StartUp), &quot;PostApplicationStart&quot;)]&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;And here&#39;s the method added to the &lt;code&gt;StartUp&lt;/code&gt; class:&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;public static void PostApplicationStart()
{
    var route = new Route(&quot;my/url&quot;, new MyRouteHandler());
    // Insert route at front of route list to avoid conflicts with application routes.
    RouteTable.Routes.Insert(0, route);
}&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;The application will have already defined its own routes, so we need to ensure our library&#39;s routes don&#39;t conflict. 
For example, the application&#39;s &lt;code&gt;&quot;{controller}/{action}&quot;&lt;/code&gt; route would capture something like &lt;code&gt;&quot;my/url&quot;&lt;/code&gt;. 
So if our library needs to handle that specific URL, then its route must be first in the route table.&lt;/p&gt;
&lt;p&gt;Another precaution you can take is to constrain your route to only match incoming requests. 
The routing table is also used to generate URLs, so you may need to guard against unintended matches. Here&#39;s an example constraint:&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;class OnlyMatchIncomingRequestsConstraint : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        return routeDirection == RouteDirection.IncomingRequest;
    }
}&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;Use it like this:&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;var route = new Route(
    &quot;my/url&quot;,
    new RouteValueDictionary(),
    new RouteValueDictionary(new { incoming = new OnlyMatchIncomingRequestsConstraint() }),
    new MyRouteHandler()
);&lt;/pre&gt;&lt;/code&gt;

&lt;p&gt;See these techniques in action in the source code of Cassette and NotFoundMVC over on GitHub:&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;&lt;a href=&quot;https://github.com/andrewdavey/cassette&quot;&gt;https://github.com/andrewdavey/cassette&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;https://github.com/andrewdavey/NotFoundMvc&quot;&gt;https://github.com/andrewdavey/NotFoundMvc&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Have you seen any other cool uses of WebActivator out there? Let me know in the comments!&lt;/p&gt;

</content>
</entry>

<entry>
<title>Testing Temp Directory</title>
<link href="http://aboutcode.net/2011/10/26/testing-temp-directory.html"/>
<updated>2011-10-26T00:00:00-07:00</updated>
<id>http://aboutcode.net/2011/10/26/testing-temp-directory</id>
<content type="html">﻿---
layout: post
title: Testing with a Temporary Directory
---
&lt;p&gt;When testing a class that interacts with the file system, it’s useful to have a clean “temp” directory. We don’t want old files lying around, which could randomly break later tests.&lt;/p&gt;
&lt;p&gt;The System.IO.Path class has a static method GetTempPath. This returns the path of the system’s temporary folder. Rather than work directly in the temp directory, we can create a new, uniquely named, directory for each test. This makes cleaning up after the test easy – simply delete the directory.&lt;/p&gt;
&lt;p&gt;This repeated pattern of using a temporary directory can be encapsulated into a simple class.&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;class TempDirectory : IDisposable
{
    public TempDirectory()
    {
        path = Path.Combine(
            Path.GetTempPath(),
            Guid.NewGuid().ToString()
        );
        Directory.CreateDirectory(path);
    }

    readonly string path;

    /// &lt;summary&gt;
    /// Allows the TempDirectory to be used anywhere a string is required.
    /// &lt;/summary&gt;
    public static implicit operator string(TempDirectory directory)
    {
        return directory.path;
    }

    public override string ToString()
    {
        return path;
    }

    public void Dispose()
    {
        Directory.Delete(path, true);
    }
}&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;Here’s a simple test using the TempDirectory class:&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;[Test]
public void SimpleTest()
{
    using (var temp = new TempDirectory())
    {
        // Temp directory is used as a string...
        File.WriteAllText(Path.Combine(temp, &quot;file.txt&quot;), &quot;hello&quot;);
        var widget = new FileWidget(temp);
        widget.Load(&quot;file.txt&quot;);
        Assert.AreEqual(&quot;hello&quot;, widget.Title);
    }
}&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;The TempDirectory creates a new, uniquely named, temporary directory. The class is disposable, so can be used in a using statement. This ensures the directory is deleted, even if the test code throws an unhandled exception.&lt;/p&gt;
&lt;p&gt;The implicit cast to string operator allows us to use the TempDirectory as if it were a string. When passing it as a string argument, the full path to the directory is used.&lt;/p&gt;
&lt;p&gt;This simple class could also be extended with methods that allow you to quickly set up temporary files as well.&lt;/p&gt;
&lt;p&gt;P.S. Obviously it’s a good idea to avoid spreading file I/O throughout all your objects! However, there will always be some point where performing real I/O is appropriate. I hope this simple class proves useful for testing those objects.&lt;/p&gt;

</content>
</entry>

<entry>
<title>Efficient Encapsulation Of Javascript Objects</title>
<link href="http://aboutcode.net/2011/10/04/efficient-encapsulation-of-javascript-objects.html"/>
<updated>2011-10-04T00:00:00-07:00</updated>
<id>http://aboutcode.net/2011/10/04/efficient-encapsulation-of-javascript-objects</id>
<content type="html">﻿---
layout: post
title: Efficient Encapsulation of JavaScript Objects
---
&lt;p&gt;Encapsulation is one of the most important principles of object oriented programming. Ideally, an object exposes a limited public interface and keeps its data and implementation details private.
&lt;/p&gt;
&lt;p&gt;JavaScript does not provide a built-in way to manage the visibility of an object’s members. However its flexibility does allow us to recreate encapsulation. A common approach is to use a function that contains the private data and functions, and then return a limited set of public functions that can interact with the private data.
&lt;/p&gt;

&lt;code&gt;&lt;pre class=&quot;brush: javascript&quot;&gt;var Customer = function(id) {
    var totalSpend = 0;

    function isSpecial() {
        return totalSpend &amp;gt; 100;
    }

    return {
        placeOrder: function(order) {
            totalSpend += order.total;
        },
        getReward: function() {
            if (isSpecial()) {
                return &quot;Special Customer Coupon!&quot;;
            } else {
                return &quot;Nothing Today&quot;;
            }
        },
        toString: function() {
            return &quot;Customer #&quot; + id;
        }
    };
};&lt;/pre&gt;&lt;/code&gt;

&lt;p&gt;This approach is valid, but not necessarily that efficient when creating lots of objects. Every time an object is created, all its functions and created as well. This takes time, and perhaps more importantly, memory. If you’re script is running on a mobile device then resources can be limited. Also, server-side JavaScript running in NodeJS could be creating many thousands of objects.
&lt;/p&gt;
&lt;p&gt;JavaScript provides the prototype model of inheritance to solve this problem. A single prototype object can contain the functions. Then any objects that have that prototype can share them without any extra overhead.
&lt;/p&gt;
&lt;p&gt;The following code demonstrates the common pattern of defining a prototype.
&lt;/p&gt;

&lt;code&gt;&lt;pre class=&quot;brush: javascript&quot;&gt;var Customer = function(id) {
    this.id = id;
    this.totalSpend = 0;
};
Customer.prototype.placeOrder = function(order) {
    totalSpend += order.total;
};
Customer.prototype.getReward = function() {
    if (isSpecial()) {
        return &quot;Special Customer Coupon!&quot;;
    } else {
        return &quot;Nothing Today&quot;;
    }
};
Customer.prototype.toString = function() {
    return &quot;Customer #&quot; + id;
};
Customer.prototype.isSpecial = function() {
    return totalSpend &amp;gt; 100;
};&lt;/pre&gt;&lt;/code&gt;

&lt;p&gt;
While this code is more efficient, we have lost the ability to encapsulate any data and private functions.
Anyone creating a &lt;code&gt;Customer&lt;/code&gt; object can directly access the &lt;code&gt;totalSpend&lt;/code&gt; property.
&lt;/p&gt;
&lt;p&gt;A possible workaround is to rely on a convention of, for example, prefixing all non-public members with an underscore. Personally, I dislike this. It adds syntactic noise to the code and doesn’t discourage wayward developers from using objects in ways they shouldn’t!
&lt;/p&gt;
&lt;p&gt;Therefore I created an alternative solution. It combines the efficiency of prototypes, with the principles of encapsulation. Here’s a quick example of defining a class:
&lt;/p&gt;

&lt;code&gt;&lt;pre class=&quot;brush: javascript&quot;&gt;var Customer = defineClass({
    &quot;constructor&quot;: function(id) {
        this.id = id;
        this.totalSpend = 0;
    },
    &quot;public&quot;: {
        placeOrder: function(order) {
            this.totalSpend += order.total;
        },
        getReward: function() {
            if (this.isSpecial()) {
                return &quot;Special Customer Coupon!&quot;;
            } else {
                return &quot;Nothing Today&quot;;
            }
        },
        toString: function() {
            return &quot;Customer #&quot; + this.id;
        }
    },
    &quot;private&quot;: {
        isSpecial: function() {
            return this.totalSpend &amp;gt; 100;
        }
    }
});&lt;/pre&gt;&lt;/code&gt;

&lt;p&gt;The defineClass function accepts an object literal which contains the constructor, the public functions and private functions. Within functions, the &quot;this&quot; keyword works as normal, allowing storage of data in the object. All the object’s functions, public and private, can call each other.
&lt;/p&gt;
&lt;p&gt;Let’s examine the use of an instance of the object.&lt;/p&gt;

&lt;code&gt;&lt;pre class=&quot;brush: javascript&quot;&gt;var customer = new Customer(123);
console.log( customer.toString() ); // &amp;gt; &quot;Customer #123&quot;
customer.placeOrder( { total: 10 } );
console.log( customer.getReward() ); // &amp;gt; &quot;Nothing Today&quot;
customer.placeOrder( { total: 101 } );
console.log( customer.getReward() ); // &amp;gt; &quot;Special Customer Coupon!&quot;&lt;/pre&gt;&lt;/code&gt;

&lt;p&gt;So what happens if we try to access the private members of the object?
&lt;/p&gt;

&lt;code&gt;&lt;pre class=&quot;brush: javascript&quot;&gt;var customer = new Customer(123);
customer.totalSpend = 1000;
console.log( customer.getReward() ); // &amp;gt; &quot;Nothing Today&quot;
console.log( typeof customer.isSpecial ); // &amp;gt; &quot;undefined&quot;&lt;/pre&gt;&lt;/code&gt;

&lt;p&gt;Any attempt to use the private data or functions fails. The actual object we’re using doesn&#39;t have those private members.

&lt;h2&gt;Annotated source for defineClass&lt;/h2&gt;

&lt;p&gt;The source code for defineClass is annotated with comments to explain the trickier details. It’s less than 100 lines and is probably easier to read, than explain it again here. 
&lt;/p&gt;

&lt;code&gt;&lt;pre class=&quot;brush: javascript&quot;&gt;var defineClass = (function() {

    // Creates a proxying function that will call the real object.
    function createProxyFunction(functionName) {
        return function() {
            // &#39;this&#39; in here is the proxy object.
            var realObject = this.__realObject__,
                realFunction = realObject[functionName];

            // Call the real function on the real object, passing any arguments we received.
            return realFunction.apply(realObject, arguments);
        };
    };

    // createProxyClass creates a function that will create Proxy objects.
    //   publicFunctions: an object of public functions for the proxy.
    function createProxyClass(publicFunctions) {
        var ProxyClass, functionName, func;

        // This is this Proxy object constructor.
        ProxyClass = function (realObject) {
            // Choose a reasonably obscure name for the real object property.
            // It should avoid any conflict with the public function names.
            // Also any code being naughty by using this property is quickly spotted!
            this.__realObject__ = realObject;
        };

        // Create a proxy function for each of the public functions.
        for (functionName in publicFunctions) {
            func = publicFunctions[functionName];
            // We only want functions that are defined directly on the publicFunctions object.
            if (publicFunctions.hasOwnProperty(functionName) &amp;amp;&amp;amp;
                typeof func === &quot;function&quot;) {
                ProxyClass.prototype[functionName] = createProxyFunction(functionName);
            }
        }

        return ProxyClass;
    }

    function copyToPrototype(source, destination) {
        var prototype = destination.prototype,
            property;
        for (property in source) {
            if (source.hasOwnProperty(property)) {
                prototype[property] = source[property];
            }
        }
    };

    function createRealClass(constructor, publics, privates, proxyClass) {
        var RealClass = function () {
            var proxy;

            if (typeof constructor === &quot;function&quot;) {
                // Call the constructor function to perform any initialization of the object.
                constructor.apply(this, arguments);
            }
            proxy = new proxyClass(this);
            // Maintain the illusion that the proxy object is a real object.
            // Assign the constructor property in case anyone uses it to create another instance.
            proxy.constructor = RealClass;
            // Returning the proxy object means creating a new instance of Class
            // results in a proxy object, instead of the real object.
            // Callers can then only interact with the proxy.
            return proxy;
        };
        // The RealClass has both public and private functions.
        copyToPrototype(publics || {}, RealClass);
        copyToPrototype(privates || {}, RealClass);

        return RealClass;
    }

    // Return the defineClass function.
    return function (options) {
        // &#39;public&#39; and &#39;private&#39; are reserved keywords, so the option properties must be 
        // accessed using strings instead of options.public, for example.
        var proxyClass = createProxyClass(options[&quot;public&quot;]),
            realClass = createRealClass(
                options[&quot;constructor&quot;],
                options[&quot;public&quot;],
                options[&quot;private&quot;],
                proxyClass
            );
        return realClass;
    };

}());&lt;/pre&gt;&lt;/code&gt;

&lt;h2&gt;Proxy Object&lt;/h2&gt;
&lt;p&gt;The key to how defineClass works lies with the &quot;proxy&quot; object pattern. A cute trick of JavaScript is that an object constructor function may return a different object, other than the one being constructed. So when creating a new Customer object, you actually get a CustomerProxy object. The real Customer object is hidden within the proxy.
&lt;/p&gt;
&lt;p&gt;To protect the real object from unwanted external manipulation, a proxy object is created to only expose the public functions. This proxy object has a single property that references the real object. Any call to a function of the proxy object is passed back to the real object.
&lt;/p&gt;
&lt;p&gt;This does provide a way to circumvent the proxy, by directly using the real object property. However, choosing a suitable name for the property will clearly highlight any calling code that is doing something questionable.
&lt;/p&gt;
&lt;p&gt;In addition, it is sometimes necessary to violate encapsulation. A common case is for serialization, which requires access to the private data of an object. It’s therefore useful to have an &quot;escape valve&quot;.
&lt;/p&gt;

&lt;h2&gt;Extensions&lt;/h2&gt;
&lt;p&gt;The approach given here could be extended to support inheritance and mixins.&lt;/p&gt;
&lt;p&gt;Feel free to use the code and extend it for your own purposes.&lt;/p&gt;
</content>
</entry>

<entry>
<title>Dear ASP.NET, we need to talk about JavaScript</title>
<link href="http://aboutcode.net/2011/06/19/dear-aspnet-we-need-to-talk-about-javascript.html"/>
<updated>2011-06-19T00:00:00-07:00</updated>
<id>http://aboutcode.net/2011/06/19/dear-aspnet-we-need-to-talk-about-javascript</id>
<content type="html">&lt;p&gt;Dear ASP.NET,&lt;/p&gt;
&lt;p&gt;I only began to enjoy web development with you once MVC came along. 
Thank you for getting me into the wonderful world of the web. 
However, the more I develop rich web applications, the more I see gaps in your tooling and libraries. 
Your server-side development story is excellent, but client-side (in browser) is weak.&lt;/p&gt;
&lt;p&gt;Having now built a few JavaScript heavy, rich interactive web applications with .NET, 
I can tell you that you are lacking in some key areas. 
Therefore, I’m (not so humbly) going to make some observations and feature requests.&lt;/p&gt;
&lt;/p&gt;

&lt;h2&gt;JavaScript&lt;/h2&gt;
&lt;p&gt;Visual Studio needs a JavaScript project type. 
If I’m building a complex jQuery plugin, Node.JS application or anything else involving more
than one JavaScript file, then rolling my own build system is tedious.&lt;/p&gt;
&lt;p&gt;You already have an excellent Visual Studio language service for JavaScript. 
The intellisense tricks you’re pulling off are fantastic. Capitalise on this by
adding a project type.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;I want File &amp;gt; New JavaScript Project.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The result of Release building a JavaScript project should be a concatenated, 
minified version of all the scripts. You will need to determine the file dependency
ordering (take a look at &lt;a href=&quot;http://aboutcode.net/knapsack&quot;&gt;Knapsack&lt;/a&gt;). 
You already have the &lt;a href=&quot;http://ajaxmin.codeplex.com/&quot;&gt;Ajax Minifier&lt;/a&gt; library, 
so reuse this.&lt;/p&gt;
&lt;p&gt;Allow the Web Application Project types to link to a JavaScript project to get the scripts. 
This could be similar to how Silverlight projects link to Web Application projects.&lt;/p&gt;
&lt;p&gt;Also, build in support for &lt;a href=&quot;http://www.jslint.com/&quot;&gt;JSLint&lt;/a&gt; and 
display red squiggles in my code when I’m writing poor JavaScript.&lt;/p&gt;

&lt;h2&gt;CoffeeScript&lt;/h2&gt;
&lt;p&gt;Get on the &lt;a href=&quot;http://coffeescript.org/&quot;&gt;CoffeeScript&lt;/a&gt; bandwagon as soon as possible! 
Rails already has. CoffeeScript makes writing JavaScript faster and easier to maintain.
It’s a fantastic language.&lt;/p&gt;
&lt;p&gt;I need Visual Studio support for CoffeeScript i.e. syntax highlighting, 
intellisense and a project type. 
I’ll also need to mix JavaScript and CoffeeScript in the same project because of existing
libraries like jQuery.&lt;/p&gt;
&lt;p&gt;The existing CoffeeScript compiler runs in JavaScript. 
So either, get your own DLR-based, JavaScript engine or (even better) 
support &lt;a href=&quot;https://github.com/fholm/IronJS&quot;&gt;IronJS&lt;/a&gt; or 
&lt;a href=&quot;http://jurassic.codeplex.com/&quot;&gt;Jurassic&lt;/a&gt;. 
Alternatively, write a new compiler in C#.&lt;/p&gt;

&lt;h2&gt;HTML Templates&lt;/h2&gt;
&lt;p&gt;Client-side web applications require HTML templating. jQuery.tmpl is very 
nice and works well with Steve Sanderson’s &lt;a href=&quot;http://knockoutjs.com/&quot;&gt;KnockoutJS&lt;/a&gt;. 
However, the current approach of “stuff a bunch of template containing script tags into the page” 
does not scale well with projects having hundreds of templates.&lt;/p&gt;
&lt;p&gt;Making the browser parse and code-generate the templates into JavaScript 
on every page feels like a huge waste of time. This needs to be done server-side
or even at build time. The final JavaScript functions should be deployed just 
like any other script files.&lt;/p&gt;
&lt;p&gt;The key to solving this problem is Razor.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Razor totally nails HTML templating.&lt;/strong&gt; We should be using it for both server
and client-side templates. The same templates could even be reusable on both sides.&lt;/p&gt;
&lt;p&gt;You just need to add JavaScript and (please, please, please) CoffeeScript
support to the Razor parser. CoffeeScript will be an especially nice language 
to write Razor templates in. For example, it has a much cleaner, C#-style, 
“for each” than raw JavaScript.&lt;/p&gt;
&lt;p&gt;Implementing this requires a managed JavaScript engine. Again, something 
like IronJS/Jurassic can be used.&lt;/p&gt;
&lt;p&gt;Server-side, the Razor views run on the DLR and work just like any other MVC view.&lt;/p&gt;
&lt;p&gt;For the client-side, send down the JavaScript generated from the Razor compiler.&lt;/p&gt;

&lt;h2&gt;Client-side Asset Management&lt;/h2&gt;
&lt;p&gt;Scripts, style sheets, images and HTML templates are the client-side assets 
of a web application. The current ASP.NET story for these is “stuff them into
folders and deploy”. This is not good enough!&lt;/p&gt;
&lt;p&gt;Combining, minification, versioning, compression and caching, all matter for 
production deployment. We need a solution that handles all that, whilst still 
maintaining an excellent debug-time experience. Stepping into a 10,000 line, 
minified, script is no fun at all!&lt;/p&gt;
&lt;p&gt;I have already started to explore the solutions to these problems in my 
&lt;a href=&quot;http://aboutcode.net/knapsack&quot;&gt;Knapsack&lt;/a&gt; project. For example, 
Knapsack determines the dependency order of JavaScript files based on the
XML reference comments. Much more needs to be done, but please take a look
and either get involved or even steal ideas!&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;I just want a solution. I need to get back to writing web applications 
with .NET. Creating tools, frameworks and build processes is your job.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;Best regards,&lt;/p&gt;
&lt;p&gt;Andrew Davey&lt;br/&gt;
- a passionate .NET open source developer -&lt;/p&gt;

&lt;p&gt;P.S. Put &lt;a href=&quot;http://twitter.com/stevensanderson&quot;&gt;Steve Sanderson&lt;/a&gt;
in charge of all this :) I think he really gets ASP.NET, JavaScript and open source.&lt;/p&gt;

&lt;p&gt;P.P.S. While this is an open letter to ASP.NET, I really would love to hear
the entire community&#39;s thoughts on the issues raised here.&lt;/p&gt;
&lt;p&gt;Either comment here, or heckle me on Twitter 
&lt;a href=&quot;http://twitter.com/andrewdavey&quot;&gt;@andrewdavey&lt;/a&gt;.&lt;/p&gt;
</content>
</entry>

<entry>
<title>Knapsack - Automatic JavaScript and stylesheet dependency management for ASP.NET</title>
<link href="http://aboutcode.net/2011/05/15/Knapsack-automatic-javascript-and-stylesheet-dependency-manager.html"/>
<updated>2011-05-15T00:00:00-07:00</updated>
<id>http://aboutcode.net/2011/05/15/Knapsack-automatic-javascript-and-stylesheet-dependency-manager</id>
<content type="html">&lt;p&gt;
Are you wasting time correctly ordering, concatenating and minifying your JavaScript? How about debugging that 10,000 line minified script? &lt;a href=&quot;http://aboutcode.net/knapsack/&quot;&gt;Knapsack&lt;/a&gt; solves all these problems. It&#39;s easy to install (via nuget) and provides some fun extras, like CoffeeScript support!
&lt;/p&gt;
&lt;p&gt;Knapsack is a new open source project. It&#39;s an answer to my &lt;a href=&quot;http://aboutcode.net/2011/04/12/managing-javascript.html&quot;&gt;previous rant&lt;/a&gt; about managing JavaScript in an ASP.NET web application.&lt;/p&gt;
&lt;p&gt;Say goodbye to maintaining JavaScript build files - Knapsack determines the correct order of files.&lt;/p&gt;
&lt;p&gt;In debug-mode, Knapsack lets you debug against the original scripts. In production-mode, minified, cache-friendly, script modules are generated instead. This is config controlled, so not a single source change is needed.&lt;/p&gt;
&lt;p&gt;Head over the the project home page &lt;a href=&quot;http://aboutcode.net/knapsack/&quot;&gt;aboutcode.net/knapsack&lt;/a&gt; to get started with Knapsack.&lt;/p&gt;
</content>
</entry>

<entry>
<title>Managing JavaScript</title>
<link href="http://aboutcode.net/2011/04/12/managing-javascript.html"/>
<updated>2011-04-12T00:00:00-07:00</updated>
<id>http://aboutcode.net/2011/04/12/managing-javascript</id>
<content type="html">&lt;p&gt;When it comes to writing rich web applications there is no escaping piles of JavaScript. I&#39;ve come to quite like the language. However, managing hundreds of JS files is starting to get a bit annoying. In a large application there will be:&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;Third-party libraries, such as jQuery, knockout, backbone, ES5 polyfills, etc&lt;/li&gt;
    &lt;li&gt;Shared scripts used by all parts of the application&lt;/li&gt;
    &lt;li&gt;Collections of files for each &quot;area&quot; of the application&lt;/li&gt;
    &lt;li&gt;Custom scripts for single pages&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;I expect to see a lot of JavaScript files in a well written project. As tempting as it is to stuff function after function into one poor file, please don&#39;t! Favour many smaller files that are scope limited and easy to understand.&lt;/p&gt;
&lt;p&gt;Working with JavaScript this way during development is very much at odds with production requirements. I like to keep each source file separate for sane debugging sessions. However, when deploying to production I want the scripts concatenated and minified into as few files as possible.&lt;/p&gt;
&lt;p&gt;Scripts files can depend on other script files. This means the order that scripts are loaded into a page matters.&lt;/p&gt;

&lt;h2&gt;Existing Solutions&lt;/h2&gt;
&lt;p&gt;I&#39;ve used &lt;a href=&quot;http://chirpy.codeplex.com/&quot;&gt;Chirpy&lt;/a&gt; in the past to build collections of JS files into logical units. However, this approach means I lose the one-to-one mapping of my original files. What&#39;s worse is that I have to manually maintain an XML file listing all the JS source files to build. This is tedious and feels like something the computer should do for me.&lt;/p&gt;
&lt;p&gt;Another alternative is &lt;a href=&quot;https://github.com/jetheredge/SquishIt&quot;&gt;SquishIt&lt;/a&gt;. SquishIt handles the dev-time vs. production experience nicely by outputting each source script tag when in debug mode. In release mode, a single minified script file is generated instead.&lt;/p&gt;
&lt;p&gt;Unfortunately, SquishIt still requires each source file to be listed in the relevant order.&lt;/p&gt;

&lt;h2&gt;What I want to see&lt;/h2&gt;
&lt;p&gt;Let&#39;s get rid of manually listing all our source scripts for the purposes of concentration and minification. Instead move the intent closer to the actual scripts themselves.&lt;/p&gt;
&lt;p&gt;If I have a script that depends on another script then let&#39;s declare that in the depending script. Visual Studio provides a special XML comment syntax to do exactly this:&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush:javascript&quot;&gt;/// &amp;ltreference path=&quot;myother.js&quot;/&amp;gt;
MyOtherFunction(1,2,3);&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;Documenting my dependencies this way will save my sanity when I come back to this code in a years&#39; time. Also, Visual Studio will now provide me with intellisense for any objects, functions, etc, exposed by the other script. This is a good thing since typos and dynamic languages do not mix!&lt;/p&gt;
&lt;p&gt;Also note that the references declaration is transient. If script C references script B, and script B references script A, then script C automatically gets a reference to script A as well. &lt;/p&gt;
&lt;p&gt;Next, clearly identify logical script file units. I listed examples of these at the start of this post. It makes sense to group the units of scripts into separate folders. E.g. ~/scripts/libs, ~/scripts/admin, ~/scripts/customers.&lt;/p&gt;
&lt;p&gt;Further sub-folders within those may still make sense for your project, but the top-level folder defines the unit. All files with a top-level folder will be concatenated in the correct order and minified into a single script.&lt;/p&gt;

&lt;h2&gt;Ordering the scripts&lt;/h2&gt;
&lt;p&gt;Remember the special &quot;references&quot; comments added to the scripts? We can use them to define a directed acyclic graph of dependencies. The scripts can then be topologically sorted and output in the correct order.&lt;/p&gt;
&lt;p&gt;The algorithm will need to account for dependencies between units. This means that the order that each unit is added into a page will be taken care of too.&lt;/p&gt;

&lt;h2&gt;Managing scripts&lt;/h2&gt;
&lt;p&gt;Maintaining a block of script tags in your HTML is fine for simple web pages. This does not scale for complex application with multiple regions, controls, components, etc. It&#39;s good practice to extract common bits of HTML into &quot;partials&quot;. However, if a partial requires a script to be loaded into the page as well then we have a problem.&lt;/p&gt;
&lt;p&gt;Do not output script tags with your partial!&lt;/p&gt;
&lt;p&gt;Your partial needs to somehow register that it requires a script to be referenced from the page. The page will then add all the required script tags in one place.&lt;/p&gt;
&lt;p&gt;The page script manager must be aware of debug and release mode. In debug mode a script tag is created for each source script. In release mode the minified script of each unit is produced instead.&lt;/p&gt;

&lt;h2&gt;Solution?&lt;/h2&gt;
&lt;p&gt;Sorry to disappoint you, but this is all just ideas for now! I&#39;ve had them floating around in my head and wanted to get them out in public for discussion.&lt;/p&gt;
&lt;p&gt;I&#39;d love to hear about how you are managing JavaScript.&lt;/p&gt;
&lt;p&gt;Please let me know what you think in the comments or on Twitter &lt;a href=&quot;http://twitter.com/andrewdavey&quot;&gt;@andrewdavey&lt;/a&gt;.&lt;/p&gt;</content>
</entry>

<entry>
<title>Caching versioned static files with ASP.NET MVC and IIS7</title>
<link href="http://aboutcode.net/2011/03/21/caching-versioned-static-files-with-asp-net-mvc-and-iis7.html"/>
<updated>2011-03-21T00:00:00-07:00</updated>
<id>http://aboutcode.net/2011/03/21/caching-versioned-static-files-with-asp-net-mvc-and-iis7</id>
<content type="html">&lt;p&gt;Correctly caching a website&#39;s content will improve the load time of pages.
There&#39;s no sense in making a web browser download the same stylesheets and images 
repeatedly. In fact, we want to avoid the web browser even doing tentative &quot;if not
modified&quot; requests. These all add up to extra HTTP connection overhead.
&lt;/p&gt;
&lt;p&gt;This article will show you how to configure IIS7 and use ASP.NET MVC to make sure 
your static files are always cached correctly.&lt;/p&gt;
&lt;h2&gt;Using max-age&lt;/h2&gt;
&lt;p&gt;IIS7 is easy to configure from your web application&#39;s Web.config file. Find the &amp;lt;configuration&amp;gt;/&amp;lt;system.webServer&amp;gt; section and add:&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: xml&quot;&gt;&amp;lt;staticContent&amp;gt;
    &amp;lt;!-- Tell client to cache static files for a year --&amp;gt;
    &amp;lt;clientCache cacheControlMode=&quot;UseMaxAge&quot;
                 cacheControlMaxAge=&quot;365.00:00:00&quot; /&amp;gt;
&amp;lt;/staticContent&amp;gt;&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;This tells IIS to add a cache-control header to all static files it serves.
The header specifies the &quot;max-age&quot; of a file to be 365 days. So once a web browser
has downloaded the file once, it won&#39;t request it again for a year.
&lt;/p&gt;
&lt;h2&gt;Versioning URLs&lt;/h2&gt;
&lt;p&gt;Websites change over time. We&#39;ll have a problem if we can&#39;t make a web browser 
download an updated stylesheet, image or (worst of all) javascript file. Therefore 
it&#39;s important to include a version number into the URL of any static file.&lt;/p&gt;
&lt;p&gt;When we update our website we can increment the version number to ensure the static
files are downloaded again.&lt;/p&gt;
&lt;p&gt;For this article, we&#39;ll assume all static files are within a directory called &quot;static&quot;
in the root of the website.&lt;/p&gt;
&lt;p&gt;Let&#39;s consider a file saved as &quot;/static/styles/site.css&quot;. In our HTML, we&#39;ll 
reference the stylesheet like this:&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: xml&quot;&gt;&amp;lt;link href=&quot;/static/1.0.0.0/styles/site.css&quot; type=&quot;text/css&quot; rel=&quot;stylesheet&quot;/&amp;gt;&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;Notice the insertion of a version number. Since we&#39;re using ASP.NET, I find it
convenient to use the application Assembly&#39;s version number. This is increased with each
build and deployment, so it guarantees we won&#39;t ever use stale files.&lt;/p&gt;
&lt;p&gt;I&#39;ll show automate this URL how to generation later. Let&#39;s first see how to make
IIS server the actual file from this modified URL.&lt;/p&gt;
&lt;p&gt;Add the following XML into your Web.config, in &amp;lt;configuration&amp;gt;/&amp;lt;system.webServer&amp;gt;:&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: xml&quot;&gt;&amp;lt;rewrite&amp;gt;
    &amp;lt;rules&amp;gt;
        &amp;lt;rule name=&quot;StaticFiles&quot; stopProcessing=&quot;true&quot;&amp;gt;
            &amp;lt;match url=&quot;static/[\d.]+/(.*)$&quot; /&amp;gt; 
            &amp;lt;action type=&quot;Rewrite&quot; url=&quot;static/{R:1}&quot; /&amp;gt;
            &amp;lt;!-- e.g. &quot;static/1.9.8.4/styles/site.css&quot; -&amp;gt; &quot;static/styles/site.css&quot; --&amp;gt;
        &amp;lt;/rule&amp;gt;
    &amp;lt;/rules&amp;gt;
&amp;lt;/rewrite&amp;gt;&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;This is using the IIS7 Rewrite Module. If you don&#39;t already have this already then 
&lt;a href=&quot;http://www.iis.net/download/URLRewrite&quot;&gt;Install URL Rewrite&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;As the comment in the XML explains we&#39;re matching static file urls that contain a 
version number and rewriting to the actual file on disk. The &quot;{R:1}&quot; refers to the 
text captured by &quot;(.*)&quot; in the match regular expression.&lt;/p&gt;
&lt;h2&gt;Generating versioned URLs&lt;/h2&gt;
&lt;p&gt;Manually maintain the version of each URL would be crazy. We can use an HTML helper 
to generate the correct URLs for us. Add this helper to your MVC web application.&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;using System.IO;
using System.Reflection;
using System.Web;
using System.Web.Mvc;

namespace StaticDemo.Helpers // Change this namespace to match your web application.
{
    public static class StaticFileHelper
    {
        static string assemblyVersion;

        static StaticFileHelper()
        {
            // This way of getting the assembly version works in medium trust.
            assemblyVersion = new AssemblyName(typeof(StaticFileHelper).Assembly.FullName).Version.ToString();
        }

        public static string StaticFile(this UrlHelper html, string filename)
        {
            var virtualPath = (
                html.RequestContext.HttpContext.IsDebuggingEnabled
                    ? DebugVirtualPath(filename, html.RequestContext.HttpContext.Server)
                    : ReleaseVirtualPath(filename)
            );

            var root = html.RequestContext.HttpContext.Request.ApplicationPath;
            if (root.Length &gt; 1) // e.g. &quot;/myapp&quot; instead of just &quot;/&quot;
            {
                virtualPath = root + virtualPath;
            }
            return virtualPath;
        }

        static string ReleaseVirtualPath(string filename)
        {
            // Insert the assembly version into the path (not the query string).
            // This seems to be more reliable when proxies are involved:
            // http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/
            return &quot;/static/&quot; + assemblyVersion + &quot;/&quot; + filename;
        }

        static string DebugVirtualPath(string filename, HttpServerUtilityBase server)
        {
            // Use query string to break caching. This means the file&#39;s path
            // still matches the development file system.
            var absoluteFilename = server.MapPath(&quot;~/static/&quot; + filename);
            var version = File.GetLastWriteTime(absoluteFilename).Ticks.ToString();
            var separator = (filename.Contains(&quot;?&quot;) ? &quot;&amp;&quot; : &quot;?&quot;);
            return &quot;/static/&quot; + filename + separator + &quot;nocache=&quot; + version;
        }
    }
}&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;This HTML helper creates the static versioned URL for a filename. Notice that it
behaves differently when the web application is in debug mode. While we&#39;re developing 
a website we&#39;ll be in debug mode. In this case we don&#39;t want caching by application version number.
Instead the helper appends the last write time of the file.&lt;/p&gt;
&lt;p&gt;Always be sure to set &amp;lt;configuration&amp;gt;/&amp;lt;system.web&amp;gt;/&amp;lt;compilation debug=&quot;false&quot;&amp;gt; when you
deploy your web application!&lt;/p&gt;
&lt;p&gt;Now make this helper available to your views. In &quot;Views\Web.config&quot;, add your 
helpers namespace into &amp;lt;configuration&amp;gt;/&amp;lt;system.web.webPages.razor&amp;gt;/&amp;lt;pages&amp;gt;/&amp;lt;namespaces&amp;gt; (for sexy Razor views),
or &amp;lt;configuration&amp;gt;/&amp;lt;system.web&amp;gt;/&amp;lt;pages&amp;gt;/&amp;lt;namespaces&amp;gt; (for horrid old ASPX views).&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: xml&quot;&gt;&amp;lt;add namespace=&quot;StaticDemo.Helpers&quot;/&amp;gt;&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;Change the namespace to match your web application.&lt;/p&gt;
&lt;p&gt;Now in our Razor view we use the helper:&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: xml&quot;&gt;&amp;lt;link href=&quot;@Url.StaticFile(&quot;styles/site.css&quot;)&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&amp;gt;&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;For those using ASPX views:&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: xml&quot;&gt;&amp;lt;link href=&quot;&amp;lt;%: Url.StaticFile(&quot;styles/site.css&quot;) %&amp;gt;&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&amp;gt;&lt;/pre&gt;&lt;/code&gt;

&lt;h2&gt;That&#39;s it!&lt;/h2&gt;
&lt;p&gt;You now have elegantly versioned static files. 
If you like what you&#39;ve read &lt;a href=&quot;http://twitter.com/andrewdavey&quot;&gt;follow me on Twitter&lt;/a&gt;
for regular web development tips, ideas and rants.&lt;/p&gt;</content>
</entry>

<entry>
<title>MVC Property Binder</title>
<link href="http://aboutcode.net/2011/03/12/mvc-property-binder.html"/>
<updated>2011-03-12T00:00:00-08:00</updated>
<id>http://aboutcode.net/2011/03/12/mvc-property-binder</id>
<content type="html">&lt;p&gt;
ASP.NET MVC has a rich model binder. Complex objects can be created from various bits of the HTTP request data. However, this isn&#39;t always enough and sometimes we need to extend the default binding behaviour.&lt;/p&gt;
&lt;p&gt;
In my application, I have a data structure to represent a &quot;change password&quot; request.&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;class ChangePassword {
  public string Username {get; set;}
  public string OldPassword {get; set;}
  public string NewPassword {get; set;}
  public string ConfirmNewPassword {get; set;}
}&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;
A controller action method receives this and performs the required update.&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;public ActionResult ChangePassword(ChangePassword change) { ... }&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;
An HTML form will provide the three password property values, but the Username property is different. The username must be that of the currently authenticated user. This value is contained in HttpContext.User.Identity.Name.&lt;/p&gt;
&lt;p&gt;
I don&#39;t want it allowing some evil user to pass in some other username, via the query string, for example. So I need to tell the MVC binder how to assign this property. This requires a custom model binder.&lt;/p&gt;
&lt;p&gt;
The problem is that MVC does not provide a way to set a custom model binder for a specific property.&lt;/p&gt;
&lt;p&gt;What I like to do is this:&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;class ChangePassword {
  [PropertyBinder(typeof(CurrentUsernameBinder))]
  public string Username {get;set;}
  public string OldPassword {get;set;}
  public string NewPassword {get;set;}
  public string ConfirmNewPassword {get;set;}
}&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;
PropertyBinder is a basic attribute that lets me declare the model binder to use.&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;public class PropertyBinderAttribute : Attribute
{
  public PropertyBinderAttribute(Type binderType)
  {
    BinderType = binderType;
  }

  public Type BinderType { get; private set; }
}&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;
For this new attribute to work, I have to override the default model binder like this:&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;public class CustomModelBinder : DefaultModelBinder
{
  protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
  {
    // Check if the property has the PropertyBinderAttribute, meaning
    // it&#39;s specifying a different binder to use.
    var propertyBinderAttribute = TryFindPropertyBinderAttribute(propertyDescriptor);
    if (propertyBinderAttribute != null)
    {
      var binder = CreateBinder(propertyBinderAttribute);
      var value = binder.BindModel(controllerContext, bindingContext);
      propertyDescriptor.SetValue(bindingContext.Model, value);
    }
    else // revert to the default behavior.
    {
      base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
    }
  }

  IModelBinder CreateBinder(PropertyBinderAttribute propertyBinderAttribute)
  {
    return (IModelBinder)DependencyResolver.Current.GetService(propertyBinderAttribute.BinderType);
  }

  PropertyBinderAttribute TryFindPropertyBinderAttribute(PropertyDescriptor propertyDescriptor)
  {
    return propertyDescriptor.Attributes
      .OfType&lt;PropertyBinderAttribute&gt;()
      .FirstOrDefault();
  }
}&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;
By overriding the BindProperty method, I can check for the attribute and call into the specified model binder.&lt;/p&gt;
&lt;p&gt;This line of code in Global.asax Application_Start to assign the new default binder:&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;System.Web.Mvc.ModelBinders.Binders.DefaultBinder = new CustomModelBinder();&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;
Incidentally, the username binder looks something like this:&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;public class ClientIdBinder : IModelBinder
{
  readonly HttpContextBase httpContext;

  public ClientIdBinder(HttpContextBase httpContext)
  {
    this.httpContext = httpContext;
  }

  public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
  {
    if (httpContext.User.Identity.IsAuthenticated)
    {
      return httpContext.User.Identity.Name;
    }

    bindingContext.ModelState.AddModelError(bindingContext.ModelName, &quot;User not signed in.&quot;); 
    
    return null;
  }
}&lt;/pre&gt;&lt;/code&gt;

&lt;p&gt;For more web development banter, with an MVC slant, &lt;a href=&quot;http://twitter.com/andrewdavey&quot;&gt;follow me on Twitter&lt;/a&gt;!&lt;/p&gt;
</content>
</entry>

<entry>
<title>Git Forked</title>
<link href="http://aboutcode.net/2011/03/03/gitforked.html"/>
<updated>2011-03-03T00:00:00-08:00</updated>
<id>http://aboutcode.net/2011/03/03/gitforked</id>
<content type="html">&lt;p&gt;I now use &lt;a href=&quot;http://github.com/&quot;&gt;GitHub&lt;/a&gt; almost exclusively as my project hosting provider. I have open source and private projects hosted there. GitHub really encourages the social aspects of open source. They also provide plenty of hand-holding while I&#39;m still learning git.&lt;/p&gt;
&lt;p&gt;As the creator of open source projects, the thing I hope for most is people getting involved. I want people to fork a project, edit the code and submit pull requests. So I created &lt;a href=&quot;http://gitforked.com/&quot;&gt;gitforked.com&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Git Forked creates social media style &quot;fork&quot; buttons that link to your GitHub repository page. You can put these buttons on your home page, blog, etc. The number of forks is shown next to the button, just like the numbers of tweets next to a Twitter tweet button.&lt;/p&gt;
&lt;p&gt;Here&#39;s an example button: &lt;a href=&quot;https://github.com/andrewdavey/postal&quot; class=&quot;gitforked-button&quot;&gt;Fork&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;So head over to &lt;a href=&quot;http://gitforked.com/&quot;&gt;gitforked.com&lt;/a&gt;, enter your repository URL and generate your very own fork button!&lt;/p&gt;

&lt;script src=&quot;http://gitforked.com/api/1.0/button.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
</content>
</entry>

<entry>
<title>CDNCatalog Updated</title>
<link href="http://aboutcode.net/2011/03/01/cdncatalog-updated.html"/>
<updated>2011-03-01T00:00:00-08:00</updated>
<id>http://aboutcode.net/2011/03/01/cdncatalog-updated</id>
<content type="html">&lt;p&gt;If you&#39;re building a modern website then you&#39;ll be needing some javascript libraries and css.&lt;/p&gt;
&lt;p&gt;I&#39;ve updated &lt;a href=&quot;http://cdncatalog.com/&quot;&gt;CDNCatalog.com&lt;/a&gt; with links to all the latest javascript and css resources hosted by Google, Microsoft, etc.&lt;/p&gt;
&lt;p&gt;The website now has easy one-click icons to copy either the URL or HTML snippet for a resource.&lt;/p&gt;
&lt;p&gt;So take a look and tell your friends!&lt;/p&gt;
</content>
</entry>

<entry>
<title>Handling Not Found with ASP.NET MVC3</title>
<link href="http://aboutcode.net/2011/02/26/handling-not-found-with-asp-net-mvc3.html"/>
<updated>2011-02-26T00:00:00-08:00</updated>
<id>http://aboutcode.net/2011/02/26/handling-not-found-with-asp-net-mvc3</id>
<content type="html">&lt;p&gt;
    A web application built using ASP.NET MVC can break in a few different places when
    handling a URL it does not recognise. By default, your user will receive a rather
    unfriendly default ASP.NET error page. Ideally, you should be catching these &amp;ldquo;not
    found&amp;rdquo; errors and displaying a more &lt;a href=&quot;http://www.codinghorror.com/blog/2007/03/creating-user-friendly-404-pages.html&quot;&gt;
        useful page&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
    First let&#39;s look at the places you need to watch for broken URLs in an ASP.NET MVC3
    application. Then I&#39;ll introduce a simple library you can use to handle all this.
&lt;/p&gt;
&lt;ol&gt;
    &lt;li&gt;
        &lt;p&gt;
            Missing action method on a controller&lt;/p&gt;
        &lt;p&gt;
            Imagine we have a controller called HomeController and a default route of &amp;ldquo;{controller}/{action}&amp;rdquo;
            in the route table. Then a URL with the path &amp;ldquo;home/epicfail&amp;rdquo; will be routed to the
            HomeController and look for an action method called &amp;ldquo;EpicFail&amp;rdquo;.
            &lt;/p&gt;
            &lt;p&gt;
            If the action method does not exist then the Controller&#39;s default HandleUnknownAction
            method is called and throws an HttpException, with 404 as the status code. ASP.NET
            then shows its nasty error page.
            &lt;/p&gt;
            &lt;p&gt;
            A possible solution is to override HandleUnknownAction and render your friendly
            404 page instead of throwing an exception.
        &lt;/p&gt;
    &lt;/li&gt;
    &lt;li&gt;
        &lt;p&gt;
            Missing controller&lt;/p&gt;
        &lt;p&gt;
            Given a route of &amp;ldquo;{controller}/{action}&amp;rdquo;, the URL &amp;ldquo;missing/example&amp;rdquo; will cause a
            search for a controller called &amp;ldquo;MissingController&amp;rdquo;. If this controller is not found
            then a 404 HttpException is thrown.
        &lt;/p&gt;
        &lt;p&gt;
            To catch this, you need to have a custom controller factory (IControllerFactory)
            that returns a special &amp;ldquo;not found&amp;rdquo; controller to handle the broken request.&lt;/p&gt;
    &lt;/li&gt;
    &lt;li&gt;
        &lt;p&gt;
            Unknown route&lt;/p&gt;
        &lt;p&gt;
            If the URL does not match any of the defined routes then a 404 HttpException is
            thrown. To intercept this you need to create a &amp;ldquo;catch-all&amp;rdquo; route. For example, &amp;ldquo;{*any}&amp;rdquo;
            and map this to some controller that will then show your friendly 404 page.&lt;/p&gt;
    &lt;/li&gt;
    &lt;li&gt;
        &lt;p&gt;
            Deliberate not found response&lt;/p&gt;
        &lt;p&gt;
            Sometimes your action methods need to say that a resource is not found. For example,
            a row with the given ID was not found in the database anymore. You may want to reuse
            a common &amp;ldquo;Not Found&amp;rdquo; view.&lt;/p&gt;
    &lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;
    Introducing NotFoundMvc&lt;/h2&gt;
&lt;p&gt;
    Correctly handling all the possible &amp;ldquo;not found&amp;rdquo; causes is non-trivial and is likely
    to be repeated in many MVC applications. Therefore I created the NotFoundMvc library.&lt;/p&gt;
&lt;p&gt;
    Add the library to your project via nuget: &lt;strong&gt;Install-Package NotFoundMvc&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;
    Or get the source code on GitHub: &lt;a href=&quot;https://github.com/andrewdavey/NotFoundMvc&quot;&gt;
        github.com/andrewdavey/NotFoundMvc&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;
    Referencing the NotFoundMvc.dll assembly from your web application project will
    cause it to auto-start with the application. (Thank you &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.web.preapplicationstartmethodattribute.aspx&quot;&gt;
        PreApplicationStartMethod&lt;/a&gt; .)&lt;/p&gt;
&lt;p&gt;
    NotFoundMvc will:&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;Handle all &amp;ldquo;not found&amp;rdquo; causes and render a friendly error view&lt;/li&gt;
    &lt;li&gt;Add a catch-all route to the end of the route table to handle unrecognised routes&lt;/li&gt;
    &lt;li&gt;Wrap the controller factory to handle missing controllers&lt;/li&gt;
    &lt;li&gt;Wrap the ActionInvoker of each created controller to handle missing actions&lt;/li&gt;
    &lt;li&gt;Provide a NotFoundViewResult you can use to return a NotFound view from your actions&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
    The wrapper objects pass through to the original implementations. So if, for example,
    you&#39;re using a custom controller factory already, it will still work as before.&lt;/p&gt;
&lt;p&gt;
    Installing the nugget package will also add a basic NotFound.cshtml view to the
    ~\Views\Shared folder. So if you&#39;re not using nugget, then please create this view
    manually. If you&#39;re using aspx views, or something else, change the file extension
    as required.&lt;/p&gt;
&lt;p&gt;
    The output of the NotFound view must be at least 512 bytes in length, otherwise
    IE and Chrome will show their own error page! The default NotFound.cshtml view includes
    padding spaces to avoid this.&lt;/p&gt;
&lt;p&gt;
    The source code for NotFoundMvc contains a sample project to demonstrate basic usage.&lt;/p&gt;
</content>
</entry>

<entry>
<title>MVC routing for public facing web applications</title>
<link href="http://aboutcode.net/2011/02/13/mvc-routing-for-public-facing-web-applications.html"/>
<updated>2011-02-13T00:00:00-08:00</updated>
<id>http://aboutcode.net/2011/02/13/mvc-routing-for-public-facing-web-applications</id>
<content type="html">&lt;p&gt;
    When building a public web application with ASP.NET MVC, I often want to divide
    the project into three major parts.
&lt;/p&gt;
&lt;ol&gt;
    &lt;li&gt;The publicly visible, marketing website with about pages, product tour, contact
        info, sign up, etc.&lt;/li&gt;
    &lt;li&gt;The actual application, secured behind a login form.&lt;/li&gt;
    &lt;li&gt;A system admin area, so I can manage user accounts, monitor reports, etc.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
    Areas, in MVC 2 and better, make it easy to slice up the three parts of the web
    application. Read on to learn how I set this up and get some useful tips you can use
    for your own applications.
&lt;/p&gt;
&lt;h2&gt;
    Everything is an Area&lt;/h2&gt;
&lt;p&gt;
    You probably want the public marketing pages to live at the root of your URL structure.
    So it&#39;s tempting to put the controllers and views into the top-level Controllers
    and Views folders. Don&#39;t do this. I don&#39;t see why the marketing junk should get
    special treatment. It&#39;s an area just like the application and the system admin areas.&lt;/p&gt;
&lt;p&gt;
    So add three areas to your MVC project called &quot;Public&quot;, &quot;App&quot;, and &quot;Admin&quot;. The
    default route registration for these is mostly OK, except for Public. We don&#39;t want
    &quot;public&quot; in the URLs. However, simply editing the route registration for Public
    will cause a potential routing failure. The order of route registration matters.&lt;/p&gt;
&lt;p&gt;
    If, by chance, the Public area is registered before the other two, then its default
    route of &quot;{controller}/{action}/{id}&quot; will greedily steal any URL heading for App
    or Admin. For example, the URL &quot;app/home/index&quot; would end up looking for a controller
    in Public called &quot;AppController&quot; and an action method called &quot;Home&quot;. This is not
    what we intended!&lt;/p&gt;
&lt;p&gt;
    To remedy the situation we must force the Public area to general route to be added
    after all other areas. Cut it out of the PublicAreaRegistration.cs file. Move it
    to Application_Start in Global.asax, after the call to AreaRegistration.RegisterAllAreas.&lt;/p&gt;
&lt;p&gt;
    Then make the following changes to make it still behave as an Area route:&lt;/p&gt;
&lt;code&gt;
    &lt;pre class=&quot;brush: csharp&quot;&gt;AreaRegistration.RegisterAllAreas(); // Force App and Admin to run first
var publicRoute = routes.MapRoute(
    &quot;PublicRoute&quot;,
    &quot;{controller}/{action}/{id}&quot;,
    new { controller = &quot;Home&quot;, action = &quot;Index&quot;, id = UrlParameter.Optional },
    new[] { typeof(Areas.Public.Controllers.HomeController).Namespace }
);
publicRoute.DataTokens[&quot;Area&quot;] = &quot;Public&quot;;&lt;/pre&gt;
&lt;/code&gt;
&lt;p&gt;
    This gives the route the correct namespace to look for controllers and assigns the
    Area name.&lt;/p&gt;
&lt;p&gt;
    URLs heading for App and Admin will reach their intended destinations. You can still
    keep custom routes in Public&#39;s registration. Just make sure they aren&#39;t too general,
    capturing URLs for areas.&lt;/p&gt;
&lt;p&gt;
    I hope you found this tip useful. &lt;a href=&quot;http://twitter.com/andrewdavey&quot;&gt;Follow me
        on Twitter&lt;/a&gt; for constant web application development banter!&lt;/p&gt;
</content>
</entry>

<entry>
<title>Displaying a flash message with ASP.NET MVC</title>
<link href="http://aboutcode.net/2010/11/30/display-a-flash-message-with-asp-net-mvc.html"/>
<updated>2010-11-30T00:00:00-08:00</updated>
<id>http://aboutcode.net/2010/11/30/display-a-flash-message-with-asp-net-mvc</id>
<content type="html">&lt;p&gt;Post-Redirect-Get is a common pattern used in MVC applications. You show a form to the user, they enter their data and click a button to post it to the server. A controller processes the form and returns an HTTP redirect response to the web browser. The browser follows the redirect by getting the given URL.&lt;/p&gt;
&lt;p&gt;The form post controller action may need to show a message to the user. For example, saying &quot;your message has been sent&quot;. So you have to pass this message to the next page somehow.&lt;/p&gt;
&lt;h2&gt;The Wrong Way&lt;/h2&gt;
&lt;p&gt;One approach is to use the controller&#39;s TempData dictionary. TempData, by default, uses the session to pass data between requests. The post action method will put the message into TempData. The page we&#39;re redirecting to will read TempData and display the message.&lt;/p&gt;
&lt;p&gt;Unfortunately using TempData will cause an annoying bug when the browser has already cached the final page. The redirect tells the browser to get the page, but the browser has it cached. So the page is shown without the extra call to the server. This means the TempData is never read.&lt;/p&gt;
&lt;p&gt;What&#39;s worse is some subsequent page request may not be cached and actually read the TempData which was not intended for it!&lt;/p&gt;
&lt;h2&gt;A Better Way&lt;/h2&gt;
&lt;p&gt;Use a cookie to send the message along with the redirect request. The controller action method will look like:&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;public ActionResult ProcessForm() {
    // ... process form ...
    Response.Cookies.Add(new HttpCookie(&quot;FlashMessage&quot;, &quot;Data processed&quot;) { Path = &quot;/&quot; }));
    return RedirectToAction(&quot;Index&quot;);
}
&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;In the view we&#39;re redirecting to, use JavaScript to read the cookie and display the message. Then delete the cookie so the message is not shown again the next time we load this page.&lt;/p&gt;
&lt;p&gt;I use &lt;a href=&quot;https://github.com/carhartl/jquery-cookie&quot;&gt;jquery.cookie.js&lt;/a&gt; to handle the cookie access. I use a jQuery extension that wraps up the flash message display code:&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: javascript&quot;&gt;$.fn.flashMessage = function (options) {
    var target = this;
    options = $.extend({}, options, { timeout: 3000 });
    if (!options.message) {
        options.message = getFlashMessageFromCookie();
        deleteFlashMessageCookie();
    }
    if (options.message) {
        if (typeof options.message === &quot;string&quot;) {
            target.html(&quot;&lt;span&gt;&quot; + options.message + &quot;&lt;/span&gt;&quot;);
        } else {
            target.empty().append(options.message);
        }
    }

    if (target.children().length === 0) return;

    target.fadeIn().one(&quot;click&quot;, function () {
        $(this).fadeOut();
    });

    if (options.timeout &gt; 0) {
        setTimeout(function () { target.fadeOut(); }, options.timeout);
    }

    return this;

    function getFlashMessageFromCookie() {
        return $.cookie(&quot;FlashMessage&quot;);
    }

    function deleteFlashMessageCookie() {
        $.cookie(&quot;FlashMessage&quot;, null, { path: &#39;/&#39; });
    }
};
&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;The view contains a div to show the message:&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: xml&quot;&gt;&amp;lt;div id=&quot;flash-message&quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;The flash message extension is called using:&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: javascript&quot;&gt;$(function() { $(&quot;#flash-message&quot;).flashMessage(); });&lt;/pre&gt;&lt;/code&gt;
</content>
</entry>

<entry>
<title>Bandage - Add properties to view models at runtime</title>
<link href="http://aboutcode.net/2010/11/19/Bandage-add-properties-to-view-models-at-runtime.html"/>
<updated>2010-11-19T00:00:00-08:00</updated>
<id>http://aboutcode.net/2010/11/19/Bandage-add-properties-to-view-models-at-runtime</id>
<content type="html">&lt;p&gt;This post introduces the &lt;a href=&quot;https://github.com/andrewdavey/Bandage&quot;&gt;Bandage&lt;/a&gt; project for ASP.NET MVC.&lt;/p&gt;
&lt;h2&gt;Introduction&lt;/h2&gt;
&lt;p&gt;Are you a pragmatic ASP.NET MVC web developer? I like to think I am. When working with simple entities it feels like overkill to use separate view model objects in my views. I&#39;d rather just send my entity directly to the view and get on with something more fun (like delivering business value!)&lt;/p&gt;
&lt;p&gt;Whilst AutoMapper does a great job of conventionally mapping entities into view models, I&#39;d rather not have to create the view model class when it&#39;s essentially a property-by-property mirror of my entity.&lt;/p&gt;
&lt;p&gt;Nothing stops me sending entities directly to the view. However, things get messy when I need to display information derived from properties of the entities. I end up resorting to helpers, extension methods and other contraptions that don&#39;t feel as natural as simply getting a property value. Furthermore, when using dynamic view models, extension methods do not work, so they&#39;re no good anyway.&lt;/p&gt;
&lt;p&gt;If I later decide to man-up and create real view models, I&#39;d then have to replace all helper calls in my view with properties. Have you tried refactoring view code? It&#39;s not fun!&lt;/p&gt;
&lt;p&gt;I created the Bandage library to solve this problem. Read on for a simple example and learn what Bandage can do for you.&lt;/p&gt;

&lt;h2&gt;Use Case&lt;/h2&gt;
&lt;p&gt;Let&#39;s take a use case I hit quite often when developing MVC web applications. We have some list of objects, products for example, to show on the screen. For each product, we want a hyperlink to a details page.&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;class Product {
    public int Id { get; set; }
    public string Name { get; set; }
}&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;The URL for a product details page is formed using the Id and the Name properties. The Name property will be processed to create a &quot;slug&quot; (a URL safe version of the actual Name). This is to be more SEO-friendly. We keep the Id in the URL to keep our coding easy.&lt;/p&gt;
&lt;p&gt;For example: The product &lt;br/&gt;&lt;samp&gt;new Product { Id = 1, Name = &quot;Interwebz for Dummies&quot; }&lt;/samp&gt;&lt;br/&gt;will have the URL &lt;samp&gt;/product/1/interwebz-for-dummies&lt;/samp&gt;&lt;/p&gt;
&lt;p&gt;My MVC route set up defines the route as follows:&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;routes.RouteUrl(
    &quot;ProductDetails&quot;,
    &quot;product/{id}/{slug}&quot;,
    new { controller = &quot;Product&quot;, action=&quot;Details&quot; }
);&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;The ProductController List action will get the products and send them to the view like this:&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;public ActionResult List() {
    ViewModel.Products = ProductRepository.GetAll();
    Return View();
}&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;The List view is then something like:&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: xml&quot;&gt;&amp;lt;ul&amp;gt;@foreach (Product product in View.Products) {
    &amp;lt;li&amp;gt;&amp;lt;a href=&quot;Url.RouteUrl(&quot;ProductDetails&quot;, new { id = product.Id, slug = Util.GetSlug(product.Name) })&quot;&amp;gt;@product.Name&amp;lt;/a&amp;gt;&amp;lt;/li&amp;gt;
}&amp;lt;/ul&amp;gt;&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;Code like that, in my opinion, does not belong in the view. It&#39;s complex and really doesn&#39;t express the intent well.&lt;/p&gt;
&lt;p&gt;It would be so much nicer to write the following.&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: xml&quot;&gt;&amp;lt;ul&amp;gt;@foreach (var product in View.Products) {
    &amp;lt;li&amp;gt;&amp;lt;a href=&quot;@product.Url&quot;&amp;gt;@product.Name&amp;lt;/a&amp;gt;&amp;lt;/li&amp;gt;
}&amp;lt;/ul&amp;gt;&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;We simply need a way to add an extra property to Product. We don&#39;t want the Url property in our business object, it&#39;s purely a web-thing. We don&#39;t want to create a view model, that&#39;s overkill for simple situations like this.&lt;/p&gt;
&lt;p&gt;Notice that the product variable in the second code snippet is dynamically typed. This is because View is dynamic, so anything you get from it is also typed as dynamic. This dynamism is where we can inject some magic pixie dust.&lt;/p&gt;

&lt;h2&gt;Say hello to Bandage&lt;/h2&gt;
&lt;p&gt;Bandage is a small library which lets you define dynamic view models and then effectively monkey patch properties onto existing types. So, for our example, we&#39;ll have Product objects in the view model and then add a Url property to each product.&lt;/p&gt;
&lt;p&gt;The controller List action changes from before to this:&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;public ActionResult List() {
    var viewmodel = new Bandage.DynamicViewModel();
    viewmodel.Products = ProductRepository.GetAll();
    viewmodel.Add(DynamicProperty.For&amp;lt;Product&amp;gt;(&quot;Url&quot;, product =&amp;gt; ProductUrl(product)));
    Return View(viewmodel);
}

private string ProductUrl(Product p) {
    return Url.RouteUrl(&quot;ProductDetails&quot;, new { id = product.Id, slug = Util.GetSlug(product.Name) });
}&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;The key line of code there is when we add a DynamicProperty for the Product type. We provide the name of the property and a lambda that will return the value for a given Product. This is registered for the entire view model. So any Product object, anywhere in the object graph, will have this dynamic property available.&lt;/p&gt;
&lt;p&gt;The view can now use this dynamic view model and its magic dynamic properties.&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: xml&quot;&gt;
&amp;lt;ul&amp;gt;@foreach (var product in Model.Products) {
    &amp;lt;li&amp;gt;&amp;lt;a href=&quot;@product.Url&quot;&amp;gt;@product.Name&amp;lt;/a&amp;gt;&amp;lt;/li&amp;gt;
}&amp;lt;/ul&amp;gt;&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;Note: We are passing the viewmodel in to the view&#39;s Model property, rather than using the View object as before. Model is also typed as dynamic however in this case. This is because Controller&#39;s ViewModel property is readonly so we can&#39;t set it to our own object. Please vote on the CodePlex issue to have this fixed.&lt;/p&gt;

&lt;h2&gt;Behind the curtain&lt;/h2&gt;
&lt;p&gt;DynamicViewModel intercepts any attempt to get a property and returns a special wrapper object instead of the original value. This wrapper is also dynamic and intercepts property calls and other kinds of member access.&lt;/p&gt;
&lt;p&gt;When we ask for the Url property of Product, the wrapper first checks if a DynamicProperty added to the view model can be used instead. The product object is passed to the lambda we register in the controller. This then returns the value.&lt;/p&gt;
&lt;p&gt;All other regular member access is delegated back to the wrapped object.&lt;/p&gt;

&lt;h2&gt;Try Bandage for yourself&lt;/h2&gt;
&lt;p&gt;Bandage is an open source library (MIT License). You can get the &lt;a href=&quot;https://github.com/andrewdavey/Bandage&quot;&gt;source code at GitHub&lt;/a&gt;. Feel free to fork, improve and send me pull requests.&lt;/p&gt;
&lt;p&gt;The dynamic object wrapper is still beta-quality and needs some serious testing. However it does work for my meagre needs.&lt;/p&gt;
&lt;p&gt;I&#39;d love to hear what you think about Bandage. Give me a shout on twitter &lt;a href=&quot;http://twitter.com/andrewdavey&quot;&gt;@andrewdavey&lt;/a&gt; or leave a comment here.&lt;/p&gt;
</content>
</entry>

<entry>
<title>Going Postal - Generating email with ASP.NET MVC View Engines</title>
<link href="http://aboutcode.net/2010/11/17/going-postal-generating-email-with-aspnet-mvc-view-engines.html"/>
<updated>2010-11-17T00:00:00-08:00</updated>
<id>http://aboutcode.net/2010/11/17/going-postal-generating-email-with-aspnet-mvc-view-engines</id>
<content type="html">&lt;h2&gt;
    Preamble&lt;/h2&gt;
&lt;p&gt;
    The .NET framework provides a simple API for sending email. I assume you are already
    acquainted with the handy namespace &lt;samp&gt;System.Net.Mail&lt;/samp&gt;. However, dynamically generating
    the content of an email is still a bit tricky. Code that concatenates strings and
    variables is no fun to write or read!&lt;/p&gt;
&lt;p&gt;
    What we need is a way to write text (or html) templates which will be rendered with
    some data. ASP.NET MVC already has exactly this in the form of Views. So let&#39;s reuse
    the view engine infrastructure to create our emails.&lt;/p&gt;
&lt;p&gt;
    I created a simple library called &lt;a href=&quot;https://github.com/andrewdavey/postal&quot;&gt;Postal&lt;/a&gt;
    that does just that. Read on to find out more.&lt;/p&gt;
&lt;h2&gt;
    Postal in action&lt;/h2&gt;
&lt;p&gt;
    First, let&#39;s see what an email view will look like. I&#39;m using the excellent Razor
    view engine (coming with MVC3).&lt;/p&gt;
&lt;p&gt;
    &lt;samp&gt;Example.cshtml&lt;/samp&gt;&lt;/p&gt;
&lt;code&gt;
    &lt;pre class=&quot;brush: plain&quot;&gt;To: @View.To
From: example@website.com
Subject: @View.Subject

Hello,
This email was generated using Postal for asp.net mvc on @View.Date.ToShortDateString()
Message follows:
@View.Message

Thanks!&lt;/pre&gt;
&lt;/code&gt;
&lt;p&gt;
    This email is just plain text, but it could contain HTML instead for richer formatting
    options.&lt;/p&gt;
&lt;p&gt;
    Notice also that we are defining some email headers (To, From, Subject) at the top.
    Postal makes it easy to define everything about the email in a single file, rather
    than having to set the headers in code. Postal will parse the headers out of the
    rendered view and apply them to the outgoing email message.&lt;/p&gt;
&lt;p&gt;
    Since this is a regular Razor view, we can use the handy
    &lt;samp&gt;View&lt;/samp&gt;
    dynamic object to access view data. This data is populated from code. Let&#39;s see
    an example controller action that will send this email.&lt;/p&gt;
&lt;code&gt;
    &lt;pre class=&quot;brush: csharp&quot;&gt;public ActionResult Send(string to, string subject, string message)
{
    dynamic email = new Email(&quot;Example&quot;);
    email.To = to;
    email.Subject = subject;
    email.Message = message;
    email.Date = DateTime.UtcNow;

    service.Send(email);

    return RedirectToAction(&quot;Sent&quot;);
}
&lt;/pre&gt;
&lt;/code&gt;
&lt;p&gt;
    This code creates a new Email object, passing the name of the email view to use.
    Postal will look for email views in
    &lt;samp&gt;~/Views/Emails/&lt;/samp&gt;. So our email view is at
    &lt;samp&gt;~/Views/Emails/Example.cshtml&lt;/samp&gt;.&lt;/p&gt;
&lt;p&gt;
    We&#39;ve typed the Email object as dynamic. This lets us define the properties we want
    at runtime, without having to create an explicit view model class. I like this lightweight
    approach. (If you don&#39;t, feel free to send me a pull request!)&lt;/p&gt;
&lt;p&gt;
    The Email object is building up a
    &lt;samp&gt;ViewDataDictionary&lt;/samp&gt;
    internally, ready to send to the view for rendering.&lt;/p&gt;
&lt;p&gt;
    Once the email object is ready to send, we&#39;re calling the
    &lt;samp&gt;service&lt;/samp&gt;
    object. This is a field of the controller.&lt;/p&gt;
&lt;code&gt;
    &lt;pre class=&quot;brush: csharp&quot;&gt;public class HomeController : Controller
{
    // In real code this should be injected by an IoC container.
    IEmailService service = new EmailService(ViewEngines.Engines);

    // ... action methods here ...
}
&lt;/pre&gt;
&lt;/code&gt;
&lt;p&gt;
    The EmailService manages finding the view, rendering the text, parsing the headers
    and finally sending the email.&lt;/p&gt;
&lt;p&gt;
    Email is sent using the System.Net.Mail.SmtpClient class. You can configure the
    SMTP settings in web.config. For example, we can simple write the emails to a folder
    for testing purposes.&lt;/p&gt;
&lt;code&gt;
    &lt;pre class=&quot;brush: xml&quot;&gt;&amp;lt;configuration&amp;gt;
    &amp;lt;system.net&amp;gt;
        &amp;lt;mailSettings&amp;gt;
            &amp;lt;smtp deliveryMethod=&amp;quot;SpecifiedPickupDirectory&amp;quot;&amp;gt;
                &amp;lt;specifiedPickupDirectory pickupDirectoryLocation=&amp;quot;c:\email&amp;quot;/&amp;gt;
                &amp;lt;network host=&amp;quot;localhost&amp;quot;/&amp;gt;
            &amp;lt;/smtp&amp;gt;
        &amp;lt;/mailSettings&amp;gt;
    &amp;lt;/system.net&amp;gt;
&amp;lt;/configuration&amp;gt;
&lt;/pre&gt;
&lt;/code&gt;
&lt;h2&gt;
    Get the code&lt;/h2&gt;
&lt;p&gt;
    Postal is something I put together in an afternoon. So the usual warnings about
    code you find on the internet apply! That said, head over to GitHub and grab the
    source:&lt;/p&gt;
&lt;p&gt;
    &lt;a href=&quot;https://github.com/andrewdavey/postal&quot;&gt;https://github.com/andrewdavey/postal&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;There&#39;s a sample project in there as well that puts the code from this post together
into a basic web application.&lt;/p&gt;
&lt;p&gt;
    If you want to change Postal, fix bugs, etc, please fork the repository and send me
    pull requests. I love to see people getting involved with open source projects.
    (Postal has the MIT License.)&lt;/p&gt;
&lt;p&gt;
    For questions and discussion, either follow me on twitter 
    &lt;a href=&quot;http://twitter.com/andrewdavey&quot;&gt;@andrewdavey&lt;/a&gt; or leave a comment here.&lt;/p&gt;
</content>
</entry>

<entry>
<title>List GitHub projects using JavaScript</title>
<link href="http://aboutcode.net/2010/11/11/list-github-projects-using-javascript.html"/>
<updated>2010-11-11T00:00:00-08:00</updated>
<id>http://aboutcode.net/2010/11/11/list-github-projects-using-javascript</id>
<content type="html">&lt;p&gt;Do you use GitHub? Got a blog/website? Then read on for a handy bit of JavaScript.&lt;/p&gt;
&lt;h2&gt;Preamble&lt;/h2&gt;
&lt;p&gt;&lt;a href=&quot;http://github.com&quot;&gt;GitHub&lt;/a&gt; is simply fantastic. If you&#39;re into open source then it
really is the place to host your work. Heck, I even use it for private projects as well.
&lt;/p&gt;
&lt;p&gt;If you have some kind of blog or personal website why not promote and show-off your projects?
It&#39;s exactly what I&#39;m doing here. Just look at my &lt;a href=&quot;/&quot;&gt;home page&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The list of projects is generated using some simple JavaScript. Read on to get the code.&lt;/p&gt;

&lt;h2&gt;Get the code&lt;/h2&gt;
&lt;p&gt;Before I go further, I must say that I originally copied this code from &lt;a href=&quot;http://jointheconversation.org/&quot;&gt;jointheconversation.org&lt;/a&gt;. However, I&#39;ve made enough changes that I think it&#39;s worth posting here to share the love.&lt;/p&gt;
&lt;p&gt;In your HTML add a &lt;samp&gt;&amp;lt;div&amp;gt;&lt;/samp&gt; with an ID. The list of projects will be inserted
here.&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: xml&quot;&gt;&amp;lt;html&amp;gt;
  ...
  &amp;lt;div id=&quot;github-projects&quot;&amp;gt;&amp;lt;/div&amp;gt;
  ...
&amp;lt;/html&amp;gt;&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;Next, just before &lt;samp&gt;&amp;lt;/body&amp;gt;&lt;/samp&gt;, add these scripts.&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: xml&quot;&gt;
&amp;lt;script src=&quot;http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js&quot; type=&quot;text/javascript&quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script src=&quot;/scripts/github.js&quot; type=&quot;text/javascript&quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script type=&quot;text/javascript&quot;&amp;gt;
  $(function() {
    $(&quot;#github-projects&quot;).loadRepositories(&quot;andrewdavey&quot;);
  });
&amp;lt/script&amp;gt;
&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;Feel free to load jQuery from wherever you usually do. I just happen to like using a CDN.&lt;/p&gt;
&lt;p&gt;Make sure you replace &quot;andrewdavey&quot; with whatever github username you want to display
repositories for.&lt;/p&gt;
&lt;p&gt;Finally, create the &lt;samp&gt;/scripts/github.js&lt;/samp&gt; file. Here comes the magic.&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: js&quot;&gt;jQuery.githubUser = function(username, callback) {
  jQuery.getJSON(&quot;http://github.com/api/v1/json/&quot; + username + &quot;?callback=?&quot;, callback);
}

jQuery.fn.loadRepositories = function(username) {
  this.html(&quot;&amp;lt;span&amp;gt;Querying GitHub for repositories...&amp;lt;/span&amp;gt;&quot;);

  var target = this; 
  $.githubUser(username, function(data) {
    var repos = data.user.repositories;
    sortByNumberOfWatchers(repos);

    var list = $(&#39;&amp;lt;dl/&amp;gt;&#39;);
    target.empty().append(list);
    $(repos).each(function() {
      list.append(&#39;&amp;lt;dt&amp;gt;&amp;lt;a href=&quot;&#39;+ this.url +&#39;&quot;&amp;gt;&#39; + this.name + &#39;&amp;lt;/a&amp;gt;&amp;lt;/dt&amp;gt;&#39;);
      list.append(&#39;&amp;lt;dd&amp;gt;&#39; + this.description + &#39;&amp;lt;/dd&amp;gt;&#39;);
    });
  });

  function sortByNumberOfWatchers(repos) {
    repos.sort(function(a,b) {
      return b.watchers - a.watchers;
    });
  }
};
&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;I hope that code is fairly self-explanatory. It&#39;s extending jQuery with a
function that will query GitHub for information about the given username.
A definition list is generated to display the repositories.&lt;/p&gt;
&lt;p&gt;Please feel free to use the code, change it, etc. Maybe even let me know if you find
it useful, I&#39;m on twitter &lt;a href=&quot;http://twitter.com/andrewdavey&quot;&gt;@andrewdavey&lt;/a&gt;!&lt;/p&gt;
</content>
</entry>

<entry>
<title>OpenWrap - Package management for .NET</title>
<link href="http://aboutcode.net/2010/11/10/openwrap-package-management-for-net.html"/>
<updated>2010-11-10T00:00:00-08:00</updated>
<id>http://aboutcode.net/2010/11/10/openwrap-package-management-for-net</id>
<content type="html">&lt;p&gt;One of the open source projects I&#39;m helping with is &lt;a href=&quot;http://openwrap.org&quot;&gt;OpenWrap&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;OpenWrap is a package manager for .NET. We&#39;re always looking for awesome .NET developers
to help out, so if you&#39;re interested please get in touch.&lt;/p&gt;
&lt;p&gt;The main website has all the details and links to source code: &lt;a href=&quot;http://openwrap.org&quot;&gt;www.openwrap.org&lt;/a&gt;&lt;/p&gt;
</content>
</entry>

<entry>
<title>Nested layout pages in Razor</title>
<link href="http://aboutcode.net/2010/11/08/nested-layout-pages-in-razor.html"/>
<updated>2010-11-08T00:00:00-08:00</updated>
<id>http://aboutcode.net/2010/11/08/nested-layout-pages-in-razor</id>
<content type="html">&lt;p&gt;This post is for people using the Razor view engine in ASP.NET MVC3.&lt;/p&gt;
&lt;h2&gt;Preamble&lt;/h2&gt;
&lt;p&gt;
In any reasonably sized website you will want to use layout pages for the common header 
and footer parts of HTML. Razor makes this easy and the syntax is elegant (especially
when compared to the old webforms view engine). However, on more complex websites there
is often a need to nest layouts.
&lt;/p&gt;
&lt;p&gt;
Consider a web application that has some common scripts and styles across all pages, but
a number of &quot;areas&quot; that have their own HTML structure. For example, a &quot;public&quot; area, an
&quot;admin&quot; area and a &quot;customer&quot; area. We&#39;d like to define a layout for the top-level HTML,
stylesheets and scripts. Then define layouts for each area and have them inherit from 
the top-level layout.
&lt;/p&gt;
&lt;h2&gt;Nested Layouts&lt;/h2&gt;
&lt;p&gt;
The top-level layout looks like a regular Razor layout. Let&#39;s create a file:&lt;br/&gt;
&lt;samp&gt;~/Views/Shared/_site.cshtml&lt;/samp&gt;
&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: xml&quot;&gt;
&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
  &amp;lt;title&amp;gt;@View.Title&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
  @RenderBody()
  &amp;lt;p&amp;gt;Copyright Me 2010&amp;lt;/p&amp;gt;
  &amp;lt;script type=&quot;text/javascript&quot; src=&quot;/scripts/jquery.js&quot;&amp;gt;&amp;lt;/script&amp;gt;
  @RenderSection(&quot;scripts&quot;, required: false)
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;Note that this top-level layout defines where it&#39;s inner content will go (RenderBody) 
and also has an optional &quot;scripts&quot; section. Pages using this layout will be able to 
specify the extra scripts they need in that section.&lt;/p&gt;
&lt;p&gt;For each area, we can now create a nested layout page. For example, in the &quot;Public&quot; 
area we&#39;ll create a file:&lt;br/&gt;
&lt;samp&gt;~/Areas/Public/Views/Shared/_public.cshtml&lt;/samp&gt;&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: xml&quot;&gt;@{ Layout = &quot;~/Views/Shared/_site.cshtml&quot;; }
&amp;lt;div id=&quot;public&quot;&amp;gt;
  &amp;lt;p&amp;gt;public header&amp;lt;/p&amp;gt;
  @RenderBody()
  &amp;lt;p&amp;gt;public footer&amp;lt;/p&amp;gt;
&amp;lt;/div&amp;gt;
@section scripts {
  &amp;lt;script type=&quot;text/javascript&quot; src=&quot;/scripts/public.js&quot;&amp;gt;&amp;lt;script&amp;gt;
  @RenderSection(&quot;scripts&quot;, required: false)
}
&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;This nested layout inherits from the top-level layout. It adds some HTML common to all
pages in the public area and defines where the page content will go (RenderBody).&lt;/p&gt;
&lt;p&gt;It also has to redefine the scripts section. 
This has to be there even when not actually adding any HTML to the 
section, otherwise content pages will not be able to add to the section. This is just 
like nested master pages in webforms using ContentPlaceholders.&lt;/p&gt;
&lt;p&gt;A view in the public area will look like this:&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: xml&quot;&gt;@{
  Layout = &quot;~/Areas/Public/Views/Shared/_public.cshtml&quot;;
  View.Title = &quot;Home Page&quot;;
}
&amp;lt;p&amp;gt;Welcome to my public website!&amp;lt;/p&amp;gt;
&lt;/pre&gt;&lt;/code&gt;
&lt;h2&gt;End Result&lt;/h2&gt;
&lt;p&gt;When the home page view is rendered the top-level and area-level layouts are nested
correctly. The output will look like this:&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: xml&quot;&gt;
&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
  &amp;lt;title&amp;gt;Home Page&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
  &amp;lt;div id=&quot;public&quot;&amp;gt;
    &amp;lt;p&amp;gt;public header&amp;lt;/p&amp;gt;
    &amp;lt;p&amp;gt;Welcome to my public website!&amp;lt;/p&amp;gt;
    &amp;lt;p&amp;gt;public footer&amp;lt;/p&amp;gt;
  &amp;lt;/div&amp;gt;
  &amp;lt;p&amp;gt;Copyright Me 2010&amp;lt;/p&amp;gt;
  &amp;lt;script type=&quot;text/javascript&quot; src=&quot;/scripts/jquery.js&quot;&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;script type=&quot;text/javascript&quot; src=&quot;/scripts/public.js&quot;&amp;gt;&amp;lt;script&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/pre&gt;&lt;/code&gt;
</content>
</entry>

<entry>
<title>Hotmod - HTML Output Modification</title>
<link href="http://aboutcode.net/2010/11/03/hotmod-html-output-modification.html"/>
<updated>2010-11-03T00:00:00-07:00</updated>
<id>http://aboutcode.net/2010/11/03/hotmod-html-output-modification</id>
<content type="html">&lt;p&gt;This post introduces the motivation behind the &lt;a href=&quot;http://github.com/andrewdavey/hotmod&quot;&gt;Hotmod&lt;/a&gt; project.
&lt;/p&gt;
&lt;h2&gt;Preamble&lt;/h2&gt;
&lt;p&gt;Using ASP.NET to generate HTML, either with webforms or MVC, can leave
the resulting output looking somewhat messy. The indentation is inconsistent 
and can be harder to debug when a viewing a page&#39;s source.
&lt;/p&gt;
&lt;p&gt;Also, when deploying your application in release mode, do you need pretty 
looking HTML? You could actually &quot;minify&quot; the HTML by removing all the 
insignificant whitespace between tags; Just like you can with CSS and 
JavaScript.
&lt;/p&gt;
&lt;p&gt;Inline HTML generation using server-side controls or helpers is great on an 
ad-hoc basis, but sometimes this gets very un-DRY. For example, say you want to
enter application relative URLs in your HTML and have them expanded at runtime 
to their equivalent full paths. This is essential when your web application is
going to run inside a virtual directory, not at the root.&lt;/p&gt;
&lt;p&gt;In ASP.NET MVC you&#39;ll probably write something like: &lt;br/&gt;
&lt;code&gt;&lt;pre&gt;&amp;lt;a href=&quot;&amp;lt;%: Url.Content(&quot;~/content/foo.html&quot;) %&amp;gt;&quot;&amp;gt;foo&amp;lt;/a&amp;gt;&lt;/pre&gt;&lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;That works, but I think the intent could be clearer.&lt;/p&gt;
&lt;p&gt;Why can&#39;t we just type:&lt;/p&gt;
&lt;code&gt;&lt;pre&gt;&amp;lt;a href=&quot;~/content/foo.html&quot;&amp;gt;foo&amp;lt;/a&amp;gt;&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;
and establish a convention that all URLs in the HTML that start with a &quot;~&quot;
need to be expanded into their absolute form?
&lt;/p&gt;
&lt;p&gt;What we need is a post-processor for HTML generated by ASP.NET.&lt;/p&gt;
&lt;p&gt;Hotmod is exactly that.&lt;/p&gt;
&lt;h2&gt;Enter Hotmod&lt;/h2&gt;
&lt;p&gt;ASP.NET is very extensible, Hotmod contains an implementation of IHttpModule 
that hooks into the web request pipeline to provide some funky post-processing 
for your HTML output.
&lt;/p&gt;
&lt;p&gt;Hotmod will capture the HTML generated by your web form pages and MVC views,
parse the document into an XDocument and then apply any number of modifiers. 
The resulting HTML can be either &quot;pretty printed&quot; with nice indentation, or 
minified to remove all unnecessary whitespace.&lt;/p&gt;
&lt;p&gt;Your HTML will need to be parseable as XML for this work. So I hope you are 
closing your tags correctly and using quotes around attribute values!&lt;/p&gt;
&lt;p&gt;Hotmod defines a simple IModifier interface you can implement to add any 
application-wide modifications you want to make to the HTML. For example,
you could add a generation timestamp footer in a comment.&lt;/p&gt;
&lt;p&gt;The approach let&#39;s you be much more compositional than trying to nest 
multiple master pages.&lt;p&gt;
&lt;h2&gt;Get Hotmod&lt;/h2&gt;
&lt;p&gt;Hotmod is an open source project. Get the code from 
&lt;a href=&quot;http://github.com/andrewdavey/hotmod&quot;&gt;Hotmod on Github&lt;/a&gt;.&lt;/p&gt;
</content>
</entry>

<entry>
<title>Start background tasks from MVC actions using Autofac</title>
<link href="http://aboutcode.net/2010/11/01/start-background-tasks-from-mvc-actions-using-autofac.html"/>
<updated>2010-11-01T00:00:00-07:00</updated>
<id>http://aboutcode.net/2010/11/01/start-background-tasks-from-mvc-actions-using-autofac</id>
<content type="html">&lt;p&gt;This post is for people who know about ASP.NET MVC and IoC containers.&lt;/p&gt;
&lt;h2&gt;Preamble&lt;/h2&gt;
&lt;p&gt;Your MVC actions should be quick to return a response to the user. Any long
running task should be run on a background thread. This reduces the chance of 
your web server becoming unresponsive.&lt;/p&gt;
&lt;p&gt;I&#39;m using &lt;a href=&quot;http://code.google.com/p/autofac&quot;&gt;Autofac&lt;/a&gt; as my IoC container in ASP.NET MVC projects. In addition to an application wide, global 
container, Autofac provides a &quot;http request scoped&quot; container for each web 
request. This means we can declare dependencies such as database connections 
to be &quot;HTTP Request Scoped&quot;. Each request gets its own instance. At the end of 
the request, Autofac knows to dispose of any disposable objects.&lt;/p&gt;
&lt;p&gt;This works very well, until you don&#39;t have an HTTP request to work within. 
Which is what happens when running some code on a background thread.&lt;/p&gt;
&lt;p&gt;So we need a way to start our background task from a controller action
method, but give it a &lt;em&gt;new&lt;/em&gt; request-style context. It will not have an
actual HTTP context. We&#39;ll pass any required information to the task when 
starting it.&lt;/p&gt;
&lt;h2&gt;Code time&lt;/h2&gt;
&lt;p&gt;To allow controller actions to start background tasks, I will pass an 
instance of the following interface into the controller via the constructor.&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;
public interface IAsyncRunner
{
    void Run&amp;lt;T&amp;gt;(Action&amp;lt;T&amp;gt; action);
}
&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;Remember, I&#39;m using Autofac to create my controllers. So the constructor 
parameters are resolved from the container. An example controller looks like
this:&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;
public class HomeController : Controller {
    public HomeController(IAsyncRunner async) {
        this.async = async;
    }
    readonly IAsyncRunner async;
}
&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;For this example, imagine we want to do heavy image processing in response 
to a file being uploaded. Our action method will be:&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;
public ActionResult UploadImage(HttpPostedFileBase image) {
    image.SaveAs(&quot;example.jpg&quot;);
    async.Run&amp;lt;ImageResizer&amp;gt;(resizer =&gt; resizer.Resize(&quot;example.jpg&quot;));
    return RedirectToAction(&quot;UploadFinished&quot;);
}
&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;That&#39;s a nice short method, but let&#39;s analyse the details.&lt;/p&gt;
&lt;p&gt;First, we synchronously write the raw image data to disk. Then we call then 
async runner&#39;s Run method. We provide the type of the object to be invoked and 
a delegate to run. The async runner will start a new 
background task, create an ImageResizer object and call the given delegate.&lt;/p&gt;
&lt;p&gt;In the meantime the action method is free to return a response to the 
user.&lt;/p&gt;
&lt;h2&gt;The AsyncRunner&lt;/h2&gt;
&lt;p&gt;Let&#39;s move onto to the actual AsyncRunner implementation. I&#39;m using Autofac,
but the code could be adapted for use with any IoC container.&lt;/p&gt;
&lt;code&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;
public class AsyncRunner : IAsyncRunner
{
    public void Run&amp;lt;T&amp;gt;(Action&amp;lt;T&amp;gt; action)
    {
        var app = GetApplicationContainer();
        Task.Factory.StartNew(delegate
        {
            // Create a nested container which will use the same dependency
            // registrations as set for HTTP request scopes.
            using (var container = app.BeginLifetimeScope(WebLifetime.Request))
            {
                var service = container.Resolve&amp;lt;T&amp;gt;();
                action(service);
            }
        });
    }

    IContainer GetApplicationContainer()
    {
        // Use Autofac&#39;s ASP.NET integration to get the application-wide
        // container that exists in the ApplicationInstance.
        // See the Autofac documentation for more about this.
        var accessor = ((IContainerProviderAccessor)HttpContext.Current.ApplicationInstance);
        return accessor.ContainerProvider.ApplicationContainer;
    }
}
&lt;/pre&gt;&lt;/code&gt;
&lt;p&gt;The AsyncRunner uses Autofac to create an instance of the requested type T.
This happens inside a new &quot;lifetime scope&quot;. By using Autofac to create the 
object, that object can also declare dependencies to be provided by the 
container.&lt;/p&gt;
&lt;p&gt;The .NET 4.0 Task Parallel Library is used to start a new task to run 
within, rather than worry about creating threads manually.&lt;/p&gt;
&lt;p&gt;The end result is a clean way to start asynchronous tasks, whilst still 
being able to use Autofac&#39;s excellent features.&lt;/p&gt;
</content>
</entry>


</feed>
