Deborah's Developer MindScape

         Tips and Techniques for Web and .NET developers.

April 4, 2016

Why Angular? Why Angular 2?

Filed under: Angular 2,JavaScript @ 10:52 am
Tags: , ,

Why Angular and not some other JavaScript framework? (And there are lots of JavaScript frameworks out there!)


· Angular makes our HTML more expressive. It powers up our HTML with features such as if conditions, for loops and local variables.

· Angular has powerful data binding. We can easily display fields from our data model, track changes, and process updates from the user.

· Angular promotes modularity by design. Our applications become a set of building blocks, making it easier to create and reuse content.

· And Angular has built-in support for communication with a back-end service. This makes it easy for our Web applications to integrate with a backend service to get and post data or execute server-side business logic.

No wonder Angular is so very popular with Web developers!

With so many developers already using Angular 1, why do we need an Angular 2?


· Angular 2 is built for speed. It has faster initial loads, faster change detection and improved rendering times.

· Angular 2 is modern. It takes advantage of features provided in the latest JavaScript standards and beyond such as classes, modules, and decorators. And it leverages Web Component technologies for building reusable user interface widgets. Yet it supports both green field and legacy browsers: Edge, Chrome, Firefox and Internet Explorer back to IE 9!

· Angular 2 has a simplified API. It has fewer built-in directives to learn, simpler binding, and a lower overall concept count.

· And Angular 2 enhances our productivity to improve our day-to-day workflow by providing a consistent pattern for writing our code.

For more information on Angular 2, check out my “Angular 2: Getting Started” course from Pluralsight.

Angular 2: Getting Started

Filed under: Angular 2,JavaScript @ 10:43 am
Tags: , ,

Whether you are new to Angular or new to Angular 2, you’re going to want to come up to speed quickly with Angular 2’s components, templates, and services. My latest Pluralsight course “Angular 2: Getting Started” provides the basics you need to get started building an Angular 2 application.


The course covers the following topics:


o We start with first things first. We’ll select a language and editor to use. Then walk through how to set up an Angular 2 application.

o Next we’ll dive into components. We’ll build the App component using a simple template and minimal component code and metadata. Here the focus is on the code including the what, why, and how.

o We’ll see how to build the user interface for our application using templates, interpolation, and directives.

o We’ll power up that user interface with data binding and nicely format our data with pipes.

o Next we’ll tackle some additional component techniques. We’ll define interfaces, encapsulate styles, and leverage lifecycle hooks to build better components.

o We’ll see how to build a component designed to be nested within other components. And how to communicate between the nested component and its container.

o We often have logic or data that is needed across components. We’ll learn how to build services specifically for this purpose and use dependency injection to inject those services into the components that need them.

o Most Web applications need to communicate with a back-end server to get or post data and to execute back-end business logic. In this module, we’ll leverage http and observables to retrieve the data for our application.

o Our sample application displays multiple views. We’ll see how to set up routing to navigate between those views.

We’re covering a lot of territory. And by the end of our journey, we’ll have a simple, but fully operational Angular 2 application that you can use as a reference for your own development.


February 24, 2016

Understanding C# Delegates

Filed under: C#,LINQ @ 12:10 pm

Delegates are sometimes seen as an ethereal concept, bodiless and hard to grasp. But they don’t have to be that way.

In my latest Pluralsight course: “C# Best Practices: Collections and Generics“, I walk through what a delegate is and how to understand them.


A delegate is simply a type that represents a reference to a method with a specific parameter list and return type. The primary purpose of delegates is to pass methods as arguments to other methods.

Here is an example of a method that needs a delegate:

var filteredList = vendors.Where(???);

In the above line of code, we use the LINQ Where method to filter a list of vendors. The Where method needs a selector defining the logic to be used for the filtering. Do we want to filter the list of vendors by some keyword in their name? Or by how much they currently owe us? Or by the product types that they sell? Somehow we need to specify this logic. We do that with a method.

What does that method need to look like? In Visual Studio, Intellisense shows us the signature of the delegate method that it needs. For the LINQ Where method, it is:

vendors.Where(Func<Vendor, bool> predicate)

Let’s break down what Intellisense is telling us here:

  • The “Func” specifies that the method we create has to return a value. If the method does not require a return value, the Intellisense will instead say “Action”.
  • The first generic parameter (Vendor in this example) is the first parameter to the method we create.
  • If there is a return value, the last generic parameter (bool in this example) defines the return value type.

So looking at the example, we know we need to create a method with a bool return value that takes one parameter of type Vendor.

We can then create a method such as this:

private bool FilterCompanies(Vendor v)
   return v.CompanyName.Contains(“Toy”);

This method takes in a Vendor object and returns a Boolean. Specifically, it returns true if the vendor’s company name contains “Toy”. Otherwise it returns false, thereby specifying how we want the vendor list filtered.

We can then pass this method as a delegate to the Where method:

var filteredList = vendors.Where(FilterCompanies);

The resulting filteredList contains the list of vendors whose company name contains “Toy”.

The problem with this approach is that we end up with little methods all over that simply define these delegates. There is another way. We can use Lambda Expressions. Lambda Expressions are basically a short cut syntax for these little methods.

So instead of this:

var filteredList = vendors.Where(FilterCompanies);

private bool FilterCompanies(Vendor v)
   return v.CompanyName.Contains(“Toy”);

We can simply type this:

var filteredList = vendors.Where(v => v.CompanyName.Contains(“Toy”));

For more information, check out: “C# Best Practices: Collections and Generics” from Pluralsight.


January 28, 2016

C# Best Practices: Collections and Generics

Filed under: C#,Lambda Expressions,LINQ @ 12:27 pm

The next in my series of “Best Practices” courses was published today in the Pluralsight library: “C# Best Practices: Collections and Generics“.

This course starts with the classic collection type: arrays. Then it moves on to generics … that challenging to explain topic that often shows up even in the most basic of beginner courses … because without generics we don’t have a good way to work with collections of things. And most applications require working with collections of things.


We move on to cover generic lists and generic dictionaries. Then we dive deeper into generic collections, looking at the interfaces they implement and how to leverage those interfaces as method parameters and return types.


Lastly, we look at Language Integrated Query (or LINQ) for filtering, shaping, ordering, grouping, aggregating, or locating elements in a collection. Along the way we cover extension methods, delegates, and Lambda expressions.



January 26, 2016

Creating a Filter Pipe in Angular 2

Filed under: Angular 2,AngularJS @ 4:23 pm
Tags: ,

Angular 1.x has filters. Angular 2 has pipes, which fulfill a similar purpose. However, there are some key filters in Angular 1.x, such as the “filter filter”, that don’t have an equivalent Angular 2 feature. This post details how to build a filter pipe in Angular 2.

Angular 1.x

In Angular 1.x, we define an input box for a user to enter filter text. We then filter a list of items by that text with one simple clause as shown below:

<div class=”row”>
    <div class=”col-md-2″>Filter by:</div>
    <div class=”col-md-4″><input type=”text” ng-model=”listFilter” /></div>

<div class=”table-responsive”>
    <table class=”table”>
            <tr ng-repeat=”movie in vm.movies | filter : {title:listFilter}“>
                <td>{{ movie.title}}</td>
                <td>{{ movie.director }}</td>
                <td>{{ movie.mpaa | uppercase}}</td>

Easy breezy.

Angular 2

Angular 2 provides pipes for this same purpose. But with no “filter” pipe in Angular 2, we have to build our own pipe component.

Converting the above code into Angular 2 results in:

<div class=”row”>
    <div class=”col-md-2″>Filter by:</div>
    <div class=”col-md-4″><input type=”text” #listFilter (keyup)=”0″ /></div>

<table class=”table”>
        <tr *ngFor=”#movie of movies | movieFilter:listFilter.value” >
             <td>{{ movie.title}}</td>
            <td>{{ movie.director }}</td>
            <td>{{ movie.mpaa | uppercase}}</td>

Hmmm. That does not look that different!

A few things you’ll notice here:

  • The local variable, listFilter, is now prefixed with a hash symbol (#) to explicitly identify it as a local variable.
    • This variable defines an HTML element, so to obtain the value, we need to access listFilter.value.
  • The (keyup)=”0″ syntax sets up an event listener for the keyup event. There is no event handler needed for this event, so it is just set to “0”.
  • The filter clause is defined here as movieFilter and we are filtering on the value of the listFilter variable. So our custom pipe is used just like the built-in pipes.

The key is creating the movieFilter pipe. In Angular 1.x, the “filter filter” was built in. In Angular 2, there are some built-in filters, but not a general list filter. So we need to build our own.

The purpose of a pipe is to take in a value, filter that value, and return the filtered result. In this example, the value we are taking in is a list of movies. We filter the movies to only those with a title containing the user-entered text. And we return the filtered result.

Here is the code for the movieFilter. The description follows.

import {Pipe, PipeTransform} from ‘angular2/core’;

    name: ‘movieFilter’
export class MovieFilterPipe implements PipeTransform {

    transform(value: any, args: string[]): any {

       let filter = args[0].toLocaleLowerCase();
       return filter ? value.filter(movie=> movie.title.toLocaleLowerCase().indexOf(filter) != -1) : value;

1) First we import the Pipe and PipeTransform. This is required to build any pipe.

2) We define a Pipe decorator. This tells Angular that this code is a pipe component. And we give the pipe a name: movieFilter. This is the name used in the HTML as part of a template expression.

3) We create a class that provides the processing for our pipe. We export the class so it can be imported by our movie component. And we implement the PipeTransform interface for our tooling. Note that implementing this interface is optional. With the @Pipe decorator, Angular already expects to find a transform method.

4) The PipeTransform interface requires implementing a transform method. This method has two parameters:

  • value: The value being filtered. In our example, this is the list of movies.
  • args: An optional array of parameters, one for each parameter passed to the pipe. In our example, we are passing listFilter.value.

5) We then define a result array which will contain the movies that match the filter criteria.

6) We create a variable to hold the passed in parameter. We use toLocaleLowerCase() so that the filtering won’t be case sensitive.

7) We check the filter variable. If there is no filter defined, we simply return the original value. No need to iterate the list. Otherwise we use the JavaScript filter function to filter the list and return it.

NOTE: This code could be simplified using regular expressions.

Lastly, we need the component:

import {Component} from ‘angular2/core’;
import {MovieFilterPipe} from ‘../common/movieFilter.pipe’

    selector: ‘mh-movie-list’,
    templateUrl: ‘app/movies/movieListView.html’,
    styleUrls: [‘node_modules/bootstrap/dist/css/bootstrap.css’],
    pipes: [MovieFilterPipe]
export class MovieListComponent {


This is the component associated with the movie list view. The two critical steps for the pipe are:

1) Import the MovieFilterPipe.

2) Identify the pipe using the @Component decorator’s pipes array. This provides the list of all custom pipes available for the template.

For more information on Angular 1.x vs Angular 2, see “Angular 1.x to Angular 2 Quick Reference“.

For a sample application, see “Angular: 3 Flavors” which has the same application in Angular 1.x, Angular 1.x with TypeScript, and Angular 2.


January 25, 2016

Angular 1 to Angular 2 Quick Reference

Filed under: Angular 2,AngularJS @ 5:04 pm

The post that was here has been edited and re-published here:


January 21, 2016

Dividing a C# Application into Components

Filed under: C# @ 2:52 pm
Tags: , ,

A good architecture divides an application into components:

  • We build UI classes in the UI layer
  • Domain entity classes in the business logic layer
  • Data access classes in the data access layer.
  • And library classes in the common library component.

The content for this blog post was taken from the Pluralsight course entitled “C# Best Practices: Improving on the Basics“. Check out this course for more information.


UI Layer

When we add a form to a UI component, such as a Windows Forms, WPF, or a Web Forms project, Visual Studio automatically creates a form class for us. So our application will have one class for each form. The form class should contain code that:

  • Responds to form events by calling the business logic layer to perform needed processing.
  • Includes error handling for any errors that occur.

There is another type of class that you may find in the UI layer, and that is a V/M or View/Model class. A View/Model manages the data and interaction for a single form or view. A View/Model class is often used in cases where the user interface can bind directly to data defined in the View/Model class, such as with WPF.


Business Logic Layer

When defining classes for the business logic of an application we can start by defining a domain model. A domain model identifies the basic business entities to be managed by the application and how they are related.


For example, if Acme Inc needs a feature to order more product inventory from a vendor, we can define a domain model that includes

  • An order.
  • The product to order. So the order “has a” product.
  • And the vendor from whom the company buys that product. So the product “has a” vendor.

We can use the domain model as a starting point for defining the classes in the business logic component. We’ll need a class to manage each order, a class to manage product information, and a class that manages each approved vendor.

Defining the domain model helps us to consider all of the different bits of logic that the application will require and organize that logic into appropriate classes.

Also in the business logic layer we may want Repository classes. Repository classes are responsible for managing the in memory repository of data for the application. For example, when the user requests display of a specific vendor and the products purchased from that vendor, the Repository classes are responsible for getting that data, tracking the state of that data (for example, whether it has been changed) and saving that data using the data access layer.


Data Access Layer

The classes in the data access layer depend on the data access strategy you are using. If you are using Entity Framework, you may not need any classes in this layer because Entity Framework defines them for you.

Common Library Component

We can determine whether specific functionality goes into a library component by looking at the other components. If the functionality is common across layers (or across applications), then it may be better in a library component. For example, code that provides logging, or sends out email.



When is it appropriate to divide an application into components and define classes such as these? Maybe always? Even if we are developing a prototype, way too often that prototype becomes the basis of our real application.

By breaking the application into a set of components early on in the development cycle we start with a strong foundation that can support the application as it grows and changes over time.


September 4, 2015

Use TypeScript to Prepare for Angular 2

If you are developing now in Angular 1.x with an eye toward Angular 2, the best thing you can do is to write your Angular code with TypeScript. Angular 1.x code you write in TypeScript today will look very similar to code you will write in Angular 2 tomorrow (not literally tomorrow!).

At a recent Angular conference, the members of the Angular team from Google stated that one of the best ways to code now in Angular 1.x in preparation for Angular 2 is to use TypeScript.

What is TypeScript?


TypeScript is an open-source programming language that is:

  • A superset of JavaScript
    • Including all of the current JavaScript syntax, plus much more.
    • Any valid JavaScript code is valid TypeScript code. And as such, TypeScript works with all existing JavaScript frameworks, including Angular.
  • TypeScript transpiles to plain JavaScript
    • So we can deploy the resulting JavaScript files for our Angular application just as we do now.
    • And the resulting files execute in any of today’s browsers on any OS.
    • Plus there is no runtime overhead of using TypeScript because all of the types evaporate and the TypeScript-only syntax is replaced … leaving only pure JavaScript.
  • TypeScript allows us to define strong types
    • Editor tooling, such as the new Visual Studio Code editor, use these types for static type checking of our code during development
    • This makes development, debugging, and refactoring easier.
    • Plus it clarifies the developer’s intent. For example, we can define that a function is meant to take in a string. Not a number, not an object, just a string.
  • And TypeScript provides class-based object-oriented programming techniques.
    • So we can optionally think of our code in terms of objects with properties and methods.
    • And the TypeScript compiler transpiles the classes into JavaScript functions.

Here is the code for an Angular controller, written using the class-based object-oriented programming techniques available in TypeScript.


To learn more about using Angular with TypeScript, check out the Pluralsight course: “Angular with TypeScript



August 12, 2015

"Angular Front to Back with Web API" Problem Solver

Angular and ASP.NET Web API are like chocolate and peanut butter, they are GREAT together! But there are lots of intricacies and many, many things that can go wrong when putting these two technologies together. This problem solver covers some of the most common things that can go wrong and how to fix them.


Using Angular as the client technology in the front-end and an ASP.NET Web API service in the back-end is a common requirement. So much so, that I developed a Pluralsight course to help developers tackle all of the touch points between an Angular client application and a back-end ASP.NET Web API service: Angular Front to Back with Web API.

As of this writing, there have been over 400 posts associated with that course, many of which identify problems that developers have had in merging these two technologies. This post summarizes the most common issues and identifies locations in the course where solutions to these issues can be found


No Access-Control-Allow-Origin Header is Present

This issue first appears in module 3 (Retrieving Data) clip 6 (Calling the Web API from Angular). We created the ASP.NET Web API code in a project separate from the Angular code. So when the solution is executed:

When the Angular code calls the ASP.NET Web API, it will work in Internet Explorer but *not* in Chrome. In Chrome, pressing the F12 tools will show the error: No “Access-Control-Allow-Origin” header is present, Status Code: 500 Internal Server Error.

This is a problem with cross-origin requests. Since the origin of the call is from http://localhost:52436 and the endpoint is at http://localhost:52293, the request is considered to be a cross-origin request. In other words, the request is originating at a different URL than the service. By default, cross-origin requests are denied. (This works in debug mode with IE because IE does not consider the difference in port numbers to be a cross-origin request.)

The solution to this problem is CORS, or cross-origin resource sharing. Wikipedia states that CORS “allows many resources … on a web page to be requested from another domain outside the domain from which the resource originated.” In other words, CORS defines a way that a service can interact safely with a browser application that originates on a different domain or different server.

To enable CORS in the ASP.NET Web API, start by downloading the CORS package using NuGet Package Manager.


Once CORS is installed, there are two additional steps:

1) Call the EnableCors method.

Open the WebApiConfig.cs file in the App_Start folder. Add this line to the Register method:


2) Set the EnableCorsAttribute.

Set this attribute on any controller class that wants to allow cross origin requests. For example, on the ProductsController, it might look like this:

[EnableCorsAttribute(“http://localhost:52436″, “*”, “*”)]
public class ProductsController : ApiController

Note that the port shown in red is the port for the Angular application. This code tells the PrioductsController class that it should allow cross-origin requests only from the defined location, which is from our Angular client application. Alternatively, use “*” to allow access from any cross-origin request.

These steps are covered in detail in module 4 (CORS and Formatters) clip 3 (Enabling CORS in a Web API service).

OData Does Not Work

This issue appears in Module 6 (Using OData Queries) and often takes the form of a problem with the contains method of the OData $filter. This problem is due to confusion on the multiple OData packages that are available in Visual Studio.

The course requires version 4 of OData, so be sure to select the NuGet package that says “OData v4.0” in the description.

NOTE: There are many similarly named NuGet packages, such as “Microsoft.Data.OData” and “Microsoft.AspNet.WebApi.OData”. Be sure to select the one shown below.


User Login Generates a CORS Error

This issue appears in module 10 (User Registration and Login). It often only occurs in Chrome (not IE).

There are two possible issues here:

1) There is one line of code that is missing from the demo in the course.

[EnableCorsAttribute(“http://localhost:52436″, “*”, “*”)]
public class AccountController : ApiController
{ }

This line of code enables CORS for the AccountController just as we did for the ProductsController earlier in the course (module 3)

2) There is one line of code added during the demo, but is sometimes missed when coding along.

In the Providers folder, ApplicationOAuthProvider.cs file, GrantResourceOwnerCredentials method, add the following line:

    new[] { “
http://localhost:52436″ });

Where the defined URL shown in red is the location of the Angular application that this code is granting access to.

This code is explained and demoed in module 10 (User Registration and Login) clip 4 (Logging the User In) starting around 9:32 with showing the error and the line of code is added at 10:13.

User Registration Network Methods

Several questions have come up regarding the network methods that occur when the Register button is selected to register a new user. I entered a new user name and password, then clicked the Register button. The results are shown below when using Chrome on Windows:


Hope this answers the questions.

Save Issues

I have not been able to reproduce any specific issue here … but if you have problems with the Save operation … Try changing this in productResource.js:

‘save’: {
    headers: { ‘Authorization’: ‘Bearer ‘ + currentUser.getProfile().token }

With this:

‘save’: {
    method: ‘POST’,
    headers: { ‘Authorization’: ‘Bearer ‘ + currentUser.getProfile().token }

Cannot Read Property ‘exceptionMessage’ of Null

This is most likely caused by the exception handling in mainCtrl.js. Change this:

function (response) {
    vm.password = “”;
    vm.message = response.statusText + “\r\n”;
    if (
        vm.message +=;

    if ( {
        vm.message +=;

To this:

function (response) {
    vm.password = “”;
    vm.message = response.statusText + “\r\n”;
    if ( &&
        vm.message +=;

    if ( && {
        vm.message +=;

Please let me know if you have run into anything else that should be added to this list.


Automatic Compilation in VS Code for TypeScript

Filed under: TypeScript,VS Code @ 2:19 pm
Tags: ,

By default, when you use VS Code with a TypeScript project, you need to use Ctrl+Shift+B (or Cmd+Shift+B on a mac) to build the application and transpile the TypeScript to JavaScript. But there is a way to make this process more seamless.

To set up VS Code to watch for changes and transpile automatically requires two steps:

1) Modify the tsconfig.json file for the project.

2) Run the TypeScript compiler on the folder for the project.

Let’s look at both of these steps in detail.

Modify the tsconfig.json File

The tsconfig.json file configures TypeScript for your project. In the tsconfig.json file you can define compiler options, such as the version of JavaScript you’d like the transpiler to use. The TypeScript code is then transpiled to the selected version of TypeScript.

To configure VS Code for automatic compilation, you need to add a watch property here:

    “compilerOptions”: {
        “target”: “ES5”,
       “watch”: true

NOTE: The intellisense does not seem to know about the “watch” option. So you won’t see it in the list of available compiler options. But it does work.

Run the TypeScript Compiler

You can manually run the TypeScript compiler from within VS Code by using Ctrl+Shift+B (or Cmd+Shift+B). Alternatively, you can manually run the TypeScript compiler from the command window (also called a terminal).

1) Right-click on the index.html file in the VS Code Explore pane and select Open in Console.

This opens a command window defaulted to the current project directory.

2) Type tsc.

Typing tsc (for TypeScript compiler) immediately transpiles all of the TypeScript code in the directory (and subdirectories) to JavaScript. Without the “watch” setting, if you later make changes to the TypeScript code, you have to re-run the tsc command to transpile the changes.


HOWEVER, if you have the watch compiler option set to true as shown in the code example above, running tsc here produces a different result. In this case, the TypeScript compiler will immediately transpile all of the TypeScript code in the directory (and subdirectories). But then, it will start watching for changes. Any change it sees to the files in the directory will automatically be transpiled. Notice in the screen shot below that it watched me make 3 changes and compiled after each of them.


If you leverage VS Code’s AutoSave feature, and turn on the watch following the two steps detailed above, then the TypeScript compiler will transpile your TypeScript files every time you make a change.


For more information on other techniques when building an Angular application with TypeScript, check out my Pluralsight course: “Angular with TypeScript”

Thanks to Greg who posted this suggestion to the Discussion forum for my Pluralsight course.

« Previous PageNext Page »

© 2016 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs