Since before I started my software development career, I have been using Visual Studio. It is a beast-mode IDE with tons of heavy-weight features and a bountiful supply of extensions. Don’t get me wrong, Visual Studio is near and dear. It has been the key to the successful delivery of many kinds of projects. Since Visual Studio was so useful, I honestly wondered why Visual Studio Code was even created. After using it though, my thoughts changed from “why?” to “this is amazing!”
To be able to view everything on a single screen is hard to do – some would say unnecessary or even Noise. One of the great things about VS Code is that it accomplishes the two feats of allowing a developer to quickly discover what they need during development without needing to wade through the noise. This is done by a simple tab-like interface including Explorer, Search, Git, Debug, and Extensions. The best part about this is the Integrated Terminal. It is very simple to get started, easily accessible, and easily ignored.
Integrated Terminals
My primary use for VS Code is front-end development. VS Code offers great tooling for creating high-quality user interfaces using the latest frameworks such as Angular 2 and React. Full-stack development can be done at once with a single language (JavaScript). With Integrated Terminals, Node.js operations can be performed quickly and easily.
With Extensions offering further integration, I find VS Code especially useful when developing with Node. Its Integrated Terminals allow an easy way of managing Node operations. When developing a MEAN stack application, each tier can get its own terminal for operations specific to that tier.
Dedicated terminals per tier are also beneficial because certain operations are long-running such as running MongoDB, Node and Angular. I tend to create a terminal per long-running operation. VSC makes it very easy to get these started – and to ignore them when they are not appropriate for the current task. For example, I can ignore the DB and Services when styling an Angular 2 component while still maintaining the benefit of them running so I can quickly test my work.
When writing front-end code, I would definitely recommend Visual Studio Code.
Commands
Ctrl+`
Toggle Integrated Terminal Panel
Ctrl+Shift+`
Create New Integrated Terminal Instance
Ctrl+Shift+P
Begin searching the Command Palette
User Interface
Interact with Integrated Terminals like you would a Command Prompt. Multiple instances can be created while being accessible by simply making a selection from the drop-down. From the small toolbar, instances can be removed, more instances can be created, and the down-arrow closes the entire panel.CodeProject
Add E2E testing and make sure your users don’t fail!
Testing your applications is a critical step in ensuring software quality. While many agree, it can be hard to justice the budget for it. This issue can occur when development and testing are imagined as two separable activities. In fact, there are common practices in place designed around their coupling (see TDD). End-to-End (E2E) testing is another common practice designed in this way.
E2E testing can be thought of as an additional direction or angle in which to test an Angular 2 application’s logic. It tests, from a user’s perspective, if the application does what is expected. If these tests fail, your users will fail and the failure will be right in their face. This user-centric approach is critical to ensuring an intended user experience. Writing these tests will produce a detailed user experience specification enforced by simply making sure the tests pass.
End to End testing does not replace QA resources. All software is written by people and people are not perfect – no matter what they say.
Interacting with Your Application
To begin creating the tests we need a way to interact with the application. This is made easier with Protractor. With Protractor, Selenium can be leveraged within JavaScript including integration with Angular applications. A few critical components are exposed to you through Protractor.
browser – browser-scoped operations such as navigating to a particular URL. element – provides a way to retrieve the UI components of your application from within your tests. by – What UI component do you want and how should it be found? promise – support asynchronous operations. ElementFinder – perform operations on retrieved UI components. ElementArrayFinder – perform operations on an array of retrieved UI components.
Importing from Protractor
Importing what you need from Protractor is as easy as importing anything else:
import {
browser, element, by, promise, ElementFinder } from 'protractor';
Navigating to a URL
Get to the correct page using browser.get():
navigateTo() {
return browser.get('/list');
}
Retrieving and Manipulating UI Components:
Use the Protractor API to retrieve elements and perform operations in your application:
Now that a few fundamentals are out of the way, let’s take a look at organizing our tests. First, we need to create Page Objects. These objects encapsulate interactions with UI components. Implementing Page Objects could be thought of as user experience mapping including structure and operations.
With single-page applications, a “Page Object” could get quite unwieldy! This is why we need to consider the structure of the application. Considering the Angular Components within the application is a great way to begin dividing your Page Objects. Take a simple Todo application shown in Figure 1:
Even with this simple application, there is a lot to include in just a single Page Object. This screen can be divided up into four distinct areas: header, menu, list, and details. Let’s look at how these can be created using separate Page Objects:
Alright, that was a lot of code. Let’s take a step back for a moment. We are creating Page Objects representing the distinct areas of the UI that we have determined. Each Page Object has offered the ability to retrieve (e.g. getContainer) and operate (e.g. clickDeleteButton) on UI elements from their respective areas. The last item we need now is a root Page Object to complete our Page Object hierarchy.
The Page Object Hierarchy
Yes, I can’t seem to help it – there is one additional Page Object that has been included along with the root Page Object. The Item Page Object will encapsulate the structure and logic of each todo item within the List.
An instance of each leaf Page Object (which includes header, menu, list, and details) is stored on the root Page Object (TodoApp). This provides the ability to write complex operations while exposing a simple API to your tests:
// snippet todo-app.po.ts
export class TodoApp {
constructor() {
this.list = new List();
}
private list: List;
removeAllItems(): promise.Promise<void[]> {
let promises: Array<promise.Promise> = new Array<promise.Promise>();
this.list.getItems().each(item => {
promises.push(item.clickDeleteButton());
});
return promise.all(promises);
}
}
In removeAllItems() each todo item is found and its Delete button is clicked. We should no longer have any todo items. This is a testable scenario. Testing this would mean answering the question – what happens when there are no items? We can use our Page Objects to create tests around this scenario!
Testing with Page Objects
Creating tests using Page Objects can clean up your tests and allows more explicit definition of your test scenarios. This way also helps keep the user interface definition out of the tests making it easier to maintain – keep in sync with your application!
Jasmine Syntax
If you have written tests using Jasmine before, you know how to create tests for Protractor. It is a great tool for writing unit tests! It is just as good for writing tests with Protractor. Simply follow their tutorials to learn more about Jasmine.
Writing Tests
Now let’s see some tests. We will test the ability to remove all items by clicking their Delete button:
This test sample is following a few common practices. First, the root Page Object is imported:
import { TodoApp } from './todo-app.po.ts';
Next, the top-level test suite is defined. Within this test suite a variable is defined to hold our root Page Object. Then comes the initialization of each test in the suite:
beforeEach(() => {
page = new TodoApp();
});
This is a fairly rudimentary example but, the initialization code will run once before each test in the suite. Make sure to place any necessary test initialization code within this block such as initializing Page Objects and setting up the UI.
Next comes the fun. The test is defined using typical Jasmine syntax with support for asynchronous test code:
The first step in our test is to navigate to the TodoApp and create a variable to hold our new item text and description.
Considering that the test is for ensuring items get deleted when their Delete button is clicked, we need to be sure there is an item to remove! Using a Page Object method for adding an item, a new todo item is added to the screen using the new item text and description defined earlier. Since the method returns a promise, we use then() to continue execution.
We have added an item. Now its time to remove it. We know that the Page Object contains a method that clicks a todo item’s Delete button. We also know that the Page Object provides the ability to remove all of the todo items in the list using this method. This means we can simply call removeAllItems() and check the list to make sure it is empty.
If the test passes we can say the Delete button works for each todo item.
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.
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.
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.
UPDATE: After working with later versions of Angular, I found it to be an effective front-end framework that can solve enterprise-level concerns. I enjoy working with TypeScript and creating stunning multi-faceted projects with the help of Nx Workspaces. To make it easier to get up to speed with the MEAN stack, Manning Publications released a new book called Getting Mean with Mongo, Express, Angular, and Node (2nd Ed.) written by two smashing authors and developers in the field Simon Holmes and Clive Harper. After leveraging this book, I am able to create substantial solutions using the MEAN stack. I highly recommend it even if you are just trying it out. It has a ton of immediately actionable information packed into it.CodeProject
With my latest post, learn how to create SOLID systems by applying common software development principles to layered software architectures – SOLID Systems Using Boundary Interfaces
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.
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 for example “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 declared 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.
Let’s 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:
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.
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) {
/* 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) {
/* 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) {
/* 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) {
/* 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) {
/* 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) {
/* 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 are 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.
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:
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.
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.CodeProject
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, the 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. The first to be examined is the markup.
Check out Part 3 of 4 in my blog series for Magenic featuring Windows Store App Using HTML5 – Asynchronous Data Template Functions. In this article, I introduce asynchronous data template functions. The nature of Windows Store apps is asynchronous. To follow along with this asynchronous nature (as Windows Store app developers should), this article will detail asynchronous template functions.
Asynchronous template functions provide enhanced usability by allowing a user to interact with the app during information retrieval while keeping the user aware of incoming information. This is essential in providing the user with an optimal experience.