post image

Aurelia – TypeScript – ASP.NET 5 – VS Code




Get started with Aurelia – TypeScript – ASP.NET 5 – VS Code

A while ago I wrote a blog post about how to get up and running with the Aurelia skeleton for TypeScript on ASP.NET 5 (This Aurelia Skeleton on ASP.NET 5). But now the Aurelia team now have their own setup, making it even easier to get started! :)

Pre-Requisites

Things that need to be installed on your system:

  • ASP.NET 5
  • Node

Node packages that needs to be installed globally:

  • gulp
  • jspm

Get the code

Go to the Aurelia skeleton repo on GitHub
Download as zip, use GitHub for Desktop or whatever you prefer.

Install dependencies

Open a cmd prompt in the project root and install the project dependencies with:

  • npm install
  • jspm install

Build the code

In the cmd prompt, use the following to build the client side code:
gulp build

Then open VS Code and open the folder skeleton-navigation\skeleton-typescript-asp.net5\src
VS Code will the prompt and ask to restore missing packages, accept this request.

Now start the ASP.NET 5 host by typing the following in the cmd prompt:
dnx web

Now open a browser and go to http://localhost:9000, if everything has worked, you should see the Aurelia navigation skeleton!



Happy coding :)




ASP.Net 5/Core – IIS Express and SSL




Setting up SSL on a dev machine running self hosting

After a lot of yak shaving this is what I found to be the easiest way to set up my dev machine(Win10) using SSL for ASP.NET Core development.

Prerequisites

IIS Express needs to be installed on your machine already. Since the whole idea is to borrow the cert it uses. If not, use makecert and create your own certificate.

Steps to success

Follow the steps below to use the IIS Express certificate to enable SSL against localhost.

1. Get the cert Hash and App ID

An easy way to get the Hash and App ID of the cert is to list all http bindings in a file, just open a CLI and enter the following:
netsh http show sslcert > output.txt
This will list all the bindings in the file named output.txt, the IIS Express cert is the one registered on port 44300 and above.

Make note of the Hash and App ID.
Certificate Bindings port 44300 IIS Express

2. Add SSL for a selected port

Add the cert for our selected port 5043 with:
netsh http add sslcert ipport=0.0.0.0:5043 appid={AppId} certhash=CertHash
Note, if you’re CLI of choice is PowerShell, you need to add single quotes around the curly bracers.
If everything goes well you’ll see:
“SSL Certificate successfully added”

3. Setting up project.json

Set the web command in project.json to:
“web”: “Microsoft.AspNet.Hosting –server Microsoft.AspNet.Server.WebListener –server.urls https://localhost:5043”
Make sure a dependency on “Microsoft.AspNet.Server.WebListener”: “1.0.0-rc1-final” is added, if not add it and run a “dnu restore”

Running “dnx web” should now start the server correctly and browsing https://localhost:5043 should be possible, although it will complain the connection is not private.
https dnx asp.net 5 asp.net core

Eventual issues

SSL Certificate add failed, Error: 1312
A specified logon session does not exist. It may already have been terminated.

If you end up with this problem when adding the ssl cert to the port, make sure the cert is in the Personal Certificates store. (Name of the cert is localhost)

The parameter is incorrect.

If you’re seeing this, chances is you are using PowerShell and and forgot single quotes around the angle brackets.

Happy coding :)

post image

VS2015 Restore Packages Not Working Properly

Visual Studio 2015 – Don’t trust the package restore

I ran into a problem at work the other day, after a branch merge all icons disappeared in our webapp for me.

We recently introduced a new build step in SASS where we colorize our SVG-icons, so it wasn’t too hard to figure out what had changed. What caused it though was a whole other problem, as no other team member had the same problem as me.

After sprinkling some log prints in the SASS-function used to fix our icons, it was evident it wasn’t being run at all. Fun thing was, there were no errors reported during the build step either.

The automatic package restore

Visual Studio 2015 Unresponsive Pakage Restore bower_components

How I spend a third of my workday on release day…

After some head scratching I decided to check versions of the npm packages in use. It turned out that this was ‘der pudels kern’.
The version of gulp-sass was specified as v2.1.1 in the package.json file, but on disk I had v1.3.3. I was naively thinking that the package versions would be correct since Visual Studio does a ‘Package Restore’ when loading a solution.

Loading a solution and running package restore is what happens when you swap branch, which I had done several times when I ran in to this issue.

Npm Install

Behind the scenes the Package Restore step is running ‘npm install’. So question is, was it a problem with the npm tooling or a Visual Studio issue?

Whatever the reason, the important thing is to know that Visual Studio’s ‘npm install’ isn’t to be trusted. Always check your npm packages after having version dependencies updated from a merge or pull.

Effects of Package Restore

Personally I think that this “Package Restore” behavior needs to be changed. When running larger solutions containing several Web Projects you’ll end up with a npm install running for all projects in the Solution when you open it or change branch.

At work we got a fairly large Solution with about 10 projects in it, and just swapping branch takes 15 minutes for the package restore, often more as my VS2015 crashes mid operation every other time. And then it takes 15 minutes more for the package restore that happens when I have to start up the studio again and load the solution.

My work machine is a three year old laptop, but it has got an i7 and 8GB of ram. Still it totally bogs down when the package restore is being run. And as web development should be accessible to all, it’s unfair to require a new stationary machine just to have a sane working development flow.

Improving Package Restore

First of all, the Package Restore functionality should be an option in the Visual Studio web tooling. I’ve seen rumors it’s possible to turn it off by disabling all External Web Tooling under Options, but this seems very clunky and quite the opposite of what we really want.

Even better would be if Visual Studio checked all installed packages and saw if they already matched what was specified in package.json. ViΓ³la, no need for unnecessary restores!

Oh, and if any one on the VS Team get’s to read this, clicking the bower_components folder totally hangs my VS too!

In Closing

If you are having the same issues or just agree with the improvement suggestions, please help forward these concerns to the Visual Studio Web Tooling Team!

Happy Coding! :)

PS. Yes, I have used the feedback tool in Visual Studio. Many times. With no response. DS.

post image

Aurelia Skeleton on ASP.NET 5

Running the Aurelia Skeleton app on ASP.NET 5

Aurelia TypeScript VS Visual Studio Code
On Dec 17:th Rob Eisenberg blogged about a new patch on for Aurelia. Performance, Bug Fixes and Documentation improvements. The thing that got me the most excited was the announcement that the Aurelia Navigation Skeleton had been improved for the TypeScript scenario and adapted to be run under VS Code!

The Aurelia Skeleton Nav project is a nice piece of code! Planned to be used in a production scenario, so it has all kinds of goodness setup, like a watch task, bundling, unit and integration tests.

But as I’m a Microsoft guy, it lacked one thing. A setup to be able to run it on ASP.NET 5 instead of node.

Get the Aurelia project

First off, download the project from Aurelia.io, you can get it here.

Setting up the project to run on ASP.NET 5

A few pre-requisites is needed to be able to run the project to start of with. Let’s first sort all the npm packages needed.

Installing npm packages

First off we need to install the npm packages.

As some of the packages need depend on node-gyp to be compiled, Python needs to be installed on your machine.
If you haven’t got Python installed, download and install it. Version 2.7.10 is the recommended install for node-gyp.
Node-gyp is also need a C++ compiler. If you are running Windows 10, install any version of Visual Studio 2015 that you have got access too and make sure the C++ packages are included in the install.
After installing Python set an environment variable named: GYP_MSVS_VERSION and set the value to: 2015.

Now make sure everything is installed properly by running npm install from the root of the project.

Install global npm dependencies>

The project is dependent on having a few packages installed globally as well, these being gulp and jspm.
To sort this, run the following:
npm install -g gulp
npm install -g jspm

Installing Aurelia with jspm

Now we need to install the Aurelia packages, and a few others. This is done by running the following form the root of the project:
jspm install

Make sure everything installed properly

Test the major part of the toolchain by building the project. Do this with:
gulp build

Setting up the ASP.NET 5 bits

If you are new to ASP.NET 5 and haven’t got the run-time installed, get it here.

First off we need to add two files, project.json and Startup.cs.
Mine looked like the following:

{
  "version": "1.0.0-*",
  "compilationOptions": {
    "emitEntryPoint": true
  },
  "tooling": {
    "defaultNamespace": "Aurelia_Skeleton"
  },

  "dependencies": {
    "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
    "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
    "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final"
  },

  "commands": {
    "web": "Microsoft.AspNet.Server.Kestrel"
  },

  "frameworks": {
    "dnx451": { },
    "dnxcore50": { }
  },

  "exclude": [
    "node_modules"
  ],
  "publishExclude": [
    "**.user",
    "**.vspscc"
  ]
}

and

using Microsoft.AspNet.Builder;
using Microsoft.Extensions.DependencyInjection;

namespace Aurelia_Skeleton
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app)
        {
            app.UseIISPlatformHandler();            
            app.UseDefaultFiles();
            app.UseStaticFiles();
        }

        // Entry point for the application.
        public static void Main(string[] args) => Microsoft.AspNet.Hosting.WebApplication.Run<Startup>(args);
    }
}

After adding these files, go back to the command line and run the following:
dnu restore
dnu build

Given everything is installed correctly, the build should have gone ok and we can now start the web server with:
dnx web

Now everything should be installed, setup and ready to go, so just open a browser and hit http://localhost:5000 and the app should be loading!

Get the code

I forked the project and introduced my changes, you can get the code from my GitHub repository.

This was a quick setup and it’s not of production quality like the stuff from the Aurelia team, but it’s hopefully a start for those who want to play around with Aurelia on ASP.NET 5.

Happy Coding! :)

post image

Running Tasks in Visual Studio Code

Running Tasks in VS Code

Time for another Coding Quick Tip – This time a look at running Tasks in Visual Studio Code. The content is available as a video at the end of the post if that’s what you prefer.

Setup

The test setup I got going is just a project with a few TypeScript files in them, and the task I’ll be rigging is just running the TypeScript compiler to transpile the code to JavaScript.

The prerequisites is that the Node and TypeScript compiler need to be installed. When Node is installed on the system, just type npm install -g typescript in a command window to install the TypeScript compiler as a global npm package. Verify that the compiler is properly installed by typing tsc -v

I also prefer to have config file for the TypeScript compiler, this can be created easily by entering tsc --init In the tsconfig.json file that will be created, I point out the location of the code and the directory where I wish the transpiled output to be placed.

Executing Commands

To run tasks from VS Code we need a configure the Task Runner. This is done by entering the Command Palette (F1 or ctrl-shift-p), typing task and selecting Tasks: Configure Task Runner.

VS Code Configure Task Runner Visual Studio Code

Configure the Task Runner in VS Code

This will create a tasks.json file under the .vscode directory in the current folder.
In the tasks.json file, edit the top-most example and remove the args parameter, as this is not needed when we got our tsconfig file setup.

Execute the task by opening the command palette, press backspace to remove the chevron and type task. This will show a drop down with all available tasks, right now just the one we recently created – named tsc.

VS Code Executing Task Visual Studio Code

Executing a task in Visual Studio Code

Running the task will compile our TypeScript files. Task accomplished (pun intended) – let’s move on.

Using a Task Runner

What if we want to use a task runner?
We’re in luck here if we like Jake, Grunt or Gulp as VS Code supports these out of the box. For this example I’m using Gulp.

First off, remove tasks.json so that we can start fresh.
After that, create a gulpfile.js in the folder with the select tasks defined (the one I’m using is listed below).

var gulp = require('gulp'),
    ts = require('gulp-typescript'),
    merge = require('merge'),
    fs = require("fs");

var webroot = "wwwroot";

var paths = {
    npm: './node_modules/',
    lib: "./" + webroot + "/lib/",
    tsSource: './TypeScript/**/*.ts',
    tsOutput: "./" + webroot + '/scripts/',
    tsDef: "./typings/internal/"
};

var tsCompilerConfig = ts.createProject('tsconfig.json');

gulp.task('ts-compile', function () {
    var tsResult = gulp.src(paths.tsSource)
        .pipe(ts(tsCompilerConfig));

    return merge([
        tsResult.dts.pipe(gulp.dest(paths.tsDef)),
        tsResult.js.pipe(gulp.dest(paths.tsOutput))
    ]);
});

gulp.task('watch', ['ts-compile'], function () {
    gulp.watch(paths.tsSource, ['ts-compile']);
});

Note, if you by any chance actually want to use the above gulp file, you need to install gulp, gulp-typescript and merge.
npm install gulp
npm install gulp-typescript
npm install merge?

Now we’re off to actually running the task again.
Open the Command Palette and type task, then select Tasks: Configure Task Runner, as in the first example.

Given all the used packages are installed correctly, a new tasks.json file will be created and look like the following

{
    "version": "0.1.0",
    "command": "gulp",
    "isShellCommand": true,
    "args": [
        "--no-color"
    ],
    "tasks": []
} 

You can now execute your Gulp tasks just like we executed our task in the example above.

Binding a task to VS Code’s “Run Build Task”

Visual Studio code has a command named Run Build Task, with the keybinding Ctrl+Shift+B. To improve the workflow in VS Code, this is the command to bind your build tasks too.
Binding the build task to the build command is done by setting the property isBuildTask to true for a specific task in the tasks.json file.

Let’s add our build task to tasks.json and try it out, modify tasks.josn like this:

{
    "version": "0.1.0",
    "command": "gulp",
    "isShellCommand": true,
    "args": [
        "--no-color"
    ],
    "tasks": [
        {
            "taskName": "ts-compile",
            "isBuildCommand": true
        }
    ]
}

Now execute the the task by pressing Ctrl+Shift+B, watch your bound task being run and rejoice :)

That’s all for this Coding Quick Tip,
Happy Coding! :)



post image

Get Started With ASP.NET 5 & VS Code – Video

Coding Quick Tip: Get Started With ASP.NET 5 and VS Code

I have been thinking of starting a series of quick tips in video format and here is the first episode. This time just showing how to get started developing in VS Code and scaffolding out an ASP.NET 5 project using Yeoman.

This was fun but it’s my first video so it’s definately a learning experience. It seems so easy when you look at all other good YouTube videos and now seeing my own result just makes me laugh. But what better way to learn than to do it in the open, feel some preassure and also be able to get some tips and critique? :)

I know mic volume is really low, I need to fix that for my next vid. Maybe it’s even time to get a proper mic. Asking the misses for a x-mas gift just got easier I think πŸ˜€

I hope you enjoy the video even though it’s bad quality, low sound, mumbling and thought pauses. Please leave feedback if you got time!



Happy Coding! :)

post image

TypeScript Classes Part III

TypeScript Classes Part III

Welcome to this second tutorial in the series covering classes in TypeScript. The topics covered in this episode is listed below.
TypeScript Classes Tutorial How-To Inheritance Interface Abstract Class

TypeScript Classes Part I – A New Hope (For structured JavaScript)

  1. Classes
  2. Constructors
  3. Scope Modifiers
  4. Parameter Shorthand

TypeScript Classes Part II – C# Strikes Back

  1. Accessors
  2. Static Properties

TypeScript Classes Part III – Return of the Object Hierarchy

  1. Inheritance
  2. Interfaces
  3. Abstract Classes

OBS! For version disclaimer & project setup – see the bottom of the post

Object Heirarchy

In this third episode we’re entering classical OO territory. Handling classes was, except for strong typing, the big thing that made TypeScript stand out compared to JavaScript when it was released.

Now classes are in the ES6 specs and thus coming to JavaScript, landing in a browser near you soon. But classes in JavaScript have been heavily debated in the community, and are still a divider for the passionate.

All class decisions haven’t been all uncontroversial in TypeScript either, Abstract Classes was the latest discussion point when being introduced in TypeScript 1.6.

For those of us coming from a more classic OO language before heading in to the JavaScript world, TypeScript and it’s classes can definitely be a good gateway in to actually enjoying a development environment that some developers fear, just because it’s lack of strong typing and non-straightforward OO patterns :)

Inheritance

Class inheritance is denoted using the extends keyword. Just mark a class with extends and then the name of the class that should be inherited.

Notable, a class can only inherit from one base class.

Example code:

class Vehicle {
	private name: string;
	private speed: number;

	constructor(name: string, speed: number) {
		this.name = name;
		this.speed = speed;
	}

	move(distance: number): string {
		var time = distance / this.speed;
		return `${this.name} moved ${distance} kilometers in ${(time * 60).toFixed(2) } minutes`;
	}
}

Now we create a class which we wish to inherit from Vehicle and we do it using the extends keyword:

class AllTerrainVehicle extends Vehicle {
	private legs: number;

	constructor(name: string, speed: number, legs: number) {
		super(name, speed);
		this.legs = legs;
	}

	move(distance: number) {
		return super.move(distance) + ` by walking on ${this.legs} legs`;
	}
}

First thing to note is that a derived class always have to call the constructor of the base class. This is can be seen on row 5 in Example 2, and is done using super.

We can see the derived class only has one private member defined, but it actually has more state, as it has the members from the base class defined as well. And not only the members from the base class but also the methods defined.
Using methods from the base class is done with calling the method name on super. This can be seen on row 10 in Example 2, where the derived class uses a method from the base class and extends it’s functionality.

Interfaces

Interfaces are used to define contracts, telling the compiler that a class is expected to implement a set of members.

In contrast to class inheritance, a class can implement several interfaces at the same time.

In TypeScript interfaces are also used heavily to define the type structure for objects we need to work with. For ex, when retrieving data from a Web API, make sure to have an interface defined for it so it’s easier to work with in TypeScript.

Defining an interface is done with the interface keyword, let’s look at some code:

interface TroopCarrier {
	troopCapacity: number;
	medicalDroid: boolean;
	pickup(troops: number): string;
}

Here we see that any class that implements this interface must define three public members, two data members and one method. Mark that the name of the interface does not start with a capital i (I) as so often seen in other languages. If you are running a TypeScript linter it will surely complain about this, but according to Microsoft’s own guidelines, this practice is to be avoided.
Declaring that a class is adhering to a contract defined in an interface is done with the implements keyword. Let’s see an example:

class AllTerrainCarrierVehicle extends Vehicle implements TroopCarrier {
	private legs: number;
	private troopsInHold: number;

	troopCapacity: number;
	medicalDroid: boolean;

	constructor(name: string, speed: number, legs: number, troopCapacity: number, hasMedicalDroid: boolean) {
		super(name, speed);
		this.legs = legs;
		this.troopCapacity = troopCapacity;
		this.medicalDroid = hasMedicalDroid;
		this.troopsInHold = 0;
	}

	move(distance: number) {
		return super.move(distance) + ` by walking on ${this.legs} legs`;
	}

	pickup(troops: number): string {
		if (this.troopsInHold + troops > this.troopCapacity) {
			return "Can't pick up that many troops";
		} else {
			this.troopsInHold += troops;
			return "Troops picked up";
		}
	}
}

Notable is that interfaces only declare member signatures, ie. it’s not possible to have an interface specify any functionality. The TroopCarrier interface can thus only specify that the pickup method needs to be implemented and how the call signature for the method is supposed to look, but it can’t define any functionality for implementing classes to use.

Abstract Classes

Much alike Interfaces are Abstract Classes. In early TypeScript this construct wasn’t in the language spec, but since TypeScript 1.6 we now have access to Abstract Classes!

An abstract class is a class that can’t be used to instantiate any objects. So in that aspect it is much like an interface. However, an abstract class can define functionality that can be used from deriving classes.

Declaring an abstract class is done using the abstract keyword. Deriving from an abstract class is done with the extends keyword, just as inheritance from regular classes. Let’s look at an example:

abstract class RepulsorliftVehicle {
	private maxSpeed: number;
	private passengers: number;
	private armaments: string;

	constructor(maxSpeed: number, passengers: number, armaments?: string) {
		this.maxSpeed = maxSpeed;
		this.passengers = passengers;
		this.armaments = armaments;
	}

	abstract pickUpPassengers(noOfPassengers: number): string;

	fire(): string {
		if (!!this.armaments) {
			return `${this.armaments} fired!`;
		} else {
			return "No armaments to fire!";
		}
	}
}

Now if we try to new up an instance of RepulsorliftVehicle it won’t work. If we’re developing in an environment that supports TypeScript, we will get a warning saying the same as the compiler will. And running the compiler will yield the message:
TS2511: Cannot create an instance of the abstract class 'RepulsorliftVehicle'.
So what kind of JavaScript sorcery is this producing to employ such trickery? Actually nothing special, it’s just tooling working for us here :) If we look at the JavaScript produced it is just the same as all transpiled TypeScript classes.

Next up, inheriting from an abstract class, an example:

class SpeederBike extends RepulsorliftVehicle {
	constructor(maxSpeed: number, passengers: number, armaments: string) {
		super(maxSpeed, passengers, armaments);
	}

	pickUpPassengers(noOfPassengers: number): string {
		if (noOfPassengers > this.passengers) {
			return "Can't fit that many passengers";
		} else {
			return "Passenger get's on and holds on for dear life";
		}
	}
}

In the derived class we need to implement the methods declared as abstract in the base class, or the code won’t compile. Let’s test the SpeederBike and see what it can do:

var model74Z: SpeederBike = new SpeederBike(350, 1, "Ax-20 blaster cannon");
model74Z.pickUpPassengers(3); //returns Can't fit that many passengers
model74Z.pickUpPassengers(1); //returns Passenger get's on and holds on for dear life
model74Z.fire(); //returns Ax-20 blaster cannon fired!

Using the pickUpPassengers method that the base class had defined as abstract is done just as per usual. We also have access to the base class non abstract methods, calling fire on SpeederBike is ok.

So, that’s the strength of abstract classes demonstrated, the possibility to provide partial implementation of the behavior via the base class.

Conclusion

So this is the last part of the series detailing the workings of TypeScript classes. I hope that you have found it easy to follow along and get into the TypeScript way of handling OO. Good luck with your adventures in TypeScript and please leave a comment below, telling me how you TypeScript is workign out for you so far :)

Version Disclaimer & Project Setup

The code for this post was written using Visual Studio Code, ASP.NET 5 (dnvm) with runtime rc-1. Node packages TypeScript v1.7.3 and gulp-typescript v2.9.2 were used. The project was setup to compile the TypeScript files with gulp. The code was tested in Microsoft Edge.

If you want to replicate this setup, just download the code from my GitHub repository here. If you want to read more about how to setup a TypeScript project in VS Code for ASP.NET 5, read this post.

Just starting out? Developing in TypeScript

Just a quick tip if you are new to TypeScript and need help getting started. I recommend either using Visual Studio Code or Visual Studio Community Edition. Both are free and excellent development tools. Which one you should select depends on your preferences.

VS Code is more of an editor, fast and light weight, but it won’t really hold your hand during learning. Now recently launched with extension support, with many great extensions already released and the Community working hard on many more :)
Download Visual Studio Code.

Visual Studio is a full fledged IDE, it has pretty much everything you need to develop web, Windows applications, apps, etc. And if the functionality isn’t available out of the box, there’s a great extensibility API, enabling loads of excellent third party extensions, most of them free.
Download Visual Studio Community Edition.

More TypeScript posts for the curious

Tutorial on TypeScript Functions: TypeScript Functions

Setting up an Aurelia project in Visual Studio Code with TypeScript: Aurelia and TypeScript from VS Code

Tutorial for setting up a TypeScript – ASP.NET 5 app in VS2015: Getting started: TypeScript 1.5 in Visual Studio 2015

Tutorial for setting up a TypeScript – ASP.NET 5 app in Visual Studio Code: How-to: TypeScript in Visual Studio Code

Setup of a TypeScript – MVC 6 app that uses RequireJS in VS2015: Setting up a TypeScript – RequireJS – Gulp – MVC 6 Web Project in Visual Studio 2015 RC

Happy coding! :)

post image

Aurelia, Visual Studio Code and TypeScript

Aurelia with TypeScript in Visual Studio Code on ASP.NET 5

This article covers setting up an Aurelia project in Visual Studio Code running ASP.NET 5 to serve the pages and using TypeScript, instead of the default Babel es6 transpiler.
There are a few examples on the web on how to do this, but none felt like a smooth way of doing it in Visual Studio Code. So here is a shot at making it as easy as possible to get started with Aurelia in VS Code using TypeScript!

Versions Disclaimer

Check at the bottom of the article for a lengthy description of versions for all frameworks/tools used during the writing and testing of this post.

Prerequisites

There are a few things that are assumed, in this article, that you have installed on your system already.
These are: Visual Studio Code, DNVM/DNX (ASP.NET 5), Yeoman with the ASP.NET generator and Node.
If you want to follow along with the code examples, you should install them now if you haven’t already got them installed.

Creating a new ASP.NET 5 project

Open your command prompt of choice and position in a directory where you want to create the project.
Create a new project by entering yo and then selecting the Aspnet generator. When given the choice, select Empty Application and name your new app.
This will create a fairly empty ASP.NET 5 project for us that we can use.
First of, position in the directory that just got created for your app via the command prompt.

Installing jspm

So, what is this “jspm”? Jspm is the module loader that Aurelia uses. Read more about it here.
If you haven’t got jspm installed on your dev machine, it’s time to do that.
Installing jspm is done with npm from your command prompt, to install it globally on your machine, enter the following:
npm install jspm -g

Configure jspm

After installing it, it’s time to setup jspm.
Positioned in the root folder of the project, type:
jspm init
A number of questions will be asked now, answer according to the examples below. The questions with nothing written after them above is using the default, thus just hit return to go to the next one.

  1. Package.json file does not exist, create it? [yes]:
  2. Would you like jspm to prefix the jspm package.json properties under jspm? [yes]:
  3. Enter server baseURL (public folder path) [./]:wwwroot
  4. Enter jspm packages folder [wwwroot\jspm_packages]:
  5. Enter config file path [wwwroot\config.js]:
  6. Configuration file wwwroot\config.js doesn’t exist, create it? [yes]:
  7. Enter client baseURL (public folder URL) [/]:
  8. Do you wish to use a transpiler? [yes]:no

Regarding the choice to NOT use a transpiler and set it up here I’ll delve deeper in to that at the end of the article.

Setup ASP.NET 5

Now it’s time to start using Code :)
Open VS Code by typing “code .” in the prompt.
Open the project.json file and add a reference under to dependencies section to:
"Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final"
Now edit the Startup.cs file and modify the Configure method like this:

        public void Configure(IApplicationBuilder app)
        {
            app.UseIISPlatformHandler();
            app.UseStaticFiles();
        }

This will enable our ASP.NET server to serve static files.

Now, add a new html page to the wwwroot folder, name it index.html:

<!DOCTYPE html>
<html>
	<head>
		<title>Aurelia + TypeScript + ASP.NET 5</title>
	</head>
	<body aurelia-app>
		<script src="jspm_packages/system.js"></script>
		<script src="config.js"></script>
		<h1>Hello World!</h1>
	</body>
</html>

Now go to the command line, position in the root of the project and first do a package restore (if you haven’t already done that from within VS Code) then start up ASP.NET 5 with:
dnu restore
dnx web

Open a browser and enter
http://localhost:5000/index.html
You should now be served with a page having only a heading saying: Hello World!
If everything works so far, it’s time to get on with the fun stuff πŸ˜€

Installing Aurelia

Now we need to install Aurelia and Corejs. In the command window, install the needed Aurelia bits with jspm by entering:
jspm install aurelia-framework
jspm install aurelia-bootstrapper
jspm install core-js

After a short while you’ll hopefully see an Install complete message (if not, a tip can be to check your GitHub download rate).

Setting up TypeScript compilation with Gulp

First we need to install a couple of npm packages. Open the package.json file in the root of the project. We need to add references to Gulp, TypeScript, Gulp-TypeScript and Merge. Edit the package.json like this:

{
  "version": "1.0.0",
  "name": "Aurelia_HelloWorld",
  "private": true,
  "devDependencies": {
    "typescript": "^1.6.2",
    "gulp": "^3.9.0",
    "gulp-typescript": "^2.9.2",
    "merge": "^1.2.0"
  },
  "jspm": {
    "directories": {
      "baseURL": "wwwroot"
    },
    "dependencies": {
      "aurelia-framework": "npm:aurelia-framework@^1.0.0-beta.1.0.2"
    }
  }
}

Now we a config file to tell the TypeScript compiler how to behave, and a file describing the Gulp tasks. But first, add a file in the root and name it tsconfig.json, this file details the behavior of the TypeScript compiler:

{
	"compilerOptions": {
		"emitDecoratorMetadata": true,
		"experimentalDecorators": true,
		"noImplicitAny": false,
		"noEmitOnError": true,
		"removeComments": true,
		"noExternalResolve": false,
		"declarationFiles": true,
		"target": "es5",
		"module": "amd",
		"sourceMap": true
	}
}

Now it’s time to define our Gulp tasks, create a new file in the project root, name it gulpfile.js:

var gulp = require('gulp'),
    ts = require('gulp-typescript'),
    merge = require('merge');

var webroot = "wwwroot";
    
var paths = {
    tsSource: './AureliaLogic/**/*.ts',
    tsOutput: "./" + webroot,
    tsDef: "./typings/"
};

var tsCompilerConfig = ts.createProject('tsconfig.json');

gulp.task('ts-compile', function () {
    var tsResult = gulp.src(paths.tsSource)
        .pipe(ts(tsCompilerConfig));

    return merge([
        tsResult.dts.pipe(gulp.dest(paths.tsDef)),
        tsResult.js.pipe(gulp.dest(paths.tsOutput))
    ]);
});

gulp.task('watch', ['ts-compile'], function () {
    gulp.watch(paths.tsSource, ['ts-compile']);
});

This will create a ts-compile and a watch task for us. Trying to run the compile task from VS Code (F1 – BackSpace – task ts-compile) will result in the following:
Running gulp --tasks-simple didn't list any tasks. Did you run npm install?
Run a Gulp task from Visual Studio Code vscode aurelia
So from the command window, in the root of the project, type:
npm install
After the installation of the packages are done, test the compile task again, either by staying in the command prompt and typing gulp ts-compile or by heading back to VS Code and running the task from there. If everything was installed and setup correctly the TypeScript compile will finish a compilation and report no errors.

Converting our app to an Aurelia app

Now we need to edit our index.html file again, and load Aurelia! :)
Edit index.html and add a new script block under the other scripts that looks like this:

<script>
	System.import("aurelia-bootstrapper");
</script>

By default, Aurelia will look for a file named app.js to start up from, so let’s make sure we have one!
Add a folder in the root, name it AureliaLogic. Now add a TypeScript file in the AureliaLogic folder, name it app.ts and edit it like this:

import { AppRouter } from 'aurelia-router';

export class App {
	message: string;

	constructor(router: any) {
		this.message = "Hello from me!";
	}
}  

The app.js file needs a template to work with as well, add a file named app.html in the wwwroot folder:

<template>
	<h1>Our first data-bound message</h1>
	<div>${message}</div>
</template>

Now we need to compile our typescript to emit the app.js file that Aurelia will look for. Do that using the Gulp ts-compile task we set up earlier.
However, the result will be a compilation error:
AureliaLogic\app.ts(1,27): error TS2307: Cannot find module 'aurelia-router'.
One more thing to fix :)

Setting up type definitions for TypeScript

The reason that the TypeScript compiler fails is that it can’t find the aurelia-router type. So let’s help the compiler along the way!
Aurelia has type definitions delivered with the code, we just need to be able to get to them in an easy way. There are many ways to solve this but my proposal is the folowing:

  1. Install TSD – TSD is a package manager for TypeScript type files
  2. Copy Aurelia’s type definition files by hand or create a Gulp task to copy definition files from the Aurelia module folders
  3. Enable TSD to find all Aurelia definitions copied to the typings folder and bundle them

The above setup will enable us to only reference one single definition file form our TypeScript code files, and still be able to have all references available for all added Aurelia modules.

Install TSD

TSD is easily installed with npm, so just head over to the command prompt again, position in the root of the project and type:
npm install tsd
After installation we need to configure and setup tsd by typing:
tsd init
This will create a folder in the root of the project called typings, here we will put all our typing files (*.d.ts).

Create a Gulp task to copy d.ts files

We need another npm module here, so in package.json we need to add a reference to flatten under devDependencies:
"gulp-flatten": "^0.2.0"
Then add a copy task to to the gulpfile:

var gulp = require('gulp'),
    ts = require('gulp-typescript'),
    merge = require('merge'),
    flatten = require('gulp-flatten');

var webroot = "wwwroot";

var paths = {
    tsSource: './AureliaLogic/**/*.ts',
    tsOutput: "./" + webroot,
    tsDef: "./typings/",
    importedTypings: "./" + webroot + "/jspm_packages/**/*.d.ts"
};

Then define a new task at the bottom of the gulpfile:

gulp.task('copy-defs', function () {
    gulp.src(paths.importedTypings)
        .pipe(flatten())
        .pipe(gulp.dest(paths.tsDef + "/jspmImports/"));
});

Now install the new npm package by running:
npm install
And then run the copy script. If you don’t want to run the Gulp tasks from VS Code, it’s possible to run them from the console as well. Just position in the root of the project and type:
gulp copy-defs
This then executes the new copy task.
The last thing to fix regarding typing is to manually install the type definitions for core-js, do this by typing:
tsd install core-js

Now we need to get all our newly copied type definitions into our tsd file. Console to the resque as usual and type:
tsd rebundle
If all has gone well a load of d.ts files will be added form our new jspmImports folder and the type def for core-js will be there as well.

Add type references to our TypeScript file

Now we can add a reference to the tsd file in our app.ts file, add the following at the top of the file

/// <reference path="../typings/tsd.d.ts" />

Now run the TypeScript compile task again!
End result after setting up Aurelia with TypeScript using VS Code and ASP.NET 5 vscode
Given that everything has worked through the previous steps it’s now time to test the result in the browser by starting the ASP.NET 5 web server again if it’s off by running:
dnx web
Then open a browser and locate localhost:5000/index.html.
At first we will be seeing a classical Hello World, this will later be replaced by another message, as soon as Aurelia loads and takes over execution. Success!

About choosing no transpiler

So why not choosing a transpiler in the initial jspm setup?
Mostly because when starting out it’s nice to have more control with running the TypeScript compilation with Gulp. And since Gulp was used for a few other tasks it’s neat to use. One thing I never demoed in the post was the use of the watch-task. This is a great task when everything is setup correctly, as it will monitor your TypeScript files and compile them as soon as a change is saved in them, makes for a great quick feedback loop!

When choosing to setup TypeScript as compiler form jspm, it’s not necessary to compile the TypeScript files at all. This will be handled by a very cool plugin that will compile the TypeScript in the browser, but this also means you have to reload and watch the console for any compilation errors when working with it.

Version Disclaimer

At the time of writing this blog post, the following versions of tools and frameworks were used:
Visual Studio Code v0.10.2
TypeScript v1.6.2
Aurelia 1.0.0-beta.1
tsd v4
Gulp v3.9.0
Gulp-typescript v2.9.2
Merge v1.2.0
jspm v0.16.15
node v0.12.2
dnvm vrc-1

The code was tested in Microsoft Edge.

More TypeScript posts for the curious

Tutorial on TypeScript Functions: TypeScript Functions

Tutorial on TypeScript Classes: TypeScript Classes

Tutorial for setting up a TypeScript – ASP.NET 5 app in VS2015: Getting started: TypeScript 1.5 in Visual Studio 2015

Tutorial for setting up a TypeScript – ASP.NET 5 app in Visual Studio Code: How-to: TypeScript in Visual Studio Code

Setup of a TypeScript – MVC 6 app that uses RequireJS in VS2015: Setting up a TypeScript – RequireJS – Gulp – MVC 6 Web Project in Visual Studio 2015 RC

Happy coding! :)

post image

VS Code, Debugger For Chrome and ASP.NET 5

Visual Studio Code, Debugger For Chrome and ASP.NET 5

During the Connect(); //2015 event held by Microsoft recently, Microsoft made Visual Studio Code open source, so yay! This was something the community had wanted for a long time.

Visual Studio Code Extensions is Awesomesauce TypeScript Tutorial How-To

But I think the thing that exited VS Code users the most was the announcement that they now supports extensions! This in my mind took VS Code from “a great editor” to “Pure AwesomeSauce”.

The Debugger For Chrome Extension

I wanted to test the Debugger for Chrome extension when playing around with some TypeScript dev in an ASP.NET 5 Project. But I ran in to problems.

At first I tried getting the extension to start Chrome and connect to my localhost, using the standard section recommended in launch.json, like this:

{
	"name": "Launch localhost with sourcemaps",
	"type": "chrome",
	"request": "launch",
	"url": "http://localhost:5000/index.html"
}

However that didn’t work as the extension could not find my default Chrome installation and gave me the error:
[webkit-debug-adapter] Can't find Chrome - install it or set the "runtimeExecutable" field in the launch config.

So I set the runtimeExecutable to point at my Chrome installation and also added the runtimeArgs to make Chrome start with the remote debugging port set correctly.

This worked and I could fire up the extension by pressing F5. But to my dismay, no breakpoints were hit, however the Console worked and logs were piped over to VS Code.

After lurking the extensions GitHub repo it seemed more people were having the same problem. Seems setting the root for content delivery was key!

{
	"name": "Launch",
	"type": "chrome",
	"request": "launch",
	"url": "http://localhost:5000/index.html",
	"runtimeExecutable": "C:/Users/_usr_/AppData/Local/Google/Chrome/Application/chrome.exe",
	"runtimeArgs": [
		"--remote-debugging-port=9222"
	],
	"cwd": ".\\wwwroot\\"
}

(If you are planning to use the above config, replace the _usr_ part of the path to your correct user!)

After setting the root path to the webroot, the extension worked like a charm, but the extension has a few quirks to be aware of:

  1. When starting debugging with F5 from VS Code, Chrome starts but won’t hit any breakpoints. You need to refresh the page in Chrome to hit your breakpoints!
  2. If opening several tabs when debugging (possible if more tabs are open before starting debugging), the most recent tab opened in Chrome most likely won’t be the one connected to Visual Studio Code, but the first one is!

In Closing

If you haven’t tested Visual Studio Code yet, download it and give it a try. It’s a lean, quick install!

Check out all the new cool VS Code extensions in the Visual Studio Marketplace!

Watch all the announcements and videos from Connect(); //2015 on channel 9.

Interested in getting started with ASP.NET 5 and TypeScript in Visual Studio code, check out this post.

Happy coding! :)

post image

TypeScript Classes Part II

TypeScript Classes Part II

Welcome to this second tutorial in the series covering classes in TypeScript. The topics covered in this episode is listed below.

TypeScript Classes Tutorial for Beginners How-To Accessor Static

TypeScript Classes Part I – A New Hope (For structured JavaScript)

  1. Classes
  2. Constructors
  3. Scope Modifiers
  4. Parameter Shorthand

TypeScript Classes Part II – C# Strikes Back

  1. Accessors
  2. Static Properties

TypeScript Classes Part III – Return of the Object Hierarchy

  1. Inheritance
  2. Interfaces
  3. Abstract Classes

Disclaimer

The code for this post was written using Visual Studio Code, ASP.NET 5 (dnvm) runtime was rc-1. Node packages TypeScript v1.6.2 and gulp-typescript v2.9.2 were used. The project was setup to compile the TypeScript files with gulp. The code was tested in Microsoft Edge.

If you want to replicate this setup, just download the code from my GitHub repository, link is at the end of the post. If you want to read more about how to setup a TypeScript project in VS Code for ASP.NET 5, read this post.

Developing in TypeScript

Before we start, just a quick tip if you are new to TypeScript and need help getting started. I recommend either using Visual Studio Code or Visual Studio Community Edition. Both are free and excellent development tools. Which one you should select depends on your preferences.

VS Code is more of an editor, fast and light weight, but it won’t really hold your hand during learning. Now recently launched with extension support, with many great extensions already released and the Community working hard on many more :)
Download Visual Studio Code.

Visual Studio is a full fledged IDE, it has pretty much everything you need to develop web, Windows applications, apps, etc. And if the functionality isn’t available out of the box, there’s a great extensibility API, enabling loads of excellent third party extensions, most of them free.
Download Visual Studio Community Edition.

Accessors

Like most programming languages, TypeScript has getter and setter methods, also known as Accessors. These accessors are functions enabling you more control over access to an objects members.

Accessor Syntax

The keywords used are get and set, followed by the accessor name. The setter takes a parameter of a type and the getter has no parameter, just a return type. Accessors can be used from within other accessors.

Scope modifiers are optional, omitting them means that the accessors are public. One gotcha is that accessors for a member name must have the same scope, this means you can’t for example have a public get and private set.

Let’s look at an example:

class Droid {
	private holoMessage: string;

	public set holographicMessage(message: string) {
		this.holoMessage = message;
	}

	public get holographicMessage(): string {
		return this.holoMessage;
	}
}

Using Accessors

The functionality of the code in Example 1 doesn’t differ in reality from just having a public member named holoMessage on the class. But if there’s anything we know it’s that holographic Messages should only be displayed for the person they are intended for. Let’s expand the example a bit before looking at using them from a test:

class Droid {
	private holoMessage: string;
	private receiver: string;

	public set holographicMessage(message: string) {
		this.holoMessage = message;
	}

	public get holographicMessage(): string {
		if (!this.receiver) {
			return "Invalid user!";
		}

		if (this.receiver === "Obi-Wan Kenobi") {
			return this.holoMessage;
		}
	}

	public enterPassCode(code: number): void {
		if (code === 1234) {
			this.receiver = "Obi-Wan Kenobi";
		}
	}
}

Now we got some logic running in our get accessor and we can see the syntax of how to use getters and setters. Any one is allowed to set a new holographic message, but only Obi-Wan has the secret pin-code to make the droid play back the holographic message. Let’s run the code with a quick test:

	var droid = new Droid();
	droid.holographicMessage = "Help me Obi-Wan Kenobi, you are my only hope!";

	console.log(droid.holographicMessage);	// "Invalid user!"

	droid.enterPassCode(42);
	console.log(droid.holographicMessage);	// "Invalid user!"

	droid.enterPassCode(1234);
	console.log(droid.holographicMessage);	// "Help me Obi Wan Kenobi, you are my only hope!"

Row 4 and 7 will render “Invalid user!”, because accessing the getter without the correct code won’t work.
However, row 10 will render the correct message after receiving an acknowledged passcode.

Static Properties

Class members declared using the static keyword is going to be members of the constructor function. This means you are able to call them without instantiating a class first. Instance members on the other hand can then not be called from static members.

Static members can be declared using all scope modifiers, public, private and protected.

Let’s look at an example:

class DeathStar {
	static fireSuperLaser(): string {
		return "Wait, we're powering up...";
	}
}

Calling the method is then done without instantiating the class, like this:

console.log(DeathStar.fireSuperLaser());

This is what the transpiled DeathStar class looks like in ES5:

var DeathStar = (function () {
    function DeathStar() {
    }
    DeathStar.fireSuperLaser = function () {
        return "Wait, we're powering up...";
    };
    return DeathStar;
})();

Here we can see the fireSuperLaser function being added to the constructor function and not to the prototype as instance members are.

Get The Code!

All the code from this post is available on my GitHub account in the repository called: TypeScript_Classes_II.

More TypeScript projects

Tutorial on TypeScript Functions: TypeScript Functions

Setting up an Aurelia project in Visual Studio Code with TypeScript: Aurelia and TypeScript from VS Code

Tutorial for setting up a TypeScript – MVC 6 app in VS2015: Getting started: TypeScript 1.5 in Visual Studio 2015

Tutorial for setting up a TypeScript – MVC 6 app in VS Code: Getting started: TypeScript 1.5 in Visual Studio Code

If you are interested in a more advanced setup of a TypeScript – MVC 6 app that uses RequireJS in VS2015, check out this post: Setting up a TypeScript – RequireJS – Gulp – MVC 6 Web Project in Visual Studio 2015 RC

Happy coding! :)