Getting Started with ASP NET Core 1 and Angular 2 in Visual Studio 2015

The goal of this post is to set up a Visual Studio 2015 project with ASP NET Core 1 and Angular 2 Typescript that can be used as a template for all my projects.

ASP NET Core1 Logo         angular2Logo

The whole code is available on GitHub: https://github.com/softwarejc/angular2-aspmvc-core1-getting-started

We will use npm (Node Package Manager) to add our dependencies and we will configure the typescript transpiler integrated in Visual Studio. We will also configure a gulp task to bundle our javascript an css dependencies.

Content

  • Introduction
  • Install Pre-requisites
  • Create an empty ASP Core 1 project
  • Auto transpile Typescript after save
  • Add Angular 2 with npm
  • Set up gulp task to bundle dependencies

Introduction

The former ASP.NET 5 was renamed to .NET Core 1. It is a modular Microsoft runtime library implementation that includes a subset of the .NET Framework.

.NET Core 1 was written from scratch. It has a lot of advantages, for example it is lighter, open-source and multi-platform: Mac, Linux and Windows.

Although the version 1 is in Release Candidate there are some ASP.NET 4.6 features missing, like SignalR.

It is up to you to choose a mature Framework like ASP.NET 4.6 or a modern one like ASP.NET Core 1… you can read more about it in this post by Scott Hanselman. I copied the following diagram from that post :-).

ASPNET Core 1

Install Pre-requisites

There are some problems in Windows using npm version 2. It nest dependencies and ends up having too long paths for Windows. Let’s start updating npm to version 3 and configuring Visual Studio to use it.

The first thing that we should do is to install Python version 2.7.X and NodeJS version 4.2.X. Remember the path where you install NodeJS, we will need it later.

Now open a command line and update npm:

npm install npm -g

Check your npm version:

npm -v

The version should be higher than 3.X.X.

Open visual studio and add the path where NodeJS is installed as the first path to look for external tools (at the top). The next time that Visual Studio has to restore a node package it will start looking for nodejs.exe in that path. The version we just installed will be found and used.

Configure VS to use npm 3

Create an empty ASP NET Core 1 project

Let’s create our project and configure a very simple server-side code.

In Visual Studio 2015 Update 1 ASP NET Core 1 is still called ASP NET 5. Create a new project and select the WebAPI template. Our project will have a SPA that will call a WebAPI controller to get a message.

Create ASPNET 5 Project

 

Delete the Project_Readme.html and update the values controller with this simple WebAPI controller that returns a hello message and the server UTC Time:

using System;
using Microsoft.AspNet.Mvc;
namespace GettingStarted_ASPNetCore1_Angular2.Controllers
{
[Route("api/[controller]")]
public class HelloController : Controller
{
[HttpGet]
public IActionResult Get(string name)
{
var time = DateTime.UtcNow.ToString("hh:mm:ss");
var response = new
{
message = $"{time} - Hello {name}, server-side speaking!"
};
return new ObjectResult(response);
}
}
}

We will call this method later from angular to check that the communication between our SPA and the server works. For now we can call it from the browser to check it. Run the application and write something like this in your browser using your configured port:

http://localhost:10137/api/hello

You should see something like:

apiTest

You can also pass your name to check that the server receive your parameters:

http://localhost:10137/api/hello?name=JuanCarlos

The file Startup.cs contains the configuration of the middleware. We will see in a future post how it works and how to configure it to use features like authentication. The default configuration when you select a WebAPI project template is ok for us.

Auto transpile Typescript after save

We can tell Visual Studio to auto transpile always that we edit and save a typescript file enabling:

“Automatically compile TypeScript files which are not part of a project”
ts Compile on Save

Our files will be part of the project… but this is an easy way to make Visual Studio auto transpile. Running typescript compiler in watch mode is an alternative… but I like this solution because I have everything integrated in Visual Studio.

If you know a better way please leave me a comment. 🙂

We will have a tsconfig.json file on the project root of our project to configure typescript, Visual Studio will use that file and not the settings that we configure in Options:

{
"compilerOptions": {
"target": "es5",
"module": "system",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true
},
"exclude": [
"node_modules"
]
}
view raw tsconfig.json hosted with ❤ by GitHub

Add Angular 2 with npm

The application that we will use as an example will be a simple application that call the server to get a message and will display using Angular 2.

Let’s add Angular 2 and other dependencies to npm, we need a file called “package.json” on the root of our project:

{
"name": "aspnetcore1-angular2-gettingstarted",
"version": "1.0.0",
"scripts": {
"gulp": "gulp"
},
"license": "ISC",
"dependencies": {
"jquery": "2.2.0",
"bootstrap": "3.3.6",
"systemjs": "0.19.17",
"rxjs": "5.0.0-beta.0",
"angular2": "2.0.0-beta.0",
"es6-shim": "^0.33.3"
},
"devDependencies": {
"del": "2.2.0",
"gulp": "3.9.0",
"gulp-concat": "2.6.0",
"gulp-rename": "1.2.2",
"gulp-uglify": "1.5.1",
"gulp-concat-css": "2.2.0"
}
}
view raw package.json hosted with ❤ by GitHub

Save the file and Visual Studio will create node_modules folder and download all dependencies for you.

It is out of the scope of this post to explain how Angular 2 works you can read more about it here. But basically we define a component that we can use in our index.

<hello></hello>

This component is a html view that has bindings to its code behind or “view-model”.

hello.view.html

<div style="background: ghostwhite">
<h3>
<label>Name:</label>
<!--binding to component field-->
<input type="text" [(ngModel)]="name" placeholder="Enter a name here">
<!--binding click event to component method-->
<button class="btn btn-primary col-md-2" (click)="sayHello()">
Hello!
</button>
</h3>
<!-- conditionally display `message` -->
<h4 [hidden]="!message">{{message}}</h4>
</div>
view raw hello.view.html hosted with ❤ by GitHub

hello.component.ts

import {Component} from 'angular2/core';
import {OnInit} from 'angular2/core';
import {HelloService} from './hello.service';
@Component({
// Declare the tag name in index.html to where the component attaches
selector: 'hello',
// Location of the template for this component
templateUrl: 'views/hello.view.html',
// Dependencies
providers: [HelloService]
})
// Component controller
export class Hello implements OnInit {
public message: string;
public name: string;
constructor(private _helloService: HelloService) {
}
ngOnInit() {
this.name = "";
this.message = "";
}
sayHello() {
// Use hello service to call the API and bind result
this._helloService.sayHello(this.name).subscribe(response => {
this.message = response;
});
}
}

The hello.component uses the service hello.service that makes REST calls to the server and returns Observable<T>.

hello.service.ts

import {Http} from 'angular2/http';
import {Injectable} from 'angular2/core';
import {Observable} from "rxjs";
@Injectable()
export class HelloService {
private _sayHelloServiceUrl: String = '/api/hello/';
constructor(private http: Http) { }
public sayHello(name: string): Observable<string> {
var url = `${this._sayHelloServiceUrl}?name=${name}`;
return this.http.get(url).map(res => res.json().message);
}
}

We need to “start” / “bootstrap” our application. We will use System.JS to do that. This is this index.html where we “start” our Angular 2 app:

index.html

<!DOCTYPE html>
<html>
<head>
<title>Getting started with ASPNET Core 1 and Angular 2</title>
<!--Styles bundle-->
<link href="css/styles.css" rel="stylesheet" />
</head>
<body>
<header>
<div class="container">
<h1>Getting started with ASPNET Core 1 and Angular 2</h1>
<h3>wwww.softwarejuancarlos.com</h3>
</div>
</header>
<script src="https://gist.github.com/softwarejc/f5cc7ed938f12378f902.js"></script>
<!--Use angular "hello" component-->
<div class="container">
<hello>Loading...</hello>
</div>
<!--Dependencies bundle-->
<script src="scripts/deps.min.js"></script>
<script>
// Load all app js files
System.config({
"transpiler": false,
"packages": {
"app": {defaultExtension: 'js'}
}
});
// Run app
System.import('./app/bootstrap').then(null, console.error.bind(console));
</script>
</body>
</html>
view raw index.html hosted with ❤ by GitHub

This is the piece of code of index.html that bootstrap our application:

System.import(‘./app/bootstrap’).then(null, console.error.bind(console));

And this is our bootstrap.ts:

import {bootstrap} from 'angular2/platform/browser'
import {HTTP_PROVIDERS} from 'angular2/http';
import {Hello} from './hello/hello.component';
import 'rxjs/Rx'
// Bootstrap Angular2
bootstrap(Hello, [HTTP_PROVIDERS]).then(
success => console.log('app bootstrapped...'),
error => console.log(error)
);
view raw bootstrap.ts hosted with ❤ by GitHub

Set up gulp task to bundle dependencies

Our index.html only references a style.css and a deps.js file. Those files are a bundle with all our dependencies. To create that bundle we will use gulp. We need this gulpfile.js on the root of our project:

/// <binding Clean='clean, bundle' />
var gulp = require('gulp');
var del = require('del');
var concat = require("gulp-concat");
var rename = require("gulp-rename");
var uglify = require("gulp-uglify");
var concatCss = require("gulp-concat-css");
var config = {
scriptsPath: "./wwwroot/scripts/",
cssPath: "./wwwroot/css/",
depsFiles: [
"./node_modules/systemjs/dist/system.src.js",
"./node_modules/es6-shim/es6-shim.js",
"./node_modules/rxjs/bundles/Rx.js",
"./node_modules/angular2/bundles/angular2.dev.js",
"./node_modules/angular2/bundles/http.js",
"./node_modules/angular2/bundles/angular2-polyfills.js"
],
cssFiles: [
"./node_modules/bootstrap/dist/css/bootstrap.min.css"
]
};
// Bundle js and css
gulp.task('bundle', ['bundle:js', 'bundle:css']);
// Bundle js files
gulp.task('bundle:js', function () {
return gulp.src(config.depsFiles)
.pipe(concat("deps.js"))
.pipe(gulp.dest(config.scriptsPath))
.pipe(rename("deps.min.js"))
.pipe(uglify())
.pipe(gulp.dest(config.scriptsPath));
});
// Bundle css files
gulp.task('bundle:css', function () {
return gulp.src(config.cssFiles)
.pipe(concatCss("styles.css"))
.pipe(gulp.dest(config.cssPath));
});
// Clean up copied scripts and generated js files
gulp.task("clean", function () {
return del([
config.scriptsPath,
config.cssPath
]);
});
// The default task (called when you run `gulp` from cli)
gulp.task("default", ["bundle"]);
view raw gulpfile.js hosted with ❤ by GitHub

We want to create our bundles automatically when we rebuild or clean the project (not in every build).

Open Task Runner Explorer and bind the clean and bundle tasks to the “Clean” Visual Studio event:

GulpBinding

This will trigger our tasks always that we clean or rebuild our solution. You can also add the bundle task to the “Before Build” event… but it can takes 8-10 seconds and normally the dependencies are not changing in every build.

We have a pre-configured project that hopefully will save us some time in the future!

If you know how to make it better please leave me a comment!

Have fun with ASP.NET Core and Angular 2!

Swift 2 examples – #12 Extensions. Show Loading Indicators and Alerts

This post is part of my collection: Swift 2 – For Beginners.

Swift extensions add new functionality to an existing class, structure, enumeration, or protocol type.

In this example we will see how to write a UIViewController extension to show loading indicators and alerts.

To add a class extensions we have to write something like:

extension UIViewController {
// write your extensions here
}

Show a loading indicator

Our first extension method will be a method that should show a loading indicator and disable the application so that the user cannot interact with it. To help the user understand that the application is disabled it should be grayed out.

To use this method we don’t need any parameter but we need a reference to the created indicator to hide it later:

var spinner = self.showModalSpinner()

To do this we can use the class UIActivityIndicatorView.

/**
Shows a loading indicator and disables user interaction with the app until it is hidden
*/
func showModalSpinner() ->UIActivityIndicatorView{

// user cannot interact with the app while the spinner is visible
UIApplication.sharedApplication().beginIgnoringInteractionEvents()

var indicator = UIActivityIndicatorView()

indicator = UIActivityIndicatorView(frame: self.view.frame)
indicator.center = self.view.center
indicator.backgroundColor = UIColor(white: 0.0, alpha: 0.5)
indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
indicator.hidesWhenStopped = true
indicator.startAnimating()

self.view.addSubview(indicator)

return indicator
}

Now we need a method to hide the spinner when our task was completed:

self.hideModalSpinner(self.spinnerView)
/**
Hides the loading indicator and enables user interaction with the app
*/
func hideModalSpinner(indicator: UIActivityIndicatorView){

indicator.stopAnimating()
indicator.hidden = true

// user can interact again with the app
UIApplication.sharedApplication().endIgnoringInteractionEvents()
}

If we put these two methods within a UIViewController extension we can use them like a normal method of the class.

Show an alert

Let’s add now a method to our extension to show an alert to the user, it should have an ‘ok’ button that will close the alert when the user taps it.

alert ios

I would like to have a very simple method that has only two parameters to indicate the title and message:

self.showAlert("Error", message: "Invalid user name / password.")

We can use the class UIAlertController to do that:

/**
Shows an alert with a title and a message
*/
func showAlert(title: String, message:String) {

let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)

// show the alert with a "ok" button that will close the alert
let okAction = UIAlertAction(title: "ok", style: UIAlertActionStyle.Default) { (action) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
}
alertController.addAction(okAction)

// show alert controller
self.presentViewController(alertController, animated: true, completion: nil)
}

Complete example:

import UIKit
extension UIViewController{

/**
Shows an alert with a title and a message
*/
func showAlert(title: String, message:String) {

let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)

// show the alert with a "ok" button that will close the alert
let okAction = UIAlertAction(title: "ok", style: UIAlertActionStyle.Default) { (action)-> Void in
self.dismissViewControllerAnimated(true, completion: nil)
}
alertController.addAction(okAction)

// show alert controller
self.presentViewController(alertController, animated: true, completion: nil)
}

/**
Shows a loading indicator and disables user interaction with the app until it is hidden
*/
func showModalSpinner()->UIActivityIndicatorView{

// user cannot interact with the app while the spinner is visible
UIApplication.sharedApplication().beginIgnoringInteractionEvents()

var indicator = UIActivityIndicatorView()

indicator = UIActivityIndicatorView(frame: self.view.frame)
indicator.center = self.view.center
indicator.backgroundColor = UIColor(white: 0.0, alpha: 0.5)
indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
indicator.hidesWhenStopped = true
indicator.startAnimating()

self.view.addSubview(indicator)

return indicator
}

/**
Hides the loading indicator and enables user interaction with the app
*/
func hideModalSpinner(indicator: UIActivityIndicatorView){

indicator.stopAnimating()
indicator.hidden = true

// user can interact again with the app
UIApplication.sharedApplication().endIgnoringInteractionEvents()
}
}

Swift 2 examples – #11 Loading images from the Photo Library and the Camera

This post is part of my collection: Swift 2 – For Beginners.

In this example we will see how to load photos in our application from the Photo Library and from the camera.

To open the photo library to pickup a photo we need a UIImagePickerController. Our controller can be the delegate. To do that we have to implement the protocols: UINavigationControllerDelegate and UIImagePickerControllerDelegate.

This code creates UIImagePickerController and use the method presentViewController to open the Photo Library:

  func selectImage(){
        let imagePickerController = UIImagePickerController()
        imagePickerController.delegate = self

        imagePickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
        imagePickerController.allowsEditing = true

        self.presentViewController(imagePickerController, animated: true, completion: nil)
    }

Once the user selects a photo our controller will be called back. Let’s implement a function that will load the selected image into a imageView:

   // Pick image finished, show selected image in a imageView
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        // Show image
        imageView.image = image
        self.dismissViewControllerAnimated(true, completion: nil)
    }

To take a new photo using the camera we just change the value of imagePickerController.sourceType. Instead of PhotoLibrary we use Camera.

We can add a parameter to the previous function to specify the source of our image:

    func selectImage(from source: UIImagePickerControllerSourceType){
        let imagePickerController = UIImagePickerController()
        imagePickerController.delegate = self

        imagePickerController.sourceType = source
        imagePickerController.allowsEditing = true

        self.presentViewController(imagePickerController, animated: true, completion: nil)
    }

Complete example:

import UIKit

class ViewController: UIViewController,

    // 1 Allows navigation to camera or photo library to pick up a photo
    // used to set this controller as delegate of UIImagePickerController
    UINavigationControllerDelegate, UIImagePickerControllerDelegate
{

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBOutlet weak var imageView: UIImageView!

    @IBAction func addFromCamera(sender: AnyObject) {
        selectImage(from: UIImagePickerControllerSourceType.Camera)
    }

    @IBAction func addFromLibrary(sender: AnyObject) {
        selectImage(from: UIImagePickerControllerSourceType.PhotoLibrary)
    }

    // 2 Show image picker or camera app
    func selectImage(from source: UIImagePickerControllerSourceType){
        let imagePickerController = UIImagePickerController()
        imagePickerController.delegate = self

        imagePickerController.sourceType = source
        imagePickerController.allowsEditing = true

        self.presentViewController(imagePickerController, animated: true, completion: nil)
    }

    // 3 Pick image finished, show selected image
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        // Show image
        imageView.image = image
        self.dismissViewControllerAnimated(true, completion: nil)
    }
}

Swift 2 examples – #10 Serialization to/from JSON using ObjectMapper

This post is part of my collection: Swift 2 – For Beginners.

JSON (JavaScript Object Notation) is a lightweight, human readable, open source, data-interchange format. In this example we will see how to serialize and deserialize objects to/from JSON using ObjectMapper in our iOS application.

For example, this would be the JSON representation of an object with two properties
name: string = “Juan Carlos”
age: Int = 29
JuanCarlosJSON

ObjectMapper is an open source project to make JSON Object mapping written in Swift. It is available in github: ObjectMapper.

Reference ObjectMapper using CocoaPods

CocoaPods is a dependency manager for Swift and Objective-C Cocoa projects. We will use it to reference ObjectMapper in our project. (If would also be possible to add it as a submodule. Check the project in GitHub for more information)

To add ObjectMapper to our project we need to execute the following commands:
Install cocoapods

sudo gem install cocoapods

Create Podfile in our project root

touch Podfile

To reference ObjectMapper add this content to the PodFile

use_frameworks!
pod 'ObjectMapper', '~> 1.0'

Select XCode path

sudo xcode-select --switch /Applications/Xcode.app

Add ObjectMapper repository

pod repo add ObjectMapper https://github.com/Hearst-DD/ObjectMapper.git

Install the project locally

pod install

Close XCode and open the created file *.xcworkspace. It contains our project and a reference to a new project called Pods. All our referenced projects will be contained in this new project.

Now we are ready to import and use ObjectMapper:

import ObjectMapper

Define our objects and implement the protocol “Mappeable”

To serialize and deserialize objects we must implement the protocol Mappeable.

// Mappeable source code
public protocol Mappable {
	init?(_ map: Map)
	mutating func mapping(map: Map)
}

Let’s write our User class, it will have two properties, name and age. The class will also implement the protocol Mappeable.

// Define our class and implement the Mappable protocol
class User: Mappable {
    var name: String?
    var age: Int = 0
    
    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
    
    // MARK: Mappable
    required init?(_ map: Map) {
        // subClasses must call the constructor of the base class
        // super.init(map)
    }

    func mapping(map: Map) {
        name <- map["name"]
        age  <- map["age"]
    }
}

Serialize and Deserialize objects

ObjectMapper is extremely easy to use:

        // Object to be serialized to JSON
        let myUser = User(name: "Juan Carlos", age: 29)

        // Convert Object to JSON
        let serializedUser = Mapper().toJSONString(myUser)
        print(serializedUser)
        
        // Convert JSON to Object
        if let deserializedUser = Mapper<User>().map(serializedUser){
            print(deserializedUser.name)
        }
        
        // Output:
        //  Optional("{\"age\":29,\"name\":\"Juan Carlos\"}")
        //  Optional("Juan Carlos")