What I've Been Doing

Monday, May 6, 2013 by K. Scott Allen
6 comments

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…

AngularJS Abstractions: Modules

Wednesday, May 1, 2013 by K. Scott Allen
3 comments

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.

Angular Abstractions: The Application

Tuesday, April 30, 2013 by K. Scott Allen
0 comments

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

The Tablet Show #82

Monday, April 29, 2013 by K. Scott Allen
0 comments

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

Node.js as a Tool For Learning To Program

Monday, April 22, 2013 by K. Scott Allen
9 comments

If you want to teach someone the very basics of computer programming, then JavaScript might be a good place to start.

- The syntax is flexible and uses only a handful of keywords, plus functions and objects.

- The language includes standard control flow structures (if/else, while, do, switch, throw).

- A beginning programmer would also have an easier time understanding a number of other popular languages, including Java, C#, and C++.

- JavaScript runtimes are ubiquitous.

- Knowing how to program in JavaScript is marketable skill.

Once you've settled on JavaScript as a starting language, then the next question is what tools and environment to use. Node.js might be a good place to start.

 

nodejs

- Node is free and easy to install on all the popular desktop operating systems.

- As a pure JavaScript execution engine, you can start by explaining Javascript without explaining HTML DOM APIs.

- Node has a REPL for interactive programming

- Node has a large universe of packages to build anything from a web server to desktop applications.

- Node projects follow simple file system conventions.

- You can still pick any editor or IDE to work with the JavaScript language. 

Using node and JavaScript to learn programming fundamentals is something I'm putting together for a future Pluralsight video, and it's working quite well.

Using GridFS in MongoDb from C#

Tuesday, April 16, 2013 by K. Scott Allen
2 comments

GridFS is a specification for storing large files in MongoDB. GridFS will chunk a file into documents, and the official C# driver supports GridFS.

The following class wraps some of the driver classes (MongoDatabase and MongoGridFS):

public class MongoGridFs
{
    private readonly MongoDatabase _db;
    private readonly MongoGridFS _gridFs;

    public MongoGridFs(MongoDatabase db)
    {
        _db = db;
        _gridFs = _db.GridFS;
    }

    public ObjectId AddFile(Stream fileStream, string fileName)
    {
        var fileInfo = _gridFs.Upload(fileStream, fileName);
        return (ObjectId)fileInfo.Id;
    }

    public Stream GetFile(ObjectId id)
    {
        var file = _gridFs.FindOneById(id);
        return file.OpenRead();           
    }
}

The following code uses the above class to put a file into MongoDB, then read it back out.

var fileName = "clip_image071.jpg";

var client = new MongoClient();
var server = client.GetServer();
var database = server.GetDatabase("testdb");
var gridFs = new MongoGridFs(database);

var id = ObjectId.Empty;            
using(var file = File.OpenRead(fileName))
{
    id = gridFs.AddFile(file, fileName);
}

using(var file = gridFs.GetFile(id))
{
    var buffer = new byte[file.Length];
    // note - you'll probably want to read in
    // small blocks or stream to avoid 
    // allocating large byte arrays like this
    file.Read(buffer, 0, (int)file.Length);
}           

Thoughts On Going Mobile With An Existing Web Site

Monday, April 15, 2013 by K. Scott Allen
2 comments

Assuming I already have an existing web site or web application deployed, running, and working great for desktop browsers, my decision tree for getting the site working on mobile devices looks something like the following. mobile thoughts

The right-hand side, the "mobile friendly" approach, is primarily concerned with adding responsive design touches to an existing site. Frameworks like Bootstrap and Skeleton can make this easier, if they can be worked into the existing design. The right-hand side seems to work best with content heavy web sites (news, blogs, articles, and dashboards) with little interactivity from the user.  

The left-hand side uses frameworks like jQuery Mobile to create the illusion of a native app. These frameworks generally require some major structural changes to the presentation layer and thus often work better as a separate site and source control project (m.server.com for mobile devices, server.com for the desktop, for example). A clean separation allows for a complete focus on the mobile experience, but  there is still the possibility of reusing assets, media, and backend services previously built for the desktop version.

The middle box is a hybrid approach using a framework like ASP.NET MVC that allows for view selection at runtime (Index.cshtml and Index.mobile.cshtml). Although this approach makes it easy to reuse quite a bit of code (even into the UI layer of the server), and often takes less time, it sometimes sacrifices the optimizations that can be made when working from a clean slate and doesn't evolve as easily when adding new features. This approach might use just a CSS framework, or might use a framework like jQuery Mobile, while still keeping the ability to make structural changes like an entirely new site.

Like everything else in software, the decisions are all about tradeoffs and where the software has to go in the future.

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