• Shortcuts : 'n' next unread feed - 'p' previous unread feed • Styles : 1 2

» Publishers, Monetize your RSS feeds with FeedShow:  More infos  (Show/Hide Ads)


Date: Tuesday, 18 Jun 2013 09:12

Imagine you need to support multiple projects that retrieve “widgets” of different types from various data sources. You might start with some simple type definitions that build a core API around widgets and widget storage.

public class Widget
{
    public int Key { get; set; }        
}

public interface IWidgetStore
{
    Widget GetWidget(int key);
}

The IWidgetStore interface is needed so that reusable algorithms can work with widgets.

Given these definitions, someone can build a widget specific for their project.

public class NamedWidget  : Widget
{        
    public string Name { get; set; }
}

As well as a concrete class for storing widgets.

public class WidgetStore : IWidgetStore
{
    public Widget GetWidget(int key)
    {          
        return _store.Single(u => u.Key == key);
    }
    
    readonly List<NamedWidget> _store = new List<NamedWidget>();
}

But the friction in development will start because specific projects don’t want to work with Widget, they want to work with NamedWidget where business properties like Name are defined. If every IWidgetStore can only return Widget, every caller has to cast the return value of GetWidget to a type like NamedWidget.

var widget = (NamedWidget)store.GetWidget(id);
var name = widget.Name;

One solution is to use an explicit interface definition to hide the IWidgetStore from application developers.

public class WidgetStore : IWidgetStore
{
    public NamedWidget GetWidget(int key)
    {            
        return _store.Single(u => u.Key == key);
    }

    Widget IWidgetStore.GetWidget(int key)
    {
        return GetWidget(key);
    }

    readonly List<NamedWidget> _store = new List<NamedWidget>();
}

Now the application code can work with NamedWidget and still pass the WidgetStore to other low level algorithms which will access the object through the IWidgetStore interface.

But, if the application is trying to stay flexible or testable it might want to continue working with widget stores through the IWidgetStore interface too, just like the reusable algorithms, and then the code would still need to cast the return value of GetWidget.

Another solution is to use a generic type parameter to parameterize a widget store with the desired type of widget.

public interface IWidgetStore<TWidget>
{
    TWidget GetWidget(int key);
}

Now a concrete widget store can implement the interface and return derived Widget objects.

public class WidgetStore<TWidget> : 
    IWidgetStore<TWidget>
    where TWidget: Widget
{
    public TWidget GetWidget(int key)
    {
        return _store.Single(u => u.Key == key);
    }

    readonly List<TWidget> _store = new List<TWidget>();
}

What makes it all work is the generic constraint where TWidget: Widget. The C# complier assumes a TWidget is of type Object unless told otherwise, so the LINQ query in GetWidget will fail with a compiler error because Object doesn’t have a Key property.

The generic constraint tells the C# compiler that a TWidget has to be a Widget, and since a Widget has to have a Key property the C# compiler is happy to compile the code.

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Monday, 17 Jun 2013 09:12

The angular-mocks library we’ve been using in the previous posts make unit tests easier to write and includes some built-in mocks for Angular services like $browser, $log, and $httpBackend. However, mocks aren’t available for every service, and there are certainly other services you’ll want to fake to isolate code in a unit test.

For example, AngularStrap offers directives and services for integrating AngularJS with Bootstrap. One of the services is the $modal service that allows you to programmatically launch a modal dialog from inside a view model. Here is a controller that launches the dialog as soon as the controller itself is created.

(function (module) {
    "use strict";

    var severSelectDialog;
    var initServerSelectDialog = function ($modal, $scope) {
        return $modal(
            {
                template: '_serverSelect.html',
                persist: true, show: false, scope: $scope
            });
    };

    var showSelectServerDialog = function () {
        severSelectDialog.then(function (modal) { modal.modal("show"); });
    };

    var MainController = function ($scope, $modal) {
        severSelectDialog = initServerSelectDialog($modal, $scope);
        showSelectServerDialog();
        
        // ...
    };
    MainController.$inject = ["$scope", "$modal"];

    module.controller("MainController", MainController);

}(angular.module("mongoMagno")));

Using $modal to open a dialog is a two step process. First you call $modal and get a promise, then you call “show” on the modal object resolved by the promise (the promise exists because the markup template  for the modal might be asynchronously loaded from the server).

Using Jasmine, if you wanted to unit test the controller to ensure the controller interacts with the $modal appropriately, you could use a spy with some fakes like so:

describe('MainController', function() {

    var fakeModal = {
        command: null,
        modal: function(command) {
            this.command = command;
        }
    };

    var fakeModalPromise = {
        then: function(callback) {
            callback(fakeModal);
        }
    };

    var $modal, scope;
    beforeEach(angular.mock.inject(function($rootScope, $controller) {
        fakeModal.command = null;
        $modal = jasmine.createSpy("$modal").andReturn(fakeModalPromise);
        scope = $rootScope.$new();
        $controller('MainController', {
            $scope: scope,
            $modal: $modal
        });
    }));

    it("should show server connect dialog when launched", function() {
        expect(fakeModal.command).toBe("show");
    });
});

Another approach is not to use a fake promise but a real promise created by the Angular $q service.

describe('MainController', function() {

    var FakeModal = function() {

        this.modal = function(command) {
            this.command = command;
        };
    };

    var scope, fakeModal;
    beforeEach(angular.mock.inject(function($rootScope, $controller, $q) {
        var deferred = $q.defer();
        fakeModal = new FakeModal();
        deferred.resolve(fakeModal);

        $modal = jasmine.createSpy("$modal").andReturn(deferred.promise);
        scope = $rootScope.$new();
        $scope.$apply(function() {
            $controller('MainController', {
                $scope: scope,
                $modal: $modal
            });
        });
    }));

    it("should show connect dialog when launched", function() {
        expect(fakeModal.command).toBe("show");
    });
});

This approach requires a call to $scope.$apply (a real promise from the $q service doesn’t fully resolve until an $apply cycle executes).

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Tuesday, 11 Jun 2013 09:12

In the last post we tested a simple controller, so now let’s look at a controller that likes to communicate over the network.

(function (module) {

    var MoviesController = function ($scope, $http) {

        $http.get("/api/movies")
            .then(function (result) {
                $scope.movies = result.data;
            });
    };

    module.controller("MoviesController",
        ["$scope", "$http", MoviesController]);

}(angular.module("myApp")));

If you want a unit test to execute without network communication there are a couple options. You could refactor the controller to use a custom service to fetch movies instead of using $http directly. Then in a unit test it would be easy to provide a fake service that returns pre-canned responses.

Another option is to use angular-mocks. Angular mocks includes a programmable fake $httpBackend that replaces the real $httpBackend service. It is important to note that $httpBackend is not the same as the $http service. The $http service uses $httpBackend to send HTTP messages. In a unit test, we’ll use the real $http service, but a fake $httpBackend programmed to respond in a specific way.

Here is one approach:

describe("myApp", function () {

    beforeEach(module('myApp'));

    describe("MoviesController", function () {

        var scope, httpBackend;
        beforeEach(inject(function ($rootScope, $controller, $httpBackend, $http) {
            scope = $rootScope.$new();
            httpBackend = $httpBackend;
            httpBackend.when("GET", "/api/movies").respond([{}, {}, {}]);
            $controller('MoviesController', {
                $scope: scope,
                $http: $http
            });
        }));

        it("should have 3 movies", function () {
            httpBackend.flush();
            expect(scope.movies.length).toBe(3);
        });
    });
});

In the above test, $httpBackend is programmed (with the when method) to respond to a GET request with three objects (empty objects, since the controller in this example never uses the data, but only assigns the response to the model).

For the data to arrive in the model, the test needs to call the flush method. Flush will respond to all requests with the programmed responses. The flush method will also verify there are no outstanding expectations. Writing tests with expectations is a little bit different.

describe("myApp", function () {

    beforeEach(module('myApp'));

    describe("MoviesController", function () {

        var scope, httpBackend, http, controller;
        beforeEach(inject(function ($rootScope, $controller, $httpBackend, $http) {
            scope = $rootScope.$new();
            httpBackend = $httpBackend;
            http = $http;
            controller = $controller;
            httpBackend.when("GET", "/api/movies").respond([{}, {}, {}]);
        }));
      
        it('should GET movies', function () {
            httpBackend.expectGET('/api/movies');
            controller('MoviesController', {
                $scope: scope,
                $http: http
            });
            httpBackend.flush();
        });
    });
});

The expectation in the above code is registered with the expectGET method. When the test calls flush, flush will fail the test if the controller did not make all of the expect calls. Of the two tests in this post, I prefer the first style. Testing with expectations is the same as interaction testing with mocks, which I’ve learned to shy away from because interaction testing tends to be brittle.

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Monday, 10 Jun 2013 09:12

One of the benefits of using AngularJS is the ability to unit test the JavaScript code in a complex application. Unit testing is incredibly easy for trivial cases when controllers and models are declared in global scope. However unit testing is slightly more challenging for objects defined inside of Angular modules because of the need to bootstrap modules, work with a dependency injector, and deal with the subtleties of nested functional code. 

Let’s try to test the following controller defined in a module:

(function (app) {
    
    var SimpleController = function ($scope) {
     
        $scope.x = 3;
        $scope.y = 4;
        $scope.doubleIt = function () {
            $scope.x *= 2;
            $scope.y *= 2;
        };
    };
    
    app.controller("SimpleController", 
             ["$scope", SimpleController]);
    
}(angular.module("myApp")));

We’ll be using AngularJS mocks and Jasmine in an HTML page, which requires the following scripts:

- jasmine.js

- jasmine-html.js

- angular.js

- angular-mocks.js

- simpleController.js (where the controller lives)

It’s important to include the Jasmine scripts before including angular-mocks, as angular-mocks will enable some additional features when Jasmine is present (notably the helper methods module and inject).

describe("myApp", function() {

    beforeEach(module('myApp'));

    describe("SimpleController", function() {

        var scope;
        beforeEach(inject(function($rootScope, $controller) {
            scope = $rootScope.$new();
            $controller("SimpleController", {
                $scope: scope
            });
        }));

        it("should double the numbers", function() {
            scope.doubleIt();
            expect(scope.x).toBe(6);
        });
    });
});

The module method used in the first beforeEach (which you can also invoke as angular.mocks.module) will initialize and configure the myApp module and its dependencies.

The inject method in the second beforeEach (angular.mocks.inject) takes a function that requires dependencies. Behind the scenes, the inject method will set up an $injector and use it to invoke the function with the right dependencies. In this test, we need the application’s $rootScope object and the $controller service. We are going to use the $controller service to have complete oversight over the instantiation of the SimpleController and keep a scope object around that we can write asserts against.

Once the setup code is done, the it tests are relatively easy to write (and read). The trick is figuring out what to inject, what to instantiate directly, and (a topic for future posts) what to mock or fake by hand.

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Friday, 07 Jun 2013 09:12

Most applications feature menu items that will need to appear selected at the appropriate time.

How to do this with Angular?

There are many different approaches, but ideally we’ll do this with a directive, since directives are responsible for DOM manipulation, and “selecting” a menu item will require some manipulation of the classes on an element. The goal would be to make it as easy as possible from a view:

<nav>
    <ul data-active-menu="selected">
        <li><a href="#/details?q=foo">Details</a></li>
        <li><a href="#/test">Summary</a></li>
        ...
    </ul>
</nav>

In the above code, the data-active-menu attribute should allow a custom directive to jump in and manipulate the styles of the elements inside by adding “selected” as a class to the active link, and removing the class from all other links.

The directive code itself would look like this:

(function () {
    
    var makeWatcher = function(location) {
        return function() {
            return location.url();
        };
    };

    var makeLinkUpdater = function(links, className) {
        return function (value) {
            angular.forEach(links, function(link) {
                link = angular.element(link);
                if (/\#(\/[^\/]+)/.exec(link.attr("href"))[1] == value) {
                    link.addClass(className);
                } else {
                    link.removeClass(className);
                }
            });
        };
    };

    var activeMenu = function($location) {

        var link = function(scope, element, attrs) {
            var links = element.find("a");
            var className = attrs.activeMenu;
            scope.$watch(makeWatcher($location),
                         makeLinkUpdater(links, className));
        };

        return {
            link:link
        };
    };
    activeMenu.$injector = ["$location"];
    
    angular.module("testApp")
           .directive("activeMenu", activeMenu);
}());

By taking a dependency on the $location service in AngularJS, the directive can both watch for when the location changes, and compare the current location to the href in the menu items. Matching hrefs get the class specified in the data-menu-active attribute. Easy, reusable, and keeps more boilerplate code out of the controllers.

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Thursday, 06 Jun 2013 09:12

The last post demonstrated a service to wrap geolocation APIs in the browser.

At some point the application might need to add some logging before and after the geolocation calls. One way to do this is to add code to the geo service directly, but AngularJS also allows us to register decorators for any service (including the built-in Angular services).

Decorator is a wonderful pattern for extensibility since the original object doesn’t need to anything about the decoration, and neither does the consumer of the service.

Here is a quick example of creating a decorator for the geo service. The decorator will log the amount of time taken for the geo service to return a result. When creating a decorator, AngularJS will pass the original service as the $delegate parameter.

(function() {
        
    var geoDecorator = function($delegate) {
        var locate = function() {
            var start = new Date();
            var result = $delegate.locate();
            result.always(function () {
                console.log("Geo location took: " + (new Date() - start) + "ms");
            });
            return result;
        };

        return {
          locate: locate  
        };
    };

    var testApp = angular.module("testApp");
    testApp.config(["$provide", function ($provide) {
        $provide.decorator("geo", geoDecorator);
    }]);
    
}());
Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Wednesday, 05 Jun 2013 09:12

At first glance, services in AngularJS are a catch-all destination for any code that doesn’t fall into one of the other primary abstractions in the framework. If it’s not a controller, filter, directive, or model,  it must be a service. One reason to think to think this way is because one can interpret the word “service” to mean anything in software. However, services in Angular have capabilities and behaviors that make them well suited for specific jobs.

Services As Application Helpers

Controllers, applications, and even other services can take a dependency on 0 or more services, meaning services can be a convenient location for code that is used in different places throughout an application. For example, if two controllers both require some algorithmic logic to make a decision, it would be better to place the logic inside a service that both controllers can use than have the code duplicated in two different controllers.

Services As Singletons

AngularJS will manage services to make sure there is only one instance of a service per application. This makes services a convenient storage location for data that needs to stick around (controllers and their models can come and go as views are loaded and unloaded in the DOM).

Services As Communication Hubs

AngularJS provides a framework to achieve a separation of concerns and a the various components have no knowledge of each other. Since services can be injected into almost anything (controllers, directives, filters, and even other services), a service can play the role of a mediator or event aggregator for other components to communicate in a loosely coupled manner.

Services As Injectable Dependencies

Perhaps the biggest reason to put code into a service is because services are injected into other components, meaning components maintain a loose coupling and any particular service can be replaced during a unit test. AngularJS itself provides many services that fall into this category. There is the $http service (for network communication),  the $window service (a wrapper for the global window object), the $log service, and others.

What Isn’t A Service?

There is plenty of vanilla JavaScript code you can write for an AngularJS application that doesn’t have to live inside an AngularJS abstraction. Model and view model definitions, for example, could live outside of any controller or service. Controllers could instantiate models, obviously, and services could hold references and vice versa. My candidates for services generally fall into one of the previous 4 categories, and as models are easy to test without test doubles, they don’t need to be injected and hence don’t need to be considered a service themselves, although it is certainly reasonable to make a service responsible for fetching a model from some unknown data source.

How To Create A Service?

One of the confusing areas of AngularJS revolves around the APIs for  creating a service, since there are no fewer than 6 ways to register a service and the obvious API choice, a method named service, probably shouldn’t be your first choice. The one that can adapt to just about any scenario is the factory method, which when used on a module object looks like something that would define a factory function for the module, but in fact is defining a factory function for a service (another unfortunate point of confusion).

As an example, here is a service to wrap the geolocation APIs of  the browser:

(function () {

    var geo = function ($q, $rootScope) {

        var apply = function () {
            $rootScope.$apply();
        };

        var locate = function () {
            var defer = $q.defer(); 
            navigator.geolocation.getCurrentPosition(
                function (position) {
                    defer.resolve(position);
                    apply();
                },
                function(error) {
                    defer.reject(error);
                    apply();
                });
            return defer.promise;
        };

        return {
            locate: locate
        };
    };

    geo.$inject = ["$q", "$rootScope"];

    angular.module("testApp")
           .factory("geo", geo);

}());

The factory method takes a function that AngularJS will invoke to create the service instance. This geo service makes use of the $q service provided by Angular to create promises for the asynchronous delivery of latitude and longitude. Somewhere else in the app, a controller can take a dependency on the geo service and use it to find the user’s position.

(function () {

    var TestController = function ($scope, geo) {

        geo.locate()
           .then(function (position) {
                $scope.position = position;
            });
    };

    TestController.$inject = ["$scope", "geo"];

    angular.module("testApp")
           .controller("TestController", TestController);

}());

Summary

Services are an important part of any AngularJS application. The built-in services in the framework make code more testable, and custom services can provide an abstraction to make code easier to maintain.

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Tuesday, 28 May 2013 09:12

Directives are one of the lynchpins that make AngularJS work, and also make the framework nice to work with.

Directives are the attributes Angular searches for in the markup when the DOM is loaded, attributes like ng-app, ng-controller, and ng-click. You can also use directives to create custom elements, like <my-widget>, but doing so depends on how much value you place in having your raw source validated by an HTML validator.

If validation is high on your list, there are HTML 5 compliant approaches to using directives, including data- prefixing attribute directives (use data-ng-controller instead of ng-controller, for example, and Angular still works).

What Are They Really?

From an abstraction perspective, directives form an anti-corruption layer between a model and a view. Directives are where you can listen for changes in a model value and then go manipulate the DOM. Directives allow models to change the content and presentation of a view without the model getting bogged down by the DOM manipulation code. The model stays clean, testable, and plain.

Here’s an example of a custom “myShow” directive(note that AngularJS already has an ngShow directive to do this job, but this is an easy example to understand).

The purpose of the myShow attribute is to show or hide a DOM element based on the truthiness of a model value.

First, the markup:

<div data-ng-controller="TestController">
    
    <div data-my-show="model.visible">
        {{model.message}}
    </div>
            
    <button data-ng-click="model.toggleVisible()">Click me!</button>

</div>

Notice the data-my-show attribute on the first inner div. The attribute value is set to “model.visible”.

Here is the controller and model for the scenario:

(function () {

    var model = {
        visible: false,
        message: "Surprise!",
        toggleVisible: function () {
            this.visible = !this.visible;
        }
    };

    var TestController = function ($scope) {
        $scope.model = model;
    };

    TestController.$inject = ["$scope"];

    angular.module("testApp")
           .controller("TestController", TestController);

}());

All that’s needed now is the code for the my-show directive:

(function () {

    var myShow = function() {
        return {
            restrict: "A",
            link: function(scope, element, attrs) {
                scope.$watch(attrs.myShow, function(value) {
                    element.css("display", value ? "" : "none");
                });
            }
        };
    };

    angular.module("testApp")
           .directive("myShow", myShow);
}());

The naming conventions applied by AngularJS allow the directive registered as “myShow” to be applied in markup as data-my-show, as well as my-show and a few other variations. 

The directive itself is setup by a function that returns a “directive definition object” (let’s call it the DDO). The DDO has to have a few members in place for the directive to work, but this sample only uses a couple members: restrict and link.

The restrict property specifies where the directive is valid (E for element, A for attribute, C for class, M for comment). Since the default for restrict is “A”, this property could be omitted.

The link function is responsible for making things happen by setting up watches to listen for changes in the model.  Angular invokes the link function and gives it the model (scope), the element (effectively a jQuery wrapped reference to the DOM element), and an attrs parameter containing the attributes of the element. Asking for attrs.myShow will return “model.visible”, since that is the attribute value specified in the markup.

The link function in this example uses scope.$watch to listen for changes in the specified model value. $watch is a good topic for a future post, but for now we can say if the model changes it’s visible property from false to true, the framework invokes the listener function passed as the second parameter to $watch.

The listener function in this sample sets the display property of the element to an empty string or “none” to toggle visibility of the element. The value parameter in the function is the recently changed model value, the value the directive set up to $watch.

Where Are We?

This sample doesn’t show the full capabilities of a directive, which can also load additional markup from a string or a URL, as well as other nifty features.  We’ll cycle back to more advanced features in a future post.

Although custom directives can require  more code in a project compared to using DOM manipulation inside a controller, the advantage of having a directive in place is in keeping the models and controllers simple. Plus, once written, most directives can be parameterized and reused in different places and multiple applications.

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Monday, 27 May 2013 09:12

I introduced a latent bug in some code recently while trying to find documents with a specific set of values embedded inside an array. For example, consider the following documents:

{
    "name" : "Thing1",
    "children" : [  
        { "name" : "C1", "value" : "A" },
        { "name" : "C2", "value" : "B" },
        { "name" : "C3", "value" : "C" }]
}, {
    "name" : "Thing2",
    "children" : [
        { "name" : "C3", "value" : "A" },
        { "name" : "C4", "value" : "B" },
        { "name" : "C5", "value" : "C" }]
}, {
    "name": "Thing3",
    "children": [
        { "name": "C5", "value": "A" },
        { "name": "C6", "value": "B" },
        { "name": "C7", "value": "C" }]
}

Let’s say we only want documents with a child entry that has a name of C3 AND a value of C (only Thing1 should match this criteria because of the last child in its array). It’s tempting to write a query with an AND clause and feel good about the C# code.

var query = things.Find(
    Query.And(
        Query.EQ("children.name", "C3"),
        Query.EQ("children.value", "C")
    ));

But MongoDB, being document oriented, interprets the query as “give me all the documents that have any child with a name of C3, and any child with a value of C. In other words, the name and value combination don’t need to match inside the same array element. A quick test from the shell can verify the behavior.

> db.things.find({"children.name":"C3", "children.value":"C"},{name:1, _id:0})
{ "Name" : "Thing1" }
{ "Name" : "Thing2" }

The $elemMatch query operator tells Mongo to only match documents when at least one element in the array satisfies the entire criteria.

var query = things.Find(
    Query.ElemMatch("children",
        Query.And(
            Query.EQ("name", "C3"), 
            Query.EQ("value", "C")
        )
     ));

The shell will verify that we only get the Thing1 we want:

> db.things.find({ children: { $elemMatch : { name:"C3", value:"C"}}}, {name:1, _id:0})
{ "Name" : "Thing1" }

Not an easy bug to catch in a test without a robust set of test data.

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Monday, 20 May 2013 09:12

Filters in AngularJS can form a pipeline to format and adapt model data inside a view. The built-in filters for AngularJS are date (format a date), filter (select a subset of an array), currency (format a number using a currency symbol for the current locale), and many more. I say filters can form a pipeline because you place them inside expressions in a view using a pipe symbol. The canonical example of a filter is the filter filter, which in the following markup filters a list of items according to what the user types in the search input (try it live here).

<input type="search" placeholder="Filter" ng-model="searchTerm"/>    

<ul ng-repeat="item in items | filter:searchTerm | limitTo:maxItems">
    <li>{{item}}</li>
</ul>

Notice the output of filter is also piped to a limitTo filter, which restricts the number of items in the list to maxItems (where maxItems would need to be defined in the model).

Custom Filters

Custom filters only require a filter function to be registered with Angular. The filter function returns a function that will perform the actual work. For example, a plurify filter to add the letter s to the output:

(function() {

    var plurify = function() {
        return function(value) {
            return value + "s";
        };
    };

    angular.module("patientApp.Filters")
           .filter("plurify", plurify);
}());

Now plurify is available to use in a view:

<ul ng-repeat="item in items | filter:searchTerm | limitTo:maxItems">
    <li>{{item | plurify }}</li>
</ul>

A filter can also take one or more optional parameters.

var plurify = function() {
    return function(value, strength) {          
       strength = strength || 1;
       return value + Array(strength + 1).join("s");
    };
};

Now we can add 5 s characters to the output:

<li>{{item | plurify:5 }}</li>

The beauty of filters is how you can package up small pieces of testable code to make the job of the model and view a bit easier, and the syntax to use a filter is easy and intuitive.

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Friday, 17 May 2013 09:12

The official MongoDB docs recommend that you avoid storing scripts on the server, but there are scenarios where having reusable functions available on the server can be useful. Inside a MapReduce operation, for example.

We’ll start with some JavaScript code encapsulating statistical calculations, and place the code in a file named mathStats.js:

function() {

    var stdDev = function(numbers) {
        // ...  
    };

    var mode = function(numbers) {
        // ...
    };

    var mean = function(numbers) {
        // ...
    };

    return {
        stdDev: stdDev,
        mode: mode,
        mean: mean
    };

};

Note the script must be a function. To use the methods inside, the function must live in the system.js collection. The following C# code can do this:

var sysJs = db.GetCollection("system.js");
var code = File.ReadAllText("pathTo\\mathStats.js");
var codeDocument = new BsonDocument("value", new BsonJavaScript(code));
codeDocument.Add(new BsonElement("_id", "mathStats"));
sysJs.Insert(codeDocument);

It is important to insert the script as the  value attribute of a document, and set the _id of the document to a friendly string name and not an ObjectID value. Failing to follow those two steps can lead to errors like “exception: name has to be a string” and “value has to be set” when you execute commands.

Once the script is loaded, you can use the function from any map, reduce, or finalize function by invoking the function with its friendly _id name. For example:

function(key, value){                      
    var stats = mathStats();
    value.stdDev = stats.stdDev(value.items);               
    return value;
}
Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Thursday, 16 May 2013 09:12

Continuing from the controllers post, the parameter to the controller function is named $scope.

var AboutController = function($scope) {

    // ...    

};

The name $scope is important since it allows the AngularJS dependency injector to know what type of object you are asking for, in this case an object that will contain the view model. Any plain old JavaScript you attach to $scope (properties, functions, objects, arrays) is eligible to use from the expressions inside the view.

In the last post our model was relatively “flat” in the sense that properties and functions were added directly to $scope:

$scope.rabbitCount = 2;

$scope.increase = function() {
    $scope.rabbitCount *= $scope.rabbitCount;
};

This allowed us to use rabbitCount and increase() in the markup that was inside the view scope (the div) of the AboutController:

<div data-ng-controller="AboutController">

    <div>Number of rabbits in the yard: {{rabbitCount}}</div>

    <button ng-click="increase()">More rabbits</button>
    
</div>

You can think of $scope as the execution context for the expressions in the view. Saying ng-click=”increase” results in a call to $scope.increase. The only thing tricky to understand about $scope is that having a controller inside a controller, or a controller inside an application (which you’ll always have), will result in nested $scopes, and a nested $scope will prototypally inherit from it’s parent scope by default. This is why $scope is injected by angularJS – the framework sets up the prototype chain before giving your controller the $scope object to use as a model.

Inheritance means a view has access to it’s own scope as well as any inherited scope. In the following example, the view inside the ChildController markup can use an expression like {{rabbitCount}}, and this expression will read the rabbitCount property of AboutController’s scope ($scope.rabbitCount will follow the prototype chain).

<div data-ng-controller="AboutController">    

    <div>Number of rabbits in the yard: {{rabbitCount}}</div>
    
    <div data-ng-controller="ChildController">
        Number of rabbits in the yard: {{rabbitCount}}
        Number of squirrels in the yard: {{squirrelCount}}
    </div>

</div>

The one place to be careful with the inherited scope is with 2 way data binding. The way JavaScript prototypes work is that writing to the rabbitCount property of the ChildController $scope will add a rabbitCount property to the ChildController $scope and effectively hide the parent property. $scope.rabbitCount no longer needs to follow the prototype chain to find a value. More details and pictures on this scenario in “The Nuances of Scope Prototypal Inheritance”.

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Wednesday, 15 May 2013 09:12

I watched the dotNetConf .NET Open Source Panel last week. It was a bit disappointing to hear defeatism in the voices of OSS project leaders, because .NET’s future appears to rely entirely on the success of open source software for .NET. Here are a couple reasons:

1. The success of Windows Azure. Azure is now an amazing cloud platform for developers and is getting better every few weeks. Azure is also a business success with annual revenue topping $1 billion. That’s $1 billion with only a 20% share of a $6 billion dollar market – a market that is expected to grow to $30 billion in 4 years. As Azure continues to pick up market share it is not completely unthinkable to see it post a 15+ billion dollar year in 2018, which is getting into the same double-digit-billion-dollar-revenue neighborhood as Windows itself.

The documentation page for Azure makes it clear where the growth will come from:

Azure Strategy 

To paraphrase the above graphic, Microsoft doesn’t need legions of developers building frameworks and tools for Windows developers when they can have legions of programmers building tools and a cloud platform for all developers. Hadoop, Redis, NodeJS, RoR, Django, PHP, and the list goes on. Even if it doesn’t run on Windows, you can always spin up a ready made Azure virtual machine image with Ubuntu, CentOS, or SUSE.

I don’t think Azure needs a successful server-side .NET framework to be a success itself.

2. The Direction of Windows 8.

I still feel Window 8 carpet bombed .NET developers. There was secrecy and hearsay followed by the death of one XAML platform and the arrival of yet another slightly different XAML platform. People running a business based on desktop technology don’t know where to place their bets and the Windows division has always appeared hostile to the CLR. I’m not sure what this year’s Build and Windows Blue will bring, but I can only hope it offers some direction for businesses who build desktop business applications with managed code.

I don’t think Windows wants to see a successful client-side .NET framework.

Where Are We?

It feels as if Microsoft has shifted focus away from .NET, and with the focus goes resources and innovation. Much of the CLR and it’s associated assemblies and languages appear to be entering maintenance or refinement mode instead of advancing in new directions. Anyone building software on Microsoft’s .NET platform should see this as cause for concern.

Except …

The circle of  software loosely surrounding .NET is exploding. There are more server side framework choices for C# developers than ever before, and client side web programming has advanced rapidly over the last few years with open source projects like AngularJS, Backbone, Ember, and Meteor. Document databases like MongoDB and RavenDB and key-value stores like Redis are all available to managed code, and products like Xamarin are pushing C# and mono to new platforms. What I’ve listed is a small sampling of what is happening and it is all pretty amazing when you sit back and look at the bigger picture. 

Plus, if you already build solutions with ASP.NET MVC, Web Pages, the WebAPI, or the Entity Framework, you are already building software on top of open source projects that rely on other open source projects from the community. 

What To Do?

If your business or company still relies solely on components delivered to developers through an MSDN subscription, then it is past time to start looking beyond what Microsoft offers for .NET development so you won’t be left behind in 5 years. Embrace and support open source.

At least, that’s how I see things.

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Monday, 13 May 2013 09:12

In MVC web programming server side controllers are responsible for reacting to an external stimulus (an HTTP request), and then building a model and possibly rendering a view in response to the stimulus. In a client app with AngularJS, the controller has an easier job.

AngularJS is officially a Model-View-Whatever framework, meaning there is quite a bit of flexibility in the architecture of an application. But, if you follow the typical conventions, a controller is simply a function the framework will call at the appropriate time. It’s the controller’s responsibility to put together a model by any means possible, and then the controller function is complete. 

One notable difference between a controller in server side world of Rails or ASP.NET MVC  and a controller with AngularJS is the view selection. Controllers and views are generally bound together on the client using directives (ng-controller) or in routing rules (a topic for a future post).

As an example, the following html is setting up the AboutController to manage the primary div element in the document. The primary div also contains some data binding expressions.

<body data-ng-app="patientApp">
                          
    <div data-ng-controller="AboutController">
        <h3>{{message}}</h3>
        <div>Number of rabbits in the yard: {{rabbitCount}}</div>

        <button ng-click="increase()">More rabbits</button>
        <button ng-click="decrease()">Less rabbits</button>
    </div>

    <script src="http://odetocode.com/libs/angular.js"></script>
    <script src="http://odetocode.com/scripts/myScript.js"></script>
</body>

When AngularJS takes control of the DOM it will see the ng-controller directive and go off searching for an AboutController. Here is one way to write the controller:

(function () {
    
    var AboutController = function($scope) {

        $scope.message = "Hello from the AboutController!";
        
        $scope.rabbitCount = 2;
        
        $scope.increase = function() {
            $scope.rabbitCount *= $scope.rabbitCount;
        };
        
        $scope.decrease = function() {
            $scope.rabbitCount -= 1;
        };
    };
    
    // Describe dependencies for the injector
    // in a minifier friendly way.
    AboutController.$inject = ["$scope"];

    // Register the controller as part of a module.
    // The patientApp module will need to take a 
    // dependency on patientApp.Controllers.
    angular.module("patientApp.Controllers")
           .controller("AboutController", AboutController);
    
}());

Once AngularJS finds the controller, the framework invokes the function and injects any dependencies the controller requires. In this case the controller is simple and only requires a $scope dependency. We’ll talk about $scope in a future post, for now you can think of $scope as the model object you need to enhance for the application to work. The HTML contains data binding expressions like {{message}} and ng-click directives that will send the framework looking for functions to invoke named increase and decrease. These are all attributes the controller needs to provide on the $scope object.

In many respects the $scope object feels like a view model in an MVVM environment like Silverlight. The data binding expressions push and pull data into properties of the view model. The command type bindings, like ng-click=increase(), invoke methods on the view model. And the view model (a.k.a $scope object) behaves in true view model like fashion in the sense that it knows nothing about the view or the DOM. The view model only needs to change values internally and data binding takes care of the rest. Clean and testable.

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Friday, 10 May 2013 09:12

From the Redis home page:

Redis is an advanced key-value store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets and sorted sets.

Redis is also fast. Incredibly fast. Mind-numbing fast.

For more information, try the Redis docs or “The Little Redis Book” by Karl  Seguin.

MSOpenTech just released a NuGet package of their Windows port to make it easy to download Redis and try the server from the command line. Combine this package with the ServiceStack.Redis package and it easy to be up and running quickly.

install-package redis-64
install-package servicestack.redis

The redis-64 package (for 64 bit systems) doesn’t add assembly references to a project, but does drop the Redis server executable in the packages\Redis-64.{version}\tools directory of the solution. Opening a command window and running redis-server.exe will launch the server with the default settings.

Here is a quick C# program to store and retrieve an object using the ServiceStack client:

static void Main(string[] args)
{
    var client = new RedisClient("localhost");
    var patientClient = client.As<Patient>();

    var patient = new Patient
        {
            Name = "Scott", 
            Codes = new List<string> {"1.1", "2.2"}
        };
    patient.Id = patientClient.GetNextSequence();
    patientClient.Store(patient);

    var retrievedPatient = patientClient.GetById(patient.Id);
    Console.WriteLine("{0}:{1}", retrievedPatient.Id, retrievedPatient.Name);

}

Once the program runs, you can also go to the command line client in the tools directory (redis-cli.exe), and verify the data stored inside of Redis. Here is a shot of the cli client and server running:

Redis running from NuGet

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Tuesday, 07 May 2013 09:12

imageNow that we know a bit about how modules work at an API level, we can look at questions that will be asked more than once in the lifetime of a project, like when to create a module, how many modules to create, and how to organize source code files for a module.

One thing to recognize early on is how much flexibility is available. Although the term "module" sounds like the JavaScript module design pattern (a single function inside a single file), there is nothing about an AngularJS module that requires all the code for a module to exist in a single file, or in a single function. Your code can use multiple JavaScript modules to add features to a single AngularJS module.

The code below is creating an alerter service to add to the patientApp.Services module, and could be one of many such pieces of code scattered across various files.

(function () {
    var alerter = function () {
        // ...
    };

    angular.module("patientApp.Services")           
           .factory("alerter", alerter);
}());

Given this amount of flexibility, there are no real limitations on the number of modules and files you create.

Use an approach that causes the least amount of friction for you and the team. Factors to evaluate include the test and deployment strategy and the reusability of a module across multiple apps. Managing the dependencies of a large number of modules produces friction. Building large monolithic modules can also produce friction. Somewhere in between is a sweet spot.

Reference Material

There is already some good material out there on organizing file and modules.

The Angular Seed project recommends creating one module for controllers, one for directives, one for filters, and one for services. I'm not a fan of choosing this approach as a default.

Brian Ford has a post on Building Huuuuuuge Apps with AngularJS. Brian suggestion: "Each file should have one "thing" in it, where a "thing" is a controller, directive, filter, or service".

Cliff Meyers also believes in one thing per file in his post "Code Organization in Large AngularJS and JavaScript applications". I like that Cliff uses a dedicated folder for models instead of throwing in models with services or controllers.

Finally, Jim Lavin has "AngularJS Modules for Great Justice" and talks about the concepts of "package by layer" versus "package by feature".

One scenario I haven't found addressed very well is the scenario where multiple apps exist in the same greater web application and require some shared code on the client. I'll try to blog about this one in the future, but we'll visit some of the other AngularJS abstractions first.

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Monday, 06 May 2013 09:12

People ask me what I do on a a regular basis. For this and various other reasons I'll shed some light on the current situation.

medisolv1.Medisolv is a company I've worked with in various roles for the last 10+ years. I'm now CTO, but still work with various product teams and commit production code as often as possible, which is by far finest part of the job. We will be hiring more software developers in the near future, so keep an eye out if you are interested. 

Battle Of Valcour With Pluralsight Crystal2. Pluralsight is where I make glorious training videos. I'm currently working on a couple different courses and plan to finish "Learning To Program" in the next couple weeks. Making videos for Pluralsight is fun. Over the years I've collected 8 crystal microphones from Pluralsight as an award for making a Top 10 course. Occasionally I arrange them on the floor to recreate great naval battles from the 18th century. The photo to the right is the Battle of Valcour Island. You can see General Carleton advancing British warships towards the American's Congress and Royal Savage.

3. OdeToCode LLC is the company I own and operate for consulting services, but I've scaled back operations to simplify life and I am currently not taking on new work.

4. Workshops, Classes, and Conferences allow me to occasionally get out and see the world. I enjoy the classes I teach for DeveloperFocus and ProgramUtvikling and plan to update and revise my current curriculum to include topics like AngularJS and web service design with WebAPI. Conferences are fun, but also stressful and time consuming, so I'm cutting back. I will be at DevSum, NDC, and the fall DevIntersection this year.

And now, back to work…

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Wednesday, 01 May 2013 09:12

Continuing from the last post, a module in AngularJS is a place where you can collect and organize components like controllers, services, directives, and filters. We'll talk about the "when & why" of creating a module in a later post. This post will focus on the API to create a module, and get a reference to an existing module. Stimulating topic, eh?

The proper way to create a module is to use the angular.module method passing at least the module name, and an array naming all the dependencies of the module  (or an empty array if there are no dependencies).

angular.module("patientApp.Services", []);
angular.module("patientApp.Controllers", []);   
angular.module("patientApp", ["patientApp.Services",
                              "patientApp.Controllers"]);

The above code actually creates three modules – patientApp.Services, patientApp.Controllers, and a patientApp module that depends on the previous two modules. I like to have all this code centralized in one place for easy management.

The following code defines the three modules, then comes back and adds a "run block" to the patientApp module (a run block is a piece of code that Angular will invoke once the module is assembled and configured).

(function () {
    "use strict";

    angular.module("patientApp.Services", []);
    angular.module("patientApp.Controllers", []);   
    angular.module("patientApp", ["patientApp.Services",
                                  "patientApp.Controllers"]);

    var app = angular.module("patientApp");
    app.run(["$rootScope", function ($rootScope) {
        $rootScope.patientAppVersion = "0.0.0.1";
    }]);
    
}());

Note the call to angular.module("patientApp") does not pass a second parameter with required module names, doing so would recreate the module and destroy anything already registered inside. Calling angular.module with just the module name will give you back a reference to an existing module so you can continue adding run blocks, services, directives, and other components into the module.

Somewhere else in the same file, or in a separate file, another block of JavaScript code might add an "alerter" service to the 'patientApp.Services' module (I know we haven't talked about services yet, but we will, and the short summary is that a service can carry out a specific task, like communicate over the network, and a service typically contains code you want isolated for testability or to obey the single responsibility principle).

(function () {
    var alerter = function () {
        return {
            alert: function (message) {
                // ... do something alerty
            }
        };
    };

    angular.module("patientApp.Services")           
           .factory("alerter", alerter);
}());

The API and terminology around services in Angular is unfortunately confusing and sometimes misleading, but we'll talk about that, too. For now, think of the factory method as "registering a service" in the module. The factory method is not providing a factory for the module itself, as the name might imply. 

Yet another hunk of script from a different file can add a logger service to the same module.

(function() {

    var logger = function() {
      
        var log = function(message) {
            // .. do something loggy
        };

        return {
            log: log,            
        };
    };

    angular.module("patientApp.Services")
           .factory("logger", logger);           

}());

Of course, that could have all been combined together, if you so desire:

(function() {
    "use strict";

    var alerter = function () {
        //...
    };

    var logger = function() {
        //...
    };

    angular.module("patientApp.Services")
           .factory("alerter", alerter)
           .factory("logger", logger);           

}());

Now that we understand a bit about how to create modules, we'll talk about the "when and why" in a future post.

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Tuesday, 30 Apr 2013 09:12

imageOne of the nice features of AngularJS is how the framework comes with a complete set of abstractions and features for building complex client pages from loosely structured and maintainable pieces of code. There are controllers, services, directives, data binding, and other pieces we'll continue looking at in future posts.

Angular also includes the concept of an application, which is the topic for this post.

An application is just an Angular module, which leads to a chicken and egg problem, since we haven't talked about modules, yet, but for now you can think of a module as an abstraction for packaging up related pieces of code.

For example, with Angular you can place all your controllers into a one module and all your services into a second module, or put the controllers and services all inside a single module. How many modules you define is entirely up to you and the needs of the project. Modules exist as containers that can provide configuration information, runtime dependencies, and other infrastructure support for their residents.

There are usually two features of the application module that make it "the application".

First is that the application module should know about all the other modules in the software, while those other modules might not know about each other or the application. Thus, the application module is the perfect place to bootstrap and glue together all the other components.

Secondly, the application module is the one identified by the ngApp directive. You can place this directive in the DOM using ng-app or data-ng-app attributes, as shown below in the simplest possible AnguarJS + HTML 5 page.

<!DOCTYPE html>
<html>
    <head>   
        <title>Patient Data</title>
    </head>
<body data-ng-app="PatientApp">
    <div>
        {{ patientAppVersion }}            
    </div>
    <script src="http://odetocode.com/libs/angular.js"></script>
    <script src="http://odetocode.com/… my scripts &hellip"></script>    
</body>
</html>

You can have multiple applications inside a single page, but typically there will only be a single application and the ng-app directive will appear on the document's body element. After Angular loads and processes the HTML in the DOM, it will go looking for the "patientApp" module, so the following code is required:

(function () {
    "use strict";

    var app = angular.module("PatientApp", []);

    app.run(function ($rootScope) {
        $rootScope.patientAppVersion = "0.0.0.1";
    });

}());

angular.module is the API to use for creating and configuring a module. The first parameter is the name of the module, the 2nd parameter describes the other modules this module depends on (there currently are none).

The .run method will give Angular a function to execute after all the modules are loaded and the dependencies are resolved. In this sample, we'll add a property to $rootScope, which is the scope in use in the previous HTML (since we have no controllers yet). The magic of {{ data binding }} allows the web page to display the text "0.0.0.1".

You can reference the patientApp module from other JavaScript files using angular.module. The following code block could live in a separate .js file, and demonstrates how different pieces of code could be tied together to execute during the application bootstrap phase:

(function() {
    "use strict";

    var app = angular.module("PatientApp");
  
    app.run(["$rootScope", function($rootScope) {
        $rootScope.patientAppGreeting = "Hello!";
    }]);  

}());

Note: the call to angular.module does not have a 2nd parameter (the list of dependencies) in this second block. The dependencies param should only appear once for a given module. Passing the dependencies parameter again will wipe out the module definition and start over.

Also note the second code block uses a style that is safe for minification because it passes $rootScope (a well known name to Angular) in an array along with the function to invoke during the run phase. Anytime you define a function where Angular will inject dependencies you are given the option of passing the function as the last element in an array that gives Angular the well known names of the dependencies required as arguments. We'll see more examples of this style as we move forward.

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Date: Monday, 29 Apr 2013 09:12

The one where I talk to Carl and Richard about everything from AngularJS, Durandal, and Glimpse to relationships and finding your true love.

Listen or download the show here.

 

Tablet Show #82

Author: "scott@OdeTocode.com"
Send by mail Print  Save  Delicious 
Next page
» You can also retrieve older items : Read
» © All content and copyrights belong to their respective authors.«
» © FeedShow - Online RSS Feeds Reader