Author Archives: geobarteam

How to structure a SPA using Angular CLI and ASPNET Core 2.0?

This article describes step by step how to structure a SPA made out of Angular for the client and ASPNET Core 2.0 for the backend.

When integrating these technologies you get a lot of options to choose from.  The first one is to decide if you should host your app inside an MVC View or just serve the angular app from static files.  After experimenting with both options, I decided that I should go for the simplest solution that could possibly work and started with just serving static files inside a Web-Api application.

For the project structure I prefer to completely separate both projects in folders beside each other. Nevertheless, I deploy the Angular app inside the same ASP.NET site that serve also the web-api.  Therefore, I need to bundle everything together when publishing the app.  To achieve this, I call the “ng build” from MsBuild targets and configured angular-cli to output the build in the \wwwroot folder of the ASP.NET app.

Concerning the IDE, what I found the most productivity was to develop my angular app using Vs.Code.  Thus far, for the Web-Api part I tend to prefer VisualStudio and Resharper. So, I optimized my Angular app for working with Vs.Code and my Web-Api project for VisualStudio.  During development I usually run the backend and launch the Webpack dev server through an “npm start” command.  At publish everything is nicely packaged together inside a ASP.NET app, so deploying to Azure can simply be done by using the VisualStudio publish wizard.

This article is a step by step guide demonstrating how to setup your dev environment following the configuration just described here above. If you’re an experienced Angular & Web-Api developer and only need an overview you can go to my  github project core-angular-example.  There you can download the solution template I use for making SPA’s with Angular-cli and DotNet Core.

For the less experienced developers you can follow this step by step guide to get started.

Prerequisites

To follow along you’ll need to install following things (just follow install guide):

1. Create the new App

Because I’m very enjoying the “dotnet” command line I propose to start our app with the  “dotnet new” and use the web-api template.  To create our Angular app we’ll do something similar but with the ng new command from Angular-Cli.

Start a new command prompt/shell and navigate to the folder you want to create your app in (root). Copy/Paste following commands:

mkdir angular-dotnetcore
cd angular-dotnetcore
mkdir web-api
cd web-api
dotnet new webapi
cd ..
ng new angular-app

2. Open your app with VS.Code

Start Vs.Code and choose file, open folder.  Navigate to the root of your app.

3. Disable TypeScript Compilation

Since we will eventually have TypeScript files in our project and we only want to compile/run them through angular-cli we should disable any TypeScript compilation. Open the web-api.csproj file and modify the top PropertyGroup:

<PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
    <TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
    <TypeScriptToolsVersion>Latest</TypeScriptToolsVersion>
    <IsPackable>false</IsPackable>
  </PropertyGroup>

4. Configure Startup.cs

As our web-api app will also serve the static files we need to configure the Stratup.cs file as follow


public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseDefaultFiles();
    app.UseStaticFiles();

    app.Use(async (context, next) => {
        await next();
        if (context.Response.StatusCode == 404 &&
            !Path.HasExtension(context.Request.Path.Value) &&
            !context.Request.Path.Value.StartsWith("/api/")) {
                context.Request.Path = "/index.html";
                await next();
            }
    });

    // Configure application for usage as API
    // with deafult route '/api/[Controller]'
    app.UseMvcWithDefaultRoute();

    // Serve static files
    app.UseStaticFiles();
}

5. Configure Angular CLI

Configure angular-cli to output the build inside the wwroot of the web-api app =>
edit the .angular-cli.json file and change the OutDir parameter:

"apps": [
    {
      "root": "src",
      "outDir": "../web-api/wwwroot",

Now when running ng build inside the angular-app angular-cli should output the result inside the wwroot folder of the web-api app.

6. Modify the app to display data coming from the backend

Modify the angular app to consume data from your web-api
Edit the following files under /angular-app/src/app file=>

App.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HttpModule } from '@angular/http';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http'
@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
   constructor(private _httpService: Http) { }
   title = "DotNet Core Angular Example";
   apiValues: string[] = [];
   ngOnInit() {
      this._httpService.get('/api/values').subscribe(values => {
         this.apiValues = values.json() as string[];
      });
   }
}

Edit app.component.html and add this as last lines of the html file:



<li>


<h2>Values from ValuesController</h2>


    

{{value}}

  </li>


</ul>


7. Redirect api calls to your DotNet core app

To be able to redirect api calls from your angular app when running in the webpack dev server you should create a proxy.conf.json file on the root of your angular app. Here my dotnet webapi runs on port 5000:

{
    "/api": {
      "target": "http://localhost:5000/",
      "secure": false
    }
}

Now you can test this part by:
– run the web-api with:
dotnet run
– launch the angular app and pass the proxy configuration:
ng serve –proxy-config proxy.conf.json
– Open Chrome on:
http://localhost:4200/

8. Configure npm proxy scripts to run and build the Angular app
edit the package.json of the angular-app and edit the script section:

"scripts": {
    "ng": "ng",
    "start": "ng serve --proxy-config proxy.conf.json",
    "build": "ng build",
    "build-prd": "ng build --prod --env=prod",

9. Create proxy scripts to run the npm commands from the web-api project

{
    "name": "core-angular-example",
    "version": "0.0.0",
    "license": "MIT",
    "scripts": {
        "install": "cd ../angular-app & npm install",
        "start": "cd ../angular-app & npm start",
        "build": "cd ../angular-app & npm run-script build",
        "build-prd": "cd ../angular-app & npm run-script build-prd"
    }
}

10. Setup MsBuild to compile the Angular app

Finally, we configure our web-api MsBuild script to invoke the ng build script when running a release build. Therefore, we add the following targets to the project webapi.csproj file:

<Target Name="EnsureNode">
  <Exec Command="node --version" ContinueOnError="true">
    <Output TaskParameter="ExitCode" PropertyName="ErrorCode" />
  </Exec>
  <Error Condition="'$(ErrorCode)' != '0'" Text="Node.js is required to build and run this project. To continue, please install Node.js from https://nodejs.org/, and then restart your command prompt or IDE." />
</Target>

<Target Name="ReleaseRunNgBuild" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Release' ">
  <CallTarget Targets="EnsureNode" />
  <Message Importance="high" Text="Install packages..." />
  <Exec Command="npm install" />
  <Message Importance="high" Text="Performing ng build for prd build..." />
  <Exec Command="npm run-script build-prd" />
</Target>

Now when you launch a Release build everything will be build together.

You can get a package containing all your app by using the publish command.
If you want to publish your app to Azure simply use the VisualStudio publish wizard or the Azure Powershell Publish commands.

Microservices: Size does not matter

The term micro in microservice suggest that services should be decomposed in very small units.  Martin Fowler recommend a size range that varies between a service-per-person and a service-per-dozen-people meaning that a microservice should not be maintained by a team of more than a dozen people.  This follows the notion of the Two Pizza Team organizations used at Amazon.  Following my own experience, micro services are maintained by small multidisciplinary teams varying between two to six people.   More important is the domain surface the micro service covers.  DDD advise to divide a unified model in smaller units named bounded context. Defining a service as covering no more than one bounded context is a comfortable way to constraint the size of your services.

So, cohesion is certainly a good way to define the service boundaries but in my opinion, this does not matter that much. A factor that is far more concrete is the speed and comfort with which developers can work on the service.  Developers that can get rapid feedback on their work by building rapidly, debug easily and test their code continuously on their own pc are in a far better position that those that have to deploy the system to an integration environment and wait for other devs to deploy their code before they can test their own work.

Therefore, I think that size of the service does not matter that much.  What’s really important is that the architecture of the system should account for autonomy.

Rather than emphasizing one rigid size for microservices, I prefer to make sure my services adheres to different forms of autonomy:

  • Runtime autonomy: The system should survive during a certain amount of time to a failure of one of its parts.
  • Testing autonomy: One should be able to test the parts of a system in isolation.
  • Change autonomy: One should be able to do modification without impacting other parts of the system.
  • Platform autonomy: The system should be able to run on platforms with different kind of hosting infrastructure.

Why Continous Delivery is vital in the Enterprise

When reviewing the DevOps study of last years I noticed an interesting slide depicting the number of deployments per day per developer.  This go against my personal experience that when projects are late adding developers to a project can decrease the overall productivity of the team.  The general rule is that when growing software and development teams you decrease the individual productivity of each developer.  This is mainly due to communication and integration overheads.

The DevOps study of 2015 found that for the high performers, those who continuously integrate and deploy code to production this rule does not apply.  The study demonstrates that organizations that do not practice continuous delivery deploy with decreasing frequency but that those that have adopt these practices deploy significantly increasing frequency.

This demonstrates that practicing continuous delivery is especially important for large enterprises. By adopting these practices they can compensate for the overhead linked with large systems and actually increase the productivity of large development teams.

Embrace Continuous Delivery or die!

In the classical view of software delivery, you need to make a trade-off between quality and speed. The traditional IT delivery process paradigm postulate that building quality software will demand longer to deliver. You trade quality with getting things done rapidly. Now, studies on teams that have adopted Continuous Delivery (CD) demonstrate exactly the opposite. Teams able to deploy by the push of a button not only deliver faster but they deliver better quality in a more reliable way. Being able to push changes fast and reliably to production changes the rule of the game and transforms many aspects of the IT delivery process. It reflects on aspects like:

Increased Availability & Manageability

Because you can push changes a lot faster you can make smaller changes with less downtime you don’t need to come in the middle of the night or weekends to deploy the system. This means less overwork and stress. It also frees up a considerable amount of time as teams don’t need to participate at long lasting release planning’s sessions to coordinate huge deployments.

Because you know you can push a change fast you’re also able to re-mediate faster and you don’t need to take account of being able to reverse a giant change. In place, you can adopt release strategies where you always advance forwards. In place of reverting a change you can be confident that you can fix any problem fast. This simplify the release process and lower the architecture complexity needed to be able to revert back a giant change.

Reports also demonstrates that teams practicing CD sees their number of big incidents diminishing drastically. Apart from the better intrinsic quality that CD brings this is also due to the automation that CD demands. The automated deployment pipeline eliminates errors that might result from manual configuration and error-prone practices.

Increased efficiency and shorter cycle time

Because you make smaller changes your tester and analyst can work in a constant flow of work. They don’t need to test everything in a great batch at the end of the release but can continuously work in at constant pace together with the developers.

When practicing continuous delivery automated tests are run immediately after each check-in what detects many bugs immediately. Bugs that are detected sooner are cheaper to fix. The developer can get immediate feedback even before he starts working on another task and so he knows where to search for the bug. It’s proved by many studies that bugs found before or immediately after the check-in are orders in magnitude cheaper to fix (sometimes more than 100 times).

Improved testability

To be able to deploy small changes independently the systems needs to be decoupled. This decoupling enables also to test the system more easily in isolation. Most of the changes can be tested without deploying to an integration environment. This lowers the number of environment needed and allows for a more rapid feedback.

Improved intrinsic product quality

Because the tremendous acceleration of time to market of a change, from once every 3 months to many times a day, product owners can experiment a lot faster enabling new product evolution strategies based on experimentation and continuous improvement. The book Lean Enterprise describes in detail how modern software companies takes advantages of continuous delivery to design products based on experimentation.

Improved Customer Satisfaction

CD brings confidence to the customers and other stakeholders on the delivery of their new features. CD enables to deliver new features at a constant and predictable pace and increase the visibility of the delivery process. By practicing feature toggles and decoupling the deployment from the actual release of the feature it enables to deploy a part or a complete new capability to early adopters.

Organizations that are more effective can spend more time on value adding activities. This creates a virtuous circle of continuous improvements that brings a decisive competitive advantage. Continuous Delivery is becoming the norm in the enterprise. IT organization that still stick to the old delivery model will be forced to change or will simply disappear. Following the 2015 State of DevOps practices study, the companies who their IT team’s practices continuous delivery has 50 % higher market capitalization growth over the 3 last years than the other and Gartner predicts that by 2020 50% of CIO’s that have not transformed their capabilities will be displaced.

Tutorial: How to use Angular CLI with DotNetCore

In this post we’ll explore how to use the Angular CLI to build an application hosted inside a DotNetCore.1.1 web api project. The code that accompanies this post can be found here.

1.      Create a new WebApi application

Open a command line and use the following commands to generate your WebApi project.

mkdir AngularDotNetCore
cd .\AngularDotNetCore\
dotnet new webapi

2.     Configure the WebApi project for Angular

    1. Open the project with Vs Code and edit the .csproj
    2. Disable the automated compilation of typescript as it will be handled by the Angular-cli (line 4)
    3. Add a reference to the Microsoft.AspNetCore.StaticFiles package so that we’ll be able to serve static files from the “/wwwroot” (line 13)
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp1.1</TargetFramework>
    <TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
  </PropertyGroup>

  <ItemGroup>
    <Folder Include="wwwroot\" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.2" />
  </ItemGroup>
  <ItemGroup>
   <DotNetCliToolReference Include="Microsoft.DotNet.Watcher.Tools" Version="1.0.0" />
  </ItemGroup>
</Project>

c. To install the new packages run:

dotnet restore

3. Modify Startup.cs

  1. Redirect all non API requests to the index.html page. (line 6-14)
  2. Configure the app to serve static files and use the index.html as default page. (line 17-23)
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.Use(async (context, next)=&amp;amp;amp;amp;gt;{
        await next();
        if (context.Response.StatusCode == 404 &amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;
            !System.IO.Path.HasExtension(context.Request.Path.Value) &amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;
            !context.Request.Path.Value.StartsWith("/api/")){
                context.Request.Path = "/index.html";
                await next();
            }
    });

    // use default route /api/[controller] 
    app.UseMvcWithDefaultRoute();

    // use index.html as default page
    app.UseDefaultFiles();
    
    // serve static pages
    app.UseStaticFiles();
}

3. Initialize the Angular App through Angular-CLI

  1. a. Install Angular-CLI
    npm install @angular/cli --global
    
  2. b. Create the Angular app
    ng new my-app --skip-install
    
  3. c. Move to the root all the content of your “my-app” folder
    mv .\my-app\* .\
    
  4. d. Delete the “my-app” folder:
  5. e. Define the “wwwroot” as the Angular-CLI output directory.
    Edit the .angular-cli.json and update the “apps” part (line 9):

    {
      "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
      "project": {
        "name": "my-app"
      },
    "apps": [
      {
        "root": "src",
        "outDir": "wwwroot",
        "assets": [
          "assets",
          "favicon.ico"
        ],
        "index": "index.html",
        "main": "main.ts",
        "polyfills": "polyfills.ts",
        "test": "test.ts",
        "tsconfig": "tsconfig.app.json",
        "testTsconfig": "tsconfig.spec.json",
        "prefix": "app",
        "styles": [
          "styles.css"
        ],
        "scripts": [],
        "environmentSource": "environments/environment.ts",
        "environments": {
          "dev": "environments/environment.ts",
          "prod": "environments/environment.prod.ts"
        }
      }
    ],
      "e2e": {
        "protractor": {
          "config": "./protractor.conf.js"
        }
      },
      "lint": [
        {
          "project": "src/tsconfig.app.json"
        },
        {
          "project": "src/tsconfig.spec.json"
        },
        {
          "project": "e2e/tsconfig.e2e.json"
        }
      ],
      "test": {
        "karma": {
          "config": "./karma.conf.js"
        }
      },
      "defaults": {
        "styleExt": "css",
        "component": {}
      }
    }
    
    
  6. f. Install the npm packages
    npm install
    
  7. g. Build and run the app
    ng build
    dotnet run
    
  8. If everything went fine you should see:

4. Call from Angular the WebApi backend

Here we’ll make a simple http call from our Angular application to our DotNetCore Web Api. We’ll query the generated example “ValuesController” from our Angular app and output the result onto our homepage. Because I want to make this example as simple as possible I make the call directly from the component but in a real application you’ll encapsulate this code into an Angular service.

  1. a. Edit the app.component.ts file:
    import { Component, OnInit } from '@angular/core';
    import { Http } from '@angular/http'
    @Component({
       selector: 'app-root',
       templateUrl: './app.component.html',
       styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {
       constructor(private _httpService: Http) { }
       title = 'app works!';
       values:string[] = [];
       ngOnInit() {
          this._httpService.get('/api/values').subscribe(values => {
             this.values = values.json() as string[];
          });
       }
    }
    
    
  2. b. Edit the app.component.html file:
    
    <h1>
      {{title}}
    </h1>
    
    
    
      Retrieved values:
    
    
    
    <ul *ngFor="let value of values">
      
    <li>{{value}}</li>
    
    </ul>
    
    
  3. c. Compile and run the app:
    ng build
    dotnet run
    

5. Configure your Angular application to auto update when code changes

The Angular-CLI can configure webpack to serve the application through his built-in server and refresh your page whenever a file changes. To launch this developer friendly mode use:

ng serve

Notice that when you open your browser on http://localhost:4200 (the webpack server default port) you don’t see any retrieved values anymore.

This is because our Angular application calls our REST API on http://localhost:4200/api/values but there’s nothing there! What we need to do is launch our WebApi application and redirect calls to it from port 4200.

  1. a. Create a “proxy.json” file on the root and add the following content to the file:
    {
       "/api": {
          "target": "http://localhost:5000",
          "secure": false
       }
    }
    
  2. b. Launch two consoles. One to run the webapi app:
    dotnet run
    

    The other to launch the webpack server with the proxy redirection:

    ng serve –proxy proxy.json
    
  3. c. You can also enable the auto refresh mode of your WebApi application. Edit the .csproj file and add following section and run “dotnet restore”:
      <ItemGroup>
       <DotNetCliToolReference Include="Microsoft.DotNet.Watcher.Tools" Version="1.0.0" />
      </ItemGroup>
    
  4. d. Now you can launch also the WebApi in watch mode:
    dotnet watch run 

Of course, you’ll still need to refresh your page every time you change your webapi project but it will recompile & run automatically every time code is changed.

Have fun!

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:

[snippet id=”371″]

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:

[snippet id=”381″]

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:

[snippet id=”321″]

3) Implement the server

A) Create a index.ts file:

[snippet id=”331″]

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:

[snippet id=”341″]

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:

[snippet id=”351″]

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:

[snippet id=”361″]

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
    [snippet id=”291″]
  3. Modify the program.cs file
    [snippet id=”301″]
  4. Add a Nunit test file: SampleTest.cs
    [snippet id=”311″]
  5. Start the test session with “dotnet run” , you can also launch the test project and debug it through VS2015.
    nunitdotnetrun