AngularJS Abstractions: Filters

Monday, May 20, 2013 by K. Scott Allen
0 comments

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.

Using system.js in MongoDB (From C#)

Friday, May 17, 2013 by K. Scott Allen
0 comments

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;
}

AngularJS Abstractions: Scope

Thursday, May 16, 2013 by K. Scott Allen
0 comments

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”.

Where Is .NET Headed?

Wednesday, May 15, 2013 by K. Scott Allen
39 comments

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.

AngularJS Abstractions: Controllers

Monday, May 13, 2013 by K. Scott Allen
1 comment

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="libs/angular.js"></script>
    <script src="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.

Trying Out Redis via NuGet

Friday, May 10, 2013 by K. Scott Allen
1 comment

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

AngularJS Abstractions: Organizing Modules

Tuesday, May 7, 2013 by K. Scott Allen
3 comments

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.

Follow Me On Twitter
RSS Subscribe
Contact
Search Archives
by K. Scott Allen
K.Scott Allen