Angular 2 in the MEAN Stack – A Project Template

I recently became aware of the beauty of developing with the MEAN stack. It started with my desire to brush up on Angular 2 and using the Angular CLI. I ended up with a TODO application that runs on Node using MongoDB, Express.js, and Angular 2 (from a foundation found here: https://scotch.io/tutorials/mean-app-with-angular-2-and-the-angular-cli).

I am also a fan of LESS. It makes writing modular CSS a breeze. I am also not yet sold on the Styled Component approach Angular is now pushing. I do believe Component-based UI architectures make writing modular CSS quite simple. I just don’t think styles should be located across the application when, with an optimally modular UI, the CSS used can be quite minimal. Beyond that, an application should have a look and feel that gives the user at least the illusion of cohesiveness. Easily done when styles are in one place.

Using Feature Modules with Angular 2 makes a lot of sense. Each feature can be created in isolation while still being integrated with the rest of the application. The module structure of the TODO application is shown in Figure 1. This structure allows the application to be extended and makes features easy to find for updates and bug fixes. The approach also provides a more SOLID application.

todofeaturemodule
Figure 1: Module structure

With the focus on Angular 2, the server-side code is quite minimal and I don’t have much to say about it. Figure 2 depicts the main ideas.

todoapi
Figure 2: Server-side

I almost forgot to mention that this app is on GitHub: https://github.com/calebmagenic/ng2-mean. Let me know your thoughts!

I look forward to continuing my work with the MEAN stack and sharing what I find that works – and what doesn’t work so well. Look for more in the future.

PhoneGap Resources

Everything from healthcare to financial advisory to games, the app stores have been filling up with apps made using PhoneGap as the platform rises in popularity. This is unfortunate at best.

This means app developers will need to learn how to develop apps using PhoneGap. This post is meant as a list of online resources to learn from.

That is all for now. Lets try to keep this updated. The poor developers that need to use this platform will thank you.

Pad A String In JavaScript Using Augmentation

Ever needed to pad a string in JavaScript with a certain character? This article will describe a simple extension to the String prototype that will do just that! -Perhaps with a bit more flexibility.

To get right to the point, here is the implementation:

if ( "undefined" === typeof String.prototype.pad ) {
    String.prototype.pad = function _String__pad ( obj ) {
        var result = this,
            width = 2,
            padChar = "0",
            prefix = false;

        if ( obj ) {
            if ( "object" === typeof obj ) {
                if ( obj.prefix ) { prefix = obj.prefix };
                if ( obj.width ) { width = obj.width };
                if ( obj.char ) { padChar = obj.char };
            } else if ( "string" === typeof obj ) {
                padChar = obj;
            } else if ( "number" === typeof obj ) {
                width = obj;
            }
        }

        while ( this && width > result.length ) {
            if ( prefix ) {
                result = padChar + result;
            } else {
                result += padChar;
            }
        }

        return result;
    };
}

Before I get to the guts of the above code snippet, I wish to examine a few reasons it is possible:

  • Instance methods can be created on-the-fly. This means a String object such as “Hello World” would immediately contain the above method named “pad”. The method could be called like “Hello World”.pad().
  • JavaScript is a dynamic language. In this case, it means any variable can be of any type at any point during runtime.
  • A method exists as a “function”. This can be explicitly tested.
  • Instance methods exist in an Object’s prototype.

Now for the details.

First, it is always wise to make sure your code is not performing unnecessary work. To this end a check is made to make sure the function does not already exist on String’s prototype. If it does not already exist, it is created.

Four variables are then declare presenting the features of this method:

  • Returns a new string
  • Supports a custom string width
  • Supports a custom padding character
  • Supports either prefix padding or suffix padding

These variables are optionally overridden by the object, String, or Number argument given. This is one of many times when the beauty of JavaScript’s weakly-typed nature really shines. Any of the features can be overridden given the appropriate argument type and value. If the argument is an object, the method expects the object to contain the three properties: prefix, width, and char. If the argument is a String the method assumes the client is attempting to override the padding character. If the argument is a number, the method assumes the client is attempting to override the padded string width.

Lets talk more about the padded string width. This is important for the next bit of code.

Assume there is a string indicating an order number of “99D”. The requirements say order numbers less than 5 characters must be padded on the left with zeros. The implementation supports this:

"99D".pad({ char: "0", width: 5, prefix: true }); //result: "0099D"

-or-

var orderNumber = "99D";
orderNumber.pad({ char: "0", width: 5, prefix: true }); //result: "0099D"

-or-

var padOptions = { char: "0", width: 5, prefix: true };
"99D".pad(padOptions); //result: "0099D"

To get this set width, a while loop is used. While the string is less than the given width, the method adds the specified pad character to either the beginning or the end of the string based on whether it should be a prefix or not. Once the string is at least the length of the specified padded string width, the method breaks out of the while loop and returns the resultant string.

There are other ways to use this implementation of the pad method as well:

Specify the padding character –

"E".pad("T"); //result: "ET"

Specify the padded string width –

"1".pad(2); //result: "10"

There are a few improvements or additional features that could be implemented for this method but, this is a flexible start.

Safe & DRY JavaScript Augmentation

Augmentation is one of my favorite features of JavaScript. Being able to, at any point, add static and instance methods to new and existing types is a wonderful feature of this dynamic language. In this post I’ll describe two common ways of augmenting JavaScript types and how those ways can be made safer while adhering to the DRY principle.

Instance Methods

One of the most common uses of augmentation is adding instance methods to types. Using a type’s prototype chain, methods can be added to all new and existing instances of the augmented type:

Array.prototype.indexOf = function (item) {
    /* Body Excluded for Brevity */
};

In this code snippet the “indexOf” function was added to the prototype of the Array object. Each Array instance will have this method (even if the instance was created before the method was defined). This method will also replace any previous implementations of the “indexOf” function. It is best to make sure the function doesn’t already exist:

if (typeof Array.prototype.indexOf === "undefined") {
    Array.prototype.indexOf = function (item) {
        /* Body Excluded for Brevity */
    };
}

Here the typeof operator is used to determine whether the method is undefined. If it is, the method implementation is added to the Array object.

Static Methods

Functions can also be added as static methods of a given type:

String.Format = function (format) {
    /* Body Excluded for Brevity */
};

In the code snippet above the “Format” method was added as a static method of the String object. Similar to adding instance methods, it is best to make sure this method does not already exist:

if (typeof String.Format === "undefined") {
    String.Format = function (format) {
        /* Body Excluded for Brevity */
    };
}

Don’t Repeat Yourself

If your augmentation code is augmenting multiple types or with multiple methods, the type check will be used over and over. Why not make that part of the code reusable? By using augmentation, a reusable method can be implemented to perform this type check and the augmentation:

if (typeof Function.safeAugment === "undefined") {
    Function.safeAugment = function (obj, func, impl) {
        var method = obj[func];
        if (typeof method === "undefined") {
            obj[func] = impl;
        }
    };
}

Here the augmentation code is wrapped inside the “safeAugment” function. This function is implemented as a static method of the “Function” object. The “safeAugment” function takes three parameters: the object to augment, the function name to add to the object, and the implementation of the function. Here is an example of its use:

Function.safeAugment(Array.prototype, "indexOf", function (item) {
    /* indexOf Body Excluded for Brevity*/
});

The safeAugment function is used to define our indexOf instance method for the Array object. The safeAugment function can be used to defined static methods as well:

Function.safeAugment(String, "Format", function (item) {
    /* String.Format Body Excluded for Brevity*/
});

Here the “Format” method is added to the String object as a static method.

Enhancing the Augmentation Code

As it stands now, the safeAugment function performs its duty: augment the given object with the given method with the given implementation. The first and most obvious improvement would be to validate its parameters. This means making sure that each parameter is of an expected type so the object to augment exists, the function name is a string (and not null), and the implementation is a function. Improvements beyond this is more dependent on your given circumstances. Perhaps you want to allow the implementation to be null, or add logging capabilities, or locate the point in which all the elements in the multiverse will collide, etc, etc. The point is to safely augment JavaScript types while adhering to the DRY principle.

Detecting Windows Store App Configuration Mode (Debug vs Release) in JavaScript

Windows Library for JavaScript (WinJS) is an amazing library. This along with the projected winmd libraries, developers have almost everything they would ever need to develop an average Windows Store App. One thing that is missing that I recently came across is the ability to detect which configuration mode the App is currently running in (Debug or Release).

I needed to enhance a few debugging capabilities if the App is in Debug mode. To detect the current mode in JavaScript I used the beauty of language projection. The following sections will examine this in more detail.

C#

First, I used a C# Windows Runtime Component to enable the capability of using the implementations in JavaScript. I then created what I called a ConfigurationManager. Below is the code:

namespace AppName.Utilities
{
    public sealed class ConfigurationManager
    {
        public static bool IsDebug {
            get {
#if DEBUG
                return true;
#else
                return false;
#endif
            }
        }
    }
}

The simplicity of this class cannot be overstated. It has a single static property called “IsDebug”. The key part of the implementation is the use of compiler directives #if and #else.

#if the DEBUG constant is defined, then the App is in Debug mode. #else (Otherwise), the App is in Release mode.

JS

After adding a reference to this component and rebuilding, I can now detect the current configuration mode in the JavaScript App:

var isDebug = AppName.Utilities.ConfigurationManager.IsDebug;
if(isDebug) {
    //debug-specific code.
} else {
    //release-specific code.
}

Please note that this depends on the compiler. There is one potential issue with this: the perceived configuration mode of the App is solely dependent on the configuration mode of the projected component.

Appendix A

There is a “Debug” object in JavaScript. This object does not contain abilities to determine the configuration mode but merely whether a debugger is attached (and various other debugger type mechanisms). This object also exists in both Debug and Release modes. The solution provided in this article shows one of the easiest ways of accomplishing the feat of determining whether the configuration mode is Debug or Release.

Windows Store Apps Using HTML5 – UI Virtualization (Part 4 of 4)

Check out Part 4 of 4 in my blog series for Magenic featuring Windows Store Apps Using HTML5 – UI Virualization (Part 4 of 4). In this article I introduce UI Virtualization using asynchronous data template functions. The performance of Windows Store Apps is important to consider, especially when handling large collections of data. When displaying the collection, performance can be degraded. In part three, first steps were taken to alleviate the performance problems that can arise under heavy data usage. Part four will describe further performance improvements using UI virtualization.

Asynchronous data template functions enable substantial user experiences by keeping an app responsive and informative. This article’s implementation of UI virtualization relies on these concepts of asynchronous data template functions. The following sections will describe the main components of the implementation along with the differences from simple asynchronous data template functions. First to be examined is the markup.

Read more here:

http://magenic.com/Blog/WindowsStoreAppsUsingHTML5UIVirtualization