Is It Time To Switch To JavaScript?

Wednesday, April 23, 2014 by K. Scott Allen
5 comments

JavaScript LogoQuestion from the mailbox: "After many years as a server side developer and DBA, is it time to make a switch to JavaScript and focus on client side development?"

I think you need to work in an environment you enjoy. Some people do not enjoy client side development, and that's ok. There is still plenty of work to do on the server and in the services that run there.

The funny thing is, you don't have to leave the server to learn JavaScript. Take a look at technologies like NodeJS or MongoDB first. Having some JavaScript experience will be good, and I think there is no better way to learn a new language than to use the language inside a paradigm you already understand.

Once you know more about JavaScript the language you should take some time to explore the HTML development landscape and try working with some of the tools and frameworks, even if you have to use some of your spare time.

Maybe you’ll find you like the new world, only then it would be time for a switch, because in the end you gotta do what you enjoy...

Better Error Handling In AngularJS

Monday, April 21, 2014 by K. Scott Allen
0 comments

In my recent work I’ve been using two approaches to handling errors and exceptions. The ultimate goal is to not let an error go unnoticed.

$exceptionHandler

First up is a decorator for the $exceptionHandler service. We’ve looked at other decorators in a previous post. This specific decorator will send all errors to $rootScope for data binding before allowing the call to fall through to the default implementation (addError is a custom method on $rootScope, while $delegate represents the service being decorated). You could also try to send the errors back to the host and thereby collect errors from all clients.

app.config(function($provide){

    $provide.decorator("$exceptionHandler", function($delegate, $injector){
        return function(exception, cause){
            var $rootScope = $injector.get("$rootScope");
            $rootScope.addError({message:"Exception", reason:exception});
            $delegate(exception, cause);
        };
    });

});

Notice the use of $injector in the above code. Using the $injector service directly is required to avoid a circular dependency error by advertising both $exceptionHandler and $rootScope as dependencies.

Promising Errors

I’m a fan of using catch at the end of a chain of promises. One reason is that catch is the only sure fire way to process all possible errors. Let’s use the following code as an example. 

someService
    .doWork()
    .then(workComplete, workError);

Even though an error handler (workError) is provided to the then method, the error handler doesn’t help if something goes wrong inside of workComplete itself . . .

var workComplete = function(result){
    return  $q.reject("Feeling lazy");
};

. . . because we are already inside a success handler for the previous promise. I like the catch approach because it handles this scenario and also makes it easier to see that an error handler is in place.

someService
    .doWork()
    .then(workComplete)               
    .catch(errors.catch("Could not complete work!"));

Since so many catch handlers started to look alike, I made an errors service to encapsulate some of the common logic.

app.factory("errors", function($rootScope){
    return {
        catch: function(message){
            return function(reason){
                $rootScope.addError({message: message, reason: reason})
            };
        }
    };
});

And now async related activities can present meaningful error messages to the user when an operation fails.

The Special Properties of ngRepeat In AngularJS

Thursday, April 17, 2014 by K. Scott Allen
1 comment

Today’s tip comes straight from the AngularJS documentation, but I’ve seen a few people miss the topic. 

Inside an ngRepeat directive the special properties $first, $last, and $middle are available. These properties hold boolean values ($first is true only for the first repeated element), and two more special properties that are available are $even and $odd.

Another useful property is the $index property, which contains the offset of each repeated element and starts at 0 (like all good offsets).

You can view the following markup live in this Plunker. The code is using $first and $last to avoid showing clickable up and down prompts when an item is in the first or last position. The markup is also using $index to grab the offset of a clicked item.

<table>
    <tr ng-repeat="item in items">
        <td>{{item.title}}</td>
        <td><span ng-show="!$first" ng-click="moveUp($index)">up</span></td>
        <td><span ng-show="!$last" ng-click="moveDown($index)">down</span></td>
    </tr>
</table>

Combined with the following controller, you can move items up and down by clicking on the arrows.

module.controller("mainController", function($scope){
    $scope.items = [
        { title: "Item 1" },
        { title: "Item 2" },
        { title: "Item 3" },
        { title: "Item 4" },
        { title: "Item 5" },
    ];

    var move = function (origin, destination) {
        var temp = $scope.items[destination];
        $scope.items[destination] = $scope.items[origin];
        $scope.items[origin] = temp;
    };

    $scope.moveUp = function(index){            
        move(index, index - 1);
    };

    $scope.moveDown = function(index){                    
        move(index, index + 1);
    };

});

Deconstructing A Function From Microsoft Word 1.1a

Tuesday, April 15, 2014 by K. Scott Allen
5 comments

When Microsoft released the source code to MS-DOS and Word, I had to take a look. One of the first functions I came across was ReplacePropsCa from the srchfmt.c file.

/* %%Function:ReplacePropsCa %%Owner:rosiep */
ReplacePropsCa(prpp, pca)
struct RPP *prpp;
struct CA *pca;
{
    struct CA caInval;

    if (prpp->cbgrpprlChp)
        {
        ExpandCaSprm(pca, &caInval, prpp->grpprlChp);
        ApplyGrpprlCa(prpp->grpprlChp, prpp->cbgrpprlChp, pca);
        if (!vfNoInval)
            {
            InvalCp(pca);
            InvalText(pca, fFalse /* fEdit */);
            }
        }

    if (prpp->cbgrpprlPap)
        {
        int fStc;
        struct CHP chp;
        struct PAP pap;

        if (fStc = (*prpp->grpprlPap == sprmPStc))
            {
            CachePara(pca->doc, pca->cpFirst);
            pap = vpapFetch;
            }
        ExpandCaSprm(pca, &caInval, prpp->grpprlPap);
        ApplyGrpprlCa(prpp->grpprlPap, prpp->cbgrpprlPap, pca);
        if (fStc)
            {
            GetMajorityChp(pca, &chp);
            EmitSprmCMajCa(pca, &chp);
            if (!FMatchAbs(pca->doc, &pap, &vpapFetch))
                InvalPageView(pca->doc);
            }
        if (!vfNoInval)
            {
            InvalCp(&caInval);
            InvalText (pca, fFalse /* fEdit */);
            DirtyOutline(pca->doc);
            }
        }
}

Thought #1: Every Function Has An Owner. Although I see the occasional project where each file has a comment indicating the owner, I don’t remember ever seeing ownership declared on individual functions. I think the concept of collective ownership is a healthier approach to building software, both for the software and the developers. Today’s tools also make it easier to jump around in code.

Thought #2: The Flow Control Is All Wrong. Oh, wait, the flow control seems ok, it’s just the funny indentation of curly braces setting off alarm bells. Joel Spolsky has a post from 2005 titled Making Wrong Code Look Wrong in which he says:

This is the real art: making robust code by literally inventing conventions that make errors stand out on the screen.

After many years in 3 different languages using { and }, my eyes are accustomed to looking for a closing curly brace in the same column as the if. Not seeing the curly means code might accidently execute outside the conditional check. This function hides the closing curly and is full of evil.

Thought #3: The Notation Is Hilarious. Call it Hungarian Notation, or Anti-Hungarian Notation, or something not Hungarian at all but a custom DSL designed in C. In any case the idea of checking to see if a prpp->grpplPap is equal to a sprmPStc is just one brick in a wall of gibberish that reminds me of a Lewis Carroll poem.

`Twas brillig, and the slithy toves
  Did gyre and gimble in the wabe:
All mimsy were the borogoves,
  And the mome raths outgrabe.

Both the function and the poem include gibberish, but at least the Lewis Carroll poem rhymes.

Deep Linking a Tabbed UI With AngularJS

Monday, April 14, 2014 by K. Scott Allen
4 comments

The idea is to dynamically generate a tabbed navigation using Angular and UI Bootstrap.

 I’ve done this before, but this time around I needed the ability to deep link into a tab. That is, if a user bookmarks /someapp/tab2, then the 2nd tab should be active with its content showing.

Tabbed UI Angular JS

Instead of using ngRouter, which is a bit simplistic, I decided to use UI Router. UI Router is not without quirks and bugs, but it does give the opportunity to setup multiple, named “states” for an application, and can manage nested states and routes through associated URLs. One of the first steps in working with UI Router is configuring the known states

var app = angular.module("routedTabs", ["ui.router", "ui.bootstrap"]);

app.config(function($stateProvider, $urlRouterProvider){

    $urlRouterProvider.otherwise("/main/tab1");

    $stateProvider
        .state("main", { abtract: true, url:"/main", templateUrl:"main.html" })
            .state("main.tab1", { url: "/tab1", templateUrl: "tab1.html" })
            .state("main.tab2", { url: "/tab2", templateUrl: "tab2.html" })
            .state("main.tab3", { url: "/tab3", templateUrl: "tab3.html" });
});

In the above code, “main” is a parent state with three children (tab1, tab2, and tab3). Each child has an associated URL (which will be appended to the parent URL) and a template. Each child template will plug into the parent template of main.html, which itself has to plug into the application shell.

In other words, the shell of the application uses the ui-view directive to position the parent template (main.html).

<body ng-app="routedTabs" class="container">

   <div ui-view></div>

</body>

This is not much different than using ngRouter and its ngView directive, but UI router also allows for main.html to use another ui-view directive where one of the child templates will appear.

<div ng-controller="mainController">

    <tabset>
        <tab 
            ng-repeat="t in tabs" 
            heading="{{t.heading}}"
            select="go(t.route)"
            active="t.active">
        </tab>
    </tabset>

    <h2>View:</h2>
    <div ui-view></div>

</div>

This view requires a controller to provide the tab data.

app.controller("mainController", function($rootScope, $scope, $state) {        
   
    $scope.tabs = [
        { heading: "Tab 1", route:"main.tab1", active:false },
        { heading: "Tab 2", route:"main.tab2", active:false },
        { heading: "Tab 3", route:"main.tab3", active:false },
    ];

    $scope.go = function(route){
        $state.go(route);
    };

    $scope.active = function(route){
        return $state.is(route);
    };

    $scope.$on("$stateChangeSuccess", function() {
        $scope.tabs.forEach(function(tab) {
            tab.active = $scope.active(tab.route);
        });
    });
});

The only reason to listen for UI router’s $stateChangeSuccess is to keep the right tab highlighted if the URL changes. It’s a bit of a hack and actually makes me wonder if using tabs from UI Bootstrap is worth the extra code, or if it would be easier to write something custom and integrate directly with UI router.

If you want to try the code for yourself, here it is on Plunkr

Dynamically Injecting Script Tags With AngularJS

Tuesday, April 8, 2014 by K. Scott Allen
0 comments

A few months ago I found myself in a situation where I had to throw some dynamically generated scripts into the browser for testing (and occasionally inspecting and debugging). I wrote a small custom directive to take care of most of the work.

<div ng-controller="mainController">   

    <div otc-scripts scripts="scripts">

    </div>

</div>

In the above markup, it’s the mainController that will fetch the script text for execution, which I’ll simulate with the code below.

app.controller("mainController", function($scope, $timeout) {
    $scope.scripts = [];

    $timeout(function () {
        $scope.scripts = [
            "alert('Hello');",
            "alert('World');"
        ];
    }, 2000);
});       

The rest of the work relies on the otcScripts directive, which watches for a new script array to appear and then creates script tags and places the tags into the DOM.

app.directive("otcScripts", function() {

    var updateScripts = function (element) {
        return function (scripts) {
            element.empty();
            angular.forEach(scripts, function (source, key) {
                var scriptTag = angular.element(
                    document.createElement("script"));
                source = "//@ sourceURL=" + key + "\n" + source;
                scriptTag.text(source)
                element.append(scriptTag);
            });
        };
    };

    return {
        restrict: "EA",
        scope: {
          scripts: "="  
        },
        link: function(scope,element) {
            scope.$watch("scripts", updateScripts(element));
        }
    };
});

I’m sure there are many different approaches to achieving the same result, but note the above code uses document.createElement directly, as this appears to be one foolproof approach that consistently works. The directive also prepends a @sourceURL to the script. If you give your @sourceURL a recognizable name, you’ll be able to recognize the code bits a little easier in the Chrome debugger.

Azure WebJobs With Node.js

Monday, April 7, 2014 by K. Scott Allen
2 comments

Azure WebJobs are background services you can run in the cloud. The experience is easy and smooth. Scott has a thorough overview in “Introducing Windows Azure WebJobs”. 

In a previous post we looked at using JavaScript to read messages from Azure Queue storage.  We can use the code from that previous post in an Azure WebJob by creating a run.js file. WebJobs will automatically execute a run.js file using Node.

var config = require("./config.json");
var queue = require("./queue")(config);

var checkQueue = function () {
    queue.getSingleMessage()
        .then(processMessage)
        .catch(processError)
        .finally(setNextCheck);
};

var processMessage = function (message) {   
    if (message) {        
        console.dir(message);

        // processing commands, then ...

        return queue.deleteMessage(message);
    }
};

var processError = function(reason) {
    console.log("Error:");
    console.log(reason);
};

var setNextCheck = function () {
    setTimeout(checkQueue, config.checkFrequency);
};

checkQueue();

Aimagell that’s needed to deploy the job is to zip up run.js with all its dependencies (including the node_modules directory) and upload the zip into an Azure website. 

The above code expects to run continuously and poll a queue. You can configure each job to run continuously, on a schedule, or on demand in the Azure portal. Azure will store any output from the program in a log file that is one click away. 

Another Useful Link

How to deploy Windows Azure WebJobs by Amit Apple is a behind the scenes look at how to deploy a web job using Git or FTP.

by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!