Angular2 vs React

angularvsreact

A comparison between Angular2 vs React from the perspective of an enterprise C# developer

Currently we had a lot of discussion on which web framework we should invest: Angular2 or React. Therefore, I decided to experiment with both and make up my own opinion.

I use Angular1 since a couple of years now and I love it. Nevertheless, hearing about all the goodness of React, I wanted to give it a try and compare both frameworks with an open mind.

So, I reviewed these technologies according to my own perspective, the perspective of an enterprise .Net developer.  In my world applications have a lifecycle that can easily stretch over 10 years. Therefore, be able to support big projects and keeping maintaining them over time, is key. This is why I took Typescript as a given.  Coming from a .Net background and having built all my Angular apps with the help of Typescript I don’t wanted to get back to pure JavaScript. I love the static type checking and all the tooling support, code completion and refactoring typescript brings to the table.  The ease of programming inside the frameworks with Typescript is for me an important feature. This is why I tested both frameworks using Typescript.

React

React is a declarative Javascript UI library, created by Facebook that handles a very specific set of concerns, composing and packaging your UI in components and rendering these components. What could seem odd in the beginning is that React doesn’t separate the HTML from the JavaScript.  Frankly I got used to it and learned to appreciate the advantages of this. You can still separate the logic from the presentation by creating components that only render Html and components that handles the logic  (named “Controller Views” components).

Here is a simple example of a React component:

import * as React from "react";

export class HelloWorld extends React.Component<{}, {}> {
    render() {
         return (
            <div>

                <p>Hello world from react!</p>

            </div>
        );
    }
}

The render() method is the core method of the React component.  React implements a virtual DOM, this is an internal representation of the DOM.

A react component is written in a JSX file.  JSX basically enables to mix HTML with JavaScript, you can also directly use js files in React but then you lose some syntactic sugar.   To transform the JSX at runtime or compile time you typically need to use Babel. Now TypeScript provide support for JSX, this enable to use the Typescript compiler instead of Babel.  To enable support for JSX with the Typescript compiler you need to add the compiler option: “jsx”:”react” in your tsconfig.json file.  When this is done, you can use the “TSX” extensions, this is the equivalent of “JSX” but for Typescript.

I found that VisualStudio 2015 and VS Code provided a good support for the TSX format.

fig1
With TSX you get auto completion in the HTML parts.

To illustrate other key concepts of React we need a more sophisticated example:

fig2

Notice on line 9, we pass two type arguments to declare our AuthorComponent class.  The first is the “prop” the other is the “state”.  These two concepts should not be confused.  “state” is an internal concern of the component, it holds the internal data (model) of the component and can change. Every time it changes the virtual DOM is adapted.  “props” are passed to the component and are not meant to be changed.  An illustration of the use of “props” is with “Controller Views Components”, these are parent components that host child components. “props” are typically used to pass the component properties:

fig3
author, onChange, onSave, errors are “props” of the AuthorForm component

Angular2 is a Framework,  React is only a UI library, therefore it’s usually used together with other libraries like Redux.  Redux help us to manage the application data flows.  You don’t absolutely need Redux but usually when building large scaled enterprise applications it’s something you’ll want to add to your React apps.  In fact you can even use Redux with Angular but the unidirectional flow of React lent itself very well to the Redux model.  Redux is based on the original Facebook Flux library. It helps at managing the application State. I found that managing state in a React application without Flux or Redux demand a considerable effort. Nevertheless, these frameworks also add a lot of supplementary concepts to learn.  Explaining these is outside the scope of this article.

Angular2

Although Angular2 comes with a lot of breaking changes and you can’t upgrade directly from Angular1, Angular2 still feels like an evolution of Angular1. Despite all the concept changes, switching from Angular1 to Angular2 was relatively easy. Nevertheless, I still have troubles with the new Angular2 binding syntax.

Angular2 advocates the separation of HTML and Code.  Although these can now be in the same file you never mix JavaScript & HTML in Angular2.   This is usually a good practice especially when working with web designers but as you use a specific data-binding syntax you don’t get the code highlighting & code completion you get with React.

Angular2 is quite complete and opinionated framework.  With Angular2 you get all in a box.  You can replace many parts but I never really needed to.  From an enterprise viewpoint, be able to count on a complete but modular toolbox is an advantage.  It helps new hired developers to be productive faster and enforce consistency.

Here is an example of what a “Hello world” Angular2 app looks like.  A tutorial is available on the angular quickstart guide, it demonstrates how to build a basic Angular app.  It took me less than 5 minutes to complete this tutorial. Once completed you’ve the basic building blocks: a project structure, a configured typescript compiler and a small web server that keeps the app running while you build your app.

Angular2 separate the HTML from the code, you can add the Html inside a Component but it’s still in a separate section. To be able to add view logic inside the HTML you need to use the Angular2 template syntax. A simple Angular HTML component looks like this:

fig4

The *ngFor, {{todo.title}}, (click), [todo] and <todo-detail> elements are all Angular2 template syntax.  The <todo-detail> tag represent a TodoListComponent.

The todolist.component.ts code could be like this:

fig5

Here is an example of how to define a two-way databinding works in Angular2:

<input type=”text” [(ngModel)]=”user.first_name” />

Every Angular2 app begins by declaring at least one module.  This is an example of such a module:

import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';
import { HttpModule }    from '@angular/http';
import { Router }        from '@angular/router';
import { AppComponent }             from './app.component';
import { TeamComponent }            from './team/team.component'
import { TeamService }              from './services/team.service'
import { routing }                  from './app.routing';

@NgModule({
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        routing
    ],
    declarations: [
        AppComponent,
        TeamComponent,
    ],
    providers: [TeamService],
    bootstrap: [AppComponent]
})

My evaluation

Angular2 loves TypeScript

For me the biggest difference between both is that Angular2 is Typescript native and React just tolerates it. Sure, you can use Typescript with React, I provided some examples how you can do that. Nevertheless, I spend a lot of time figuring how.  This is especially a problem when you consider that the React examples you find on the web are inconsistent. During my experimentation with React I often was forced to use the <<any>> type.  This means that I lost the goodness of working with Typescript: compile time type checking, autocomplete and refactoring support.

Angular2 feels like home for C# devs

The React documentation provided by Facebook is quite good but the Angular2 official documentation is just superb.  Following the quickstart guide I was able to construct a full application in less than 5 minutes.  You can also find a complete guide that covers every topic of the framework.  The Angular2 “Tour of Heroes” is a tutorial where you build a real world application using every important aspect of Angular2.

Every example in the Angular2 documentation is provided in Typescript.  For React most documentation is in ES6 but on other internet sites most of the examples are still in ES5. Finding an up-to-date tutorial on how to bootstrap a standard React application with Typescript is not easy. You can find one on the TypeScript site but it’s very basic.  When you compare this to the Angular2 documentation where you even find guidance on how to setup VisualStudio, you immediately understand that Angular2 is far more welcoming for C# devs as React.  For React the only guidance I found on how to integrate Typescript was on the Typescript site itself. Usually you need to figure out by yourself how to use Typescript with React as you don’t find a lot on the internet. During my React experimental project I’ve wasted many hours converting Javascript examples to Typescript. I had some problems with inconsistencies between type definitions; sometimes I needed to tweak this myself to get my project compiled.  I didn’t have any of these problems using Angular2, the type definitions where always up to date and all provided libraries worked well together.

Mixing Html inside JavaScript is fine!

When working with React in VS.Code and VisualStudio, I was first disappointed as these editors didn’t support the JSX syntax correctly.  All this changed when I converted my first code to TSX (the TypeScript equivalent of JSX).  Here React really shined as I got type checking & code completion even inside my TSX templates.   Mixing typescript inside the HTML was for me a little revelation.  You don’t need to learn another programming or templating syntax. You can use the same programming language everywhere. When you use TypeScript you even get static type checking in your templates. Those who have already used Angular will certainly see the benefit of this.  With Angular I can’t count the number of times I got a blank page or things missing on my page because I misspelled some property in the template or used the wrong templating syntax.

ErrorMessages are better in React

Another great aspect of React is the explicit error messages it provides.
fig6

In Angular1, at best,  you usually get a blank screen with completely useless error messages. With the current version of Angular2 I found the error messages had improved. Most of the time the error messages returns explicit messages with descriptions on how you can solve the problem.
fig7

Many ways to do the same thing

A pain point concerning React is the many ways to do the same thing. For example I found the following ways to create a React component: using the ES5 Create Class Component, using the ES6 class component, using stateless components, with Object.Create, with Mixins, creating Parasitic Components and with the StampIt library.    Also, a primary concern for me, is the high churn rate of React, currently React is at version 15.  This is a high number for a framework that is only a couple of years old.

Conclusion

For me the conclusion is the following: if you are a C# enterprise developer who wants to get all the goodness Typescript brings to the table, Angular2 is the obvious choice.  React is a beautiful library that enforces good design but it doesn’t embrace Typescript as Angular2 does.  React has certainly some advantages compared to Angular2 like using JavaScript for the templating syntax. Nevertheless Angular2 is what an enterprise developer wants. It’s complete, opinionated and his Typescript native support makes it more crafted for large scale applications.  Angular2 two-way binding also result usually in a higher productivity rate and less code to maintain when it comes to building business applications.

 

 

 

To build this review I used following resources:

 

The source code of the example applications can be found on Github:

  • React-pluralsight: Simple demo app using TypeScript and React based on the pluralsight course, Building Applications with React and Flux

  • MerodeTeamManagement: Angular2 app using .Net Core as a backend

TypeScript tutorial: build a node api with MongoDB

 

download

In this TypeScript starter tutorial we’ll setup a node api that stores and retrieve his data from a mangoDB backend. 

For the lazy ones, the full code can be found on my github repo under:
https://github.com/geobarteam/node-mongo

1) Install the prerequisites

First you need NodeJsIf you haven’t already TypeScript installed:

$npm install -g typescript

To Install MongoDB on your dev box, follow the instructions on: https://docs.mongodb.com/manual/installation/

You can query and configure mongoDb through the command line but I prefer to use Robomango.

2) Create and configure the Node project

A) Create a new node project from the command line:

$ mkdir mango-node
$ cd mango-node
$ npm init

You can just accept all the proposed values by hitting enter. npm will create a new package.json file.

B) Download the npm packages
We’ll use 3 npm packages inside our app:

  • Mongoose, it’s a sort of driver for MongoDB and it provides a schema-based way to model your solution.
  • express: the most used web framework for node
  • body-parser: let us pull POST content from our HTTP request.

Install the npm packages:

$ npm install mongoose —save
$ npm install express —save
$ npm install body-parser —save

C) Install the TypeScript definitions

To enable manage and install TypeScript definitions we’ll use Typings. Therefore you need typings to be installed as a global package:

$ sudo npm install -g typings

To install the typings packages:

$ typings install mongoose
$ typings install dt~express –save —-global
$ typings install dt~body-parser –save —-global
$ typings install dt~node –save —global
$ typings install mime —save
$ typings install dt~express-serve-static-core –save —global
$ typings install dt~serve-static –save –global

D) Add a TypeScript configuration file tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  }
}

3) Implement the server

A) Create a index.ts file:

import * as express from "express";
import * as bodyParser from "body-parser"

var app = express();
var mongoose = require('mongoose');
mongoose.connect("mongodb://localhost/mydb");

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));

var server = app.listen(3000, function () {
    console.log('Server listening on port 3000');
});

B) Test that you can compile and start your server:

$ tsc
$ node index.js
Screen Shot 2016-06-25 at 13.04.03
C) Configure the npm start command.

To combine these steps in one command you can use the “scripts” section of your package.json file:

"scripts": {
    "start": "node ./index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

Screen Shot 2016-06-25 at 13.08.09

4) Define the entity and his mongoose schema

We need to define a User entity and his mongoose schema.  Create a user.ts file:

import * as mongoose from "mongoose";

interface IUser{
    first_name:string;
    last_name:string;
    email:string;
}

interface IUserModel extends IUser, mongoose.Document{};
var userSchema = new mongoose.Schema({
    first_name: String,
    last_name: String,
    email: String,
});

var User = mongoose.model<IUserModel>("User", userSchema);

export = User;

5) Implement the REST API

Finally we implement our api logic. 

A) Open the index.ts file and import our user entity:

import * as User from “./User”

B) Setup the http endpoints

Just after the setup of the bodyParser middleware, configuration the app to handle the http verbs, get and post:

/* Create */
app.post('/api/user', function (req, res) {
    var newUser = new User(req.body);
    newUser.save((err)=>{
        if (err){
            res.json({info: 'error during User create', error: err});
        }
        res.json({info: 'User saved successfully', data: newUser}); 
    });
});

/* Read all */
app.get('/api/user', function (req, res) {
    User.find((err, Users) => {
        if (err) {
            res.json({info: 'error during find Users', error: err});
        };
        res.json({info: 'Users found successfully', data: Users});
    });
});

/* Find one */
app.get('/api/user/:name', function (req, res) {
    var query = { name: req.params.name};
    User.findOne(query, function(err, User) {
        if (err) {
            res.json({info: 'error during find User', error: err});
        };
        if (User) {
            res.json({info: 'User found successfully', data: User});
        } else {
            res.json({info: 'User not found with name:'+ req.params.name});
        }
    });
});

6) Test the app.

A) download Postman , it’s a tool to help you test and document your api’s.

B) Launch your app:

Screen Shot 2016-06-25 at 13.08.09

C) Launch Postman and configure a post request with Postman. 

First set the URL & headers, add a content-type key with value: application/json:
Screen Shot 2016-06-25 at 12.10.02

Then configure provide the body of your request:

Screen Shot 2016-06-25 at 13.39.43

Push send, you should get something like this in the response body:

Screen Shot 2016-06-25 at 13.39.02

That’s all, now you can populate as many users you want and try to retrieve all or a specific one.

Start building apps with Angular2, NodeJs, MongoDB, Gulp and TypeScript

Screen Shot 2016-06-11 at 10.42.19

On https://github.com/geobarteam/merode/tree/mongoose I assembled an example application based on the Angular2 Tour of Heroes tutorial but extended with NodeJs and MongoDB. 

The example is an ideal starting place to build applications on a nice development stack made of :

  • Angular2 for the fronted application
  • Node.js: as backend web server.
  • LiteServer: This server should not be used for production but only during the development. LiteServer is specifically designed for serving static pages during the development.  It refresh the browser every time a file is saved.
  • Express: to serve the static pages in production.
  • MongoDB & Mongoose: Document database technology.  Mongoose is the client side library enabling to interact with MongoDB .
  • TypeScript: for providing the type safety.
  • Gulp: it’s used to automate all sort of development tasks like copying files or cleaning the typescript compile output.

To startup the application in development mode just type: “npm start”.

ASP.NET Core: Unit testing with NUnit

In this post I reuse my sample project (ported to ASP.NET Core RC2)  but add a new Nunit test project to it.

Nunit has no testrunner ready yet that supports testing with dotNetCore. In fact for the moment only XUnit supports the VS2015 GUI testrunner.

NUnit has a lightweight testrunner NUnitLight. DotNet Core supports only two mode, ASP.NET MVC apps and Console apps.  So, what I did is use NunitLight inside a .Net Core console.

The code can be found here: https://github.com/geobarteam/myClub/tree/1-4.Add.NUnit.TestProject

  1. You should start by adding a new .Net Core Classlibrary project and addd the NUnit & NUnitLight dependencies.
    $ yo aspnet
    yeoman
  2. Modify the project.json file
    {
      "version": "1.0.0-*",
    
      "buildOptions": {
        "preserveCompilationContext": true,
        "emitEntryPoint": true
      },
    
      "dependencies": {
        "NUnit": "3.2.1",
        "NUnitLite": "3.2.1",
        "MyClub.Web": "1.0.0-*"
      },
    
      "frameworks": {
        "net461": { }
      },
    
      "tooling": {
        "defaultNamespace": "MyClub.Test"
      },
      "commands": {
        "test": "MyClub.Test"
      }
    }
  3. Modify the program.cs file
    public class Program
    {
        public static void Main(string[] args)
        {
            new AutoRun().Execute(args);
        }
    }
  4. Add a Nunit test file: SampleTest.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using NUnit.Framework;
    
    
    namespace MyClub.Test
    {
        [TestFixture]
        public class SampleTest
        {
           [Test]
            public void PassingTest()
            {
                Assert.AreEqual(4, Add(2, 2));
            }
    
            [Test]
            public void FailingTest()
            {
                Assert.AreEqual(5, Add(2, 2));
            }
    
            int Add(int x, int y)
            {
                return x + y;
            }
        }
    }
    
  5. Start the test session with “dotnet run” , you can also launch the test project and debug it through VS2015.
    nunitdotnetrun

ASP.NET CORE: Upgrade from RC1 to RC2

RC2 of .Net Core is out, so it’s time to upgrade your apps. The official documentation on how to upgrade can be found on: https://docs.asp.net/en/latest/migration/rc1-to-rc2.html

Here is the list of things I did to upgrade my existing ASP.NET CORE RC1 apps to RC2 :

Without VS2015:

  • Updated Yeoman: yo, choose Update Generators
  • With Yeoman create a new: yo aspnet, Web Application Basic.
  • Copy the content of the project.json to my existing application
  • From inside the project folder I run from the command line: dotnet restore
  • To test if everything work file: dotnet run

With VS20015:

  • Remove all VS2015 specific files: *.sln, .vs, *.xproj, *.xproj.user
  • Delete the existing package.json and copy an existing package.json inside the project (created with file, new project, web, ASP.NET Core Web Application).
  • Open the project with Visual Studio, here VS2015 crashed!
  • I needed to copy some parts of the xproj project file created with the template. Mainly the TargetFrameworkVersion part.
  • Re-open my solution, compile, run, it worked!

I had also to do minor adaptations in my code. I had to port from the namespace Microsoft.AspNet.* to Microsoft.AspNetCore.*

If you want to target the .Net framework you need to:

  1. Change the framework part of your project.json:
    “frameworks”: {
    “net461”: {}
    },
  2. Remove: “Microsoft.NETCore.App” from the dependencies.

Asp.Net Core: Building TypeScript with Gulp

In the preceding post I show how you can compile your TypeScript files with tsc. You can also simply use Visual Studio and enable the option: “Compile TypeScipt on Build” in the Build properties of your ASP.NET Core project.
While these are valid options I generally prefer to use Gulp to setup my own workflow.
In this post I’ll explain how you can use Gulp to setup and fine tune a Typescript build.

The code is available at: https://github.com/geobarteam/myClub/tree/1-3.Build.TypeScript.With.Gulp

$ git pull https://github.com/geobarteam/myClub.git 1-3.Build.TypeScript.With.Gulp

A) Pull the Gulp packages

First we’ll need to use npm to pull down some gulp packages that will help us in setting up our Typescript build.
The npm packages we need are:
“gulp-rimraf”: “^0.2.0”,

“gulp-sourcemaps”: “^1.6.0”,

“gulp-typescript”: “^2.13.4”,

“gulp-uglify”: “1.2.0”,

“rimraf”: “2.2.8”

gulpfiles1

To install these packages you can copy paste the list here above right under the “devDependencies” of the package.json file but I prefer to use npm.
To install these packages through npm, first navigate to the root of your project and use the command:
$ npm install [packagename] –save-dev
The –save-dev option is used to update our packages.json and put the new dependencies under the “devDependencies”.

B) Create the Gulp Tasks

Here we’ll use gulp-typescript to compile automate the typescript build. The documentation can be found here. Open the gulpfile.js and modify as follows:

  1. Require the packages
    var rimraf = require("rimraf"),
        gulpRimraf = require("gulp-rimraf"),
        concat = require("gulp-concat"),
        ts = require("gulp-typescript"),
        sourcemaps = require('gulp-sourcemaps');
  2. Add following path variables
    typescriptRoot: './scripts/',
    typescriptOut: webroot + 'js/',
    typescriptJs: './scripts/**/*.js',
    concatTsFileName: 'app.js'
  3. As we’ll use the tsconfig.json file to set the build properties we’ll create a project:
    var tsProject = ts.createProject(paths.typescriptRoot + 'tsConfig.json'); // use tsconfig.json
    
  4. Write the typescript build task
    gulp.task("tsbuild", function () {
        var tsResult = tsProject.src()
            .pipe(sourcemaps.init()) // needed to create sourcemaps
            .pipe(ts(tsProject)); // use tsconfig.json
    
        return tsResult.js
            .pipe(concat(paths.concatTsFileName)) // concat all output files into a sings js files
            .pipe(sourcemaps.write()) // write the sourcemap to be able to debug the ts files
            .pipe(gulp.dest(paths.typescriptOut)); // output the result on specific path
    });
  5. Write the clean tasks
    gulp.task("clean:tsout", function (cb) {
        rimraf(paths.typescriptOut + paths.concatTsFileName, cb); // rimraf is used to delete a folder
    });
    
    gulp.task("clean:scriptjs",
        function () {
            return gulp.src(paths.typescriptJs, { read: false })  // to clean up multiple files we need to use gulp-rimraf
              .pipe(gulpRimraf());
        });
    
  6. If you use VS2015 you can bind the gulp tasks with your VS build. The clean tasks should run before our build and after our build we should run first the ‘tsbuilld’ and then the ‘min’ task.
    gulpfiles2gulpfiles3
  7. Write a watch task if you want that the ts build is triggered when a ts file changes.
    gulp.task("watch:tsbuild", ['tsbuild'], function () {
        gulp.watch(paths.typescriptRoot + '**/*.ts', ['tbbuild']);
    });
  8. If needed, modify your angular script links. As the predefined min:js gulp task minifies all js files we can choose to use the minified app.js file in production.
     <environment names="Development">
            <script src="~/lib/jquery/dist/jquery.js"></script>
            <script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
            <script src="~/lib/angular/angular.js"></script>
            <script src="~/js/app.js"></script>
        </environment>
        <environment names="Staging,Production">
            <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js"
                    asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
                    asp-fallback-test="window.jQuery">
    
            </script>
            <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.5/bootstrap.min.js"
                    asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
                    asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal">
    
            </script>
            <script src="~/lib/angular/angular.min.js"></script>
            <script src="~/js/app.min.js"></script>
        </environment>

ASP.NET Core: Modify an Angular App to use Typescript

In this step we’ll modify our Angular 1.x app to use typescript.

Code can be found on: https://github.com/geobarteam/myClub

Branch: 1-2.Add.Typescript

Configure a Typescript Build

First install the latest Typescript compiler:

npm install -g typescript

Add a script folder to your project, this will be the home for your typescript files:

scriptfolder

Add a tsconfig.json file right under the scripts folder.

tsconfigs

The tsconfig.ts file contains the build options for the typescript compiler, it allows to run the Typescript compile process without specifying arguments.  To compile from the command line you should navigate inside the script folder and run: tsc

tsconfig.ts:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "compileOnSave": true
} 

Configure Typings

Typings allow to simply manage and install TypeScript definitions.

Install typings globally via npm:

npm install typings –global

To install typing definitions for angular 1.x, and Jquery use the command:

typings install angular jquery –ambient –save

 

Migrate the Angular scripts to use typescript

Move all your javascript angular scripts into the “scripts” directory and rename their suffix to “xxxxx.ts”.

tsconfigs

Add the “any” type to all your parameters and variables.
This is only required because we   used the “noImplicitAny”: false setting.  I like to use it as it makes clear that I should type all variables.

function myTeam($location:any) {
…
    }

You should now modify the tsconfig.ts to add the files to compile and set an output file:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    "outFile": "../wwwroot/app/app.js"
  },
  "compileOnSave": true,
  "files": [
    "../typings/main.d.ts",
    "app.module.ts",
    "app.config.ts",
    "home.controller.ts",
    "myTeam.controller.ts"
  ]
} 

Inside _Layout.cshtml modify the angular scripts link to use the app.js script file:

…
<script src="~/lib/angular/angular.min.js"></script>
<script src="~/lib/angular-ui-router/release/angular-ui-router.js"></script>
<script src="~/app/app.js"></script>    
</body>
</html>

When compiling the app in VS2015 or running tsc from the command line inside the script folder;  you should end up with a app.js file inside the wwwroot/app directory:

prscr

Test the app, it should still run exactly as before.

ASP.NET Core: Create an Angular App


aspnetcore

Here I’ll start a series of little tutorials on how to build from scratch a new Angular application with ASP.NET Core and MVC5.

The code used in these tutorials can be found under my git hub project: myClub

Every post has his own dedicated branch, so you can just use  “git checkout <branchname>” to find all the source code of the post you’re interesting in.

1) Create a new MVC core project

To generate a new project we’ll use Yeomen.  Open a commend prompt/bash shell or powershell shell on the location you want to put your new project =>

mkdir myClub

cd myClub

yo aspnet

yeomen

Choose Web Application Basic and provide a name.


 

2)          Add Angular to the MVC app

1)      Add Angular, from command line inside you project dir:
bower install angular angular-ui-router –save

Add angular to _layout.cshtml :

<script src=”~/lib/angular/angular.min.js”></script>


 

3) Create two js scripts under wwwroot:

app.config.js

(function () {
    'use strict';

    angular.module('myClub')
    .config(initrouter);

    function initrouter($stateProvider, $locationProvider, $urlRouterProvider) {
        $locationProvider.html5Mode(true);
        $urlRouterProvider.otherwise('/');
        $stateProvider
            .state(
                'home',
                {
                    url: '/',
                    templateUrl: 'app/home.html',
                    controller: "HomeController",
                    controllerAs: 'vm'
                }
            )
            .state(
                'myteam',
                {
                    url: '/myteam',
                    templateUrl: 'app/myTeam.html',
                    controller: "MyTeamController",
                    controllerAs: 'vm'
                }
            );
    }
})();

app.module.js

(function() {
    'use strict';

    angular.module('myClub', ['ui.router']);
})();

printscreenvscode


 

4) Add two controllers

myTeam.controller.js & home.controller.js

(function () {
    'use strict';

    angular
        .module('myClub')
        .controller('HomeController', myTeam);

    myTeam.$inject = ['$location'];

    function myTeam($location) {
        /* jshint validthis:true */
        var vm = this;
        vm.players = [];


        vm.title = 'Home';

        activate();

        function activate() {
           
        }
    }
})();

 

5) Add the two html pages inside the angular app

home.html

<div class="jumbotron">
    <div class="container">
        <h1>MyClub</h1>
        <p></p>
    </div>
</div>
<div>
    
</div>

myTeam.html

<div>
    <p>My Team</p>
</div>

 

6)  Reference the js scripts in _layout.cshtml

<script src="~/lib/angular/angular.min.js"></script>
<script src="~/lib/angular-ui-router/release/angular-ui-router.js"></script>
<script src="~/app/app.module.js"></script>
<script src="~/app/app.config.js"></script>
<script src="~/app/home.controller.js"></script>
<script src="~/app/myTeam.controller.js"></script>

 

7)      Add the angular app inside idex.cshtml and move the navbar from _layout.html

index.cshtml

<script src="~/lib/angular/angular.min.js"></script>
<script src="~/lib/angular-ui-router/release/angular-ui-router.js"></script>
<script src="~/app/app.module.js"></script>
<script src="~/app/app.config.js"></script>
<script src="~/app/home.controller.js"></script>
<script src="~/app/myTeam.controller.js"></script>

 

8)      Test the application

testpage

Asp.Net Core: How to configure your development environment on Linux

linuxVsCode

In this post I explain how to setup an ASP.NET 5 RC1 development environment on Linux Ubuntu 14.04 using vagrant.

Here you’ll find the vagrantfile and the provisioning script used to setup your vagrant box.

You can also use the provision.sh script to configure an Ubuntu 14.04 VM without using vagrant. Nevertheless I strongly recommend to use vagrant and to follow the steps depicted here.

Install Vagrant on your windows host

  • First download and install chocolatey: https://chocolatey.org/
  • Install Cygwin and add the openssh through cyg-get, open a command or powershell pompt and type following commands:

choco install Cygwin

choco install cyg-get

cyg-get openssh 

  • Setup Vagrant and virtualbox:

choco install virtualbox

choco install vagrant

  • Test vagrant is installed correctly, Open a Cygwin terminal and type:vagrant –v

The console should output your vagrant version.  If this isn’t working check your path variable, the bin directory of vagrant should be added, if this is not found, add the vagrant bin dir to your Path.  (It’s usually: C:\HashiCorp\Vagrant\bin)

 

Download and setup your Linux base box with Vagrant

  1. Open a Cygwin terminal and type:

$ mkdir data

$ mkdir netCoreRC1

$ cd netCoreRC1

 

  1. Configure and launch your vagrant box
    Copy the ”Vagrantfile” and “provision.sh” into the directory netCoreRC1 – you’ll find these files here: https://github.com/geobarteam/vagrant/tree/master/netCoreRC1

Now run:

$ vagrant up

This will start your vm and start the provisioning process.

To stop or reboot your vm:

$vagrant halt

To login into your box through ssh:

$ vagrant ssh

If you need to reconfigure your keyboard for your country type:

sudo dpkg-reconfigure keyboard-configuration

It’s also recommended to create your own user with:
sudo adduser [your user name]
and add it to the sudo group:
sudo adduser [your user name] sudo

You can login in the gui interface with user: vagrant and password: vagrant.

To complete the install you’ll need to reboot your vm: vagrant reload
To test that .net core and mono are installed open a terminal or ssh session and type:

dnvm list

You should see something like:
Active Version              Runtime Architecture OperatingSystem Alias

—— ——-              ——- ———— ————— —–

1.0.0-rc1-update1    coreclr x64          linux             *

1.0.0-rc1-update1    mono                 linux/osx       default

If something went wrong or you want to use another user than vagrant, open an ssh session under the new user account:

ssh -p 2222 [username]@localhost

Copy paste following commands into the ssh window:

curl -sSL https://raw.githubusercontent.com/aspnet/Home/dev/dnvminstall.sh | DNX_BRANCH=dev sh && source ~/.dnx/dnvm/dnvm.sh

dnvm upgrade -r coreclr

dnvm upgrade -r mono

This should install .net core & mono and fix your box, if you still encounter errors you can find the detailed install procedure of .net core under:
https://docs.asp.net/en/latest/getting-started/installing-on-linux.html

Install Visual Studio Code

Go to: https://code.visualstudio.com/ and download Vs Code.
You’ll find the install instructions under: https://code.visualstudio.com/

Once you’ve rebooted your dev box you can start experimenting with asp.net 5.

A good point to get started is to use yo men (it was already installed through the provisioning step) to create an empty Asp.Net 5 app as explained here: https://azure.microsoft.com/en-us/documentation/articles/web-sites-create-web-app-using-vscode/

Have fun!