Click here to Skip to main content
15,867,141 members
Articles / Web Development / ASP.NET / ASP.NETvNext

.NET CORE 1.0, MVC6 & ANGULARJS2 - STARTUP

Rate me:
Please Sign up or sign in to vote.
4.90/5 (31 votes)
24 Nov 2016CPOL7 min read 54.7K   1.2K   61   13
In this article we are going to explore .Net Core, Know how to use MVC6 & AngularJS2, how to manage client side dependencies with Node package manager (NPM).

Table of Content:

  1. Setup Environment
  2. Overview on ASP.Net
  3. Start with .Net Core 1.0.
  4. Explore Initial Template (Empty)
  5. How to Add MVC6
  6. AngularJS2
    1. Manage Client-side Dependencies
    2. Use Package Manager (NPM).
    3. Use Task Runner
    4. Bootstrapping using Type Script
  7. Build & run application

1. Setup Environment

Prerequisites: The following prerequisites are needed.

  1. Visual Studio 2015
  2. ASP.NET Core 1.0

Visual Studio 2015: If you already have a copy of Visual Studio 2015 installed, you may update Visual Studio 2015 with Update 3.

Or

Download Visual Studio Community 2015 for free.

.NET Core Downloads:

You may download one of these:

  1. .NET Core SDK  (Software Development Kit/Command Line Interface) tools
  2. .NET Core 1.0.0 - VS 2015 Tooling Preview 2 (Run apps with the .NET Core runtime)

We are all set to go. Before we dive into our main topic let’s get an overview on ASP.Net.

2. Overview on ASP.Net

Image 1

Let’s differentiate both.

.Net Framework:

  1. Developed and run on Windows Platform only.
  2. Built on the .NET Framework runtime.
  3. Supported (MVC, Web API & SignalR) Dependency Injection (DI).
  4. MVC & Web Api Controller are separated.

 .Net Core:

  1. Open Source.
  2. Developed & run on Cross Platform.
  3. Built on the .NET Core runtime & also on .NET Framework.
  4. Facility of dynamic compilation.
  5. Built in Dependency Injection (DI).
  6. MVC & Web Api Controller are unified, Inherited from same base class.
  7. Smart tooling (Bower, NPM, Grunt & Gulp).
  8. Command-line tools.

3. Start with .Net Core 1.0

Let’s create a new project with Visual Studio 2015 > File > New > ProjectImage 2

Choose empty template click > OK.Image 3

Visual Studio will create a new project of ASP.Net Core empty project.

Image 4

We will now explore all initial file one by one.

4. Explore Initial Template

Marked from solution explorer are going explored one by one.

Image 5

First of all we know about program.cs file. Ok let’s concentrate on it.

Program.cs: Here we have sample piece of code let’s get explanation.

C#
namespace CoreMVCAngular
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }
    }
}

.UseKestrel() : Define the web server. ASP.NET Core supports hosting in IIS and IIS Express.

HTTP servers:

  1. Microsoft.AspNetCore.Server.Kestrel (cross-platform)
  2. Microsoft.AspNetCore.Server.WebListener (Windows-only)

.UseContentRoot(Directory.GetCurrentDirectory()) : Application base path that specifying path to root directory of the application.

.UseIISIntegration() : For hosting in IIS and IIS Express.

.UseStartup<Startup>() : Specifies the Startup class.

.Build() : Build the IWebHost that will host the app & manage incoming HTTP requests.

Startup.cs: This is the entry point of every .Net Core application, provide services that application required.

C#
namespace CoreMVCAngular
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            
        }
    }
}

As you can see there are two methods one is ConfigureServices & another is Configure. In Configure method, three parameters are specified.

IApplicationBuilder defines a class that provides the mechanisms to configure an application's request.

We can add MVC (middleware) to the request pipeline by using “Use” extension method, later we will use it.

ConfigureServices is a public method that configure to use several services.

Project.json: This is where our application dependencies listed here by name & version. This file also manage runtime, compilation settings.

Dependencies: all application dependencies here, we can add new dependencies if required, intellisense will help up to include with name & version.

Image 6

After save change it will automatically restore dependencies from NuGET.

Image 7

Here the code snippet that I have changed.

C#
"dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.0",
      "type": "platform"
    },
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",

    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.0"
  },

To uninstall go to Solution explorer > right click on package > Uninstall package

Image 8

Tools: This section manage & list command line tools, we can see IISIntegration.Tools is added by default which is a tools that contain dotnet publish iis command for publishing the application on IIS.

C#
"tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
  },

Frameworks: As we can see initially our app is running on the .NET Core platform by default with runtime Code

C#
"frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },

Build Options: Options that are passed to compiler while build application.

C#
"buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

RuntimeOptions: Manage server garbage collection at application runtime.

C#
"runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

PublishOptions: This define the file/folder to include/exclude to/from the output folder while publish the application.

C#
"publishOptions": {
    "include": [
      "wwwroot",
      "web.config"
    ]
  },

Scripts: Scripts is object type which specifies that scripts to run during build or publish the application.

C#
"scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }

5. Add MVC6

It’s time to add MVC6. In .NET Core 1.0 MVC & Webapi are unified, become single class which inherit from same base class.

Let’s add MVC service to our application. Open project.json to add new dependencies in it. In dependencies section add two dependencies.

C#
"Microsoft.AspNetCore.Mvc": "1.0.0",
"Microsoft.AspNetCore.StaticFiles": "1.0.0" //Serving static file

Click Save.

Image 9

It will start restoring the packages automatically.

Image 10

Now let’s add MVC(midleware) to request pipeline in Config method at startup class.

C#
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    //app.UseStaticFiles();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

In ConfigureServices method, we need to add framework service. we have added services.AddMvc();

C#
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
}

MVC Folder Structure: 

Let’s add MVC folder structure to our sample application. We have added view files in views folder & MVC controller in Controllers folder like old MVC application.

Image 11

Here you may notice that there is a new file in views folder “_ViewImports.cshtml”, this file is responsible for setting up namespaces that can be accessed by the views in project, which was previously done by the web.config file in the views folder.

We are almost done. Let’s modify our view content with welcome message.Now run the application, as you can see welcome message is appear in home page.

Image 12

Output:

Image 13

6. AngularJS2

AngularJS2 is a modern Client end JavaScript Framework for application development. This JavaScript Framework is totally new & written based on TypeScript.

We will follow the below steps to learn how we install it to our application:

  1. Manage Client-side Dependencies
  2. Use Package Manager (NPM).
  3. Use Task Runner
  4. Bootstrapping using Type Script

Client-side Dependencies: We need to add a json config file for Node Package Manager(NPM). Click add > New Item > Client- Side > npm Configuration File then click Ok.

Image 14

Open our newly added npm config file and modify initial settings.

C#
{
  "version": "1.0.0",
  "name": "asp.net",
  "private": true,
  "Dependencies": {
    "angular2": "2.0.0-beta.9",
    "systemjs": "0.19.24",
    "es6-shim": "^0.33.3",
    "rxjs": "5.0.0-beta.2"
  },
  "devDependencies": {
    "gulp": "3.8.11",
    "gulp-concat": "2.5.2",
    "gulp-cssmin": "0.1.7",
    "gulp-uglify": "1.2.0",
    "rimraf": "2.2.8"
  }
}

In dependencies section we need to add AngularJS2 with others dependencies, here what are they for:

  1. Es6-shim : is a library, provides compatibility on old environment.
  2. Rxjs : provide more modular file structure in a variety of formats.
  3. SystemJS : enables System.import TypeScript files directly.

As you can see there are two different type object, one is dependencies that used for production purpose & other one is devDependencies for development related, Like gulp is to run different task.

Click save, it will restore automatically. Here we have all our required packages in Dependencies section.

Image 15

In this application we have added another package manager called Bower, Click add > New Item > Client- Side > Bower Configuration File then click Ok.

Image 16

Comparing with NPM,

Bower:

  1. Manage html, css, js component
  2. Load minimal resources
  3. Load with flat dependencies

NPM:

  1. Install dependencies recursively
  2. Load nested dependencies
  3. Manage NodeJS module

Open the config file then add required dependencies in dependencies secction with specific version.

Image 17

Save the JSON file after edit, it will automatically restore that package in our project. Here you can see we have added Jquery & Bootstrap package with Bower package manager.

Image 18

Now let’s add a gulp configuration file to run task. Click Add > New Item > Client-Side then select gulp json file to include.

Image 19

Gulp.json

C#
/*
This file in the main entry point for defining Gulp tasks and using Gulp plugins.
Click here to learn more. http://go.microsoft.com/fwlink/?LinkId=518007
*/

"use strict";

var gulp = require("gulp");
var root_path = { webroot: "./wwwroot/" };

//library source
root_path.nmSrc = "./node_modules/";

//library destination
root_path.package_lib = root_path.webroot + "lib-npm/";

gulp.task("copy-systemjs", function () {
    return gulp.src(root_path.nmSrc + '/systemjs/dist/**/*.*', {
        base: root_path.nmSrc + '/systemjs/dist/'
    }).pipe(gulp.dest(root_path.package_lib + '/systemjs/'));
});

gulp.task("copy-angular2", function () {
    return gulp.src(root_path.nmSrc + '/angular2/bundles/**/*.js', {
        base: root_path.nmSrc + '/angular2/bundles/'
    }).pipe(gulp.dest(root_path.package_lib + '/angular2/'));
});

gulp.task("copy-es6-shim", function () {
    return gulp.src(root_path.nmSrc + '/es6-shim/es6-sh*', {
        base: root_path.nmSrc + '/es6-shim/'
    }).pipe(gulp.dest(root_path.package_lib + '/es6-shim/'));
});

gulp.task("copy-rxjs", function () {
    return gulp.src(root_path.nmSrc + '/rxjs/bundles/*.*', {
        base: root_path.nmSrc + '/rxjs/bundles/'
    }).pipe(gulp.dest(root_path.package_lib + '/rxjs/'));
});

gulp.task("copy-all", ["copy-rxjs", 'copy-angular2', 'copy-systemjs', 'copy-es6-shim']);

To run the task right click on Gulp.json file the reload.

Image 20

Right click on copy-all & click Run.

Image 21

Task run & finished as you can see.

Image 22

In solution explorer all required package is copied. We also need to put the type definitions for es6-shim(typing folder), without this, it will cause error - "Cannot find name 'Promise'".

Image 23

Bootstrapping with TypeScriptImage 24

tsConfig.json

C#
{
  "compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5",

    //add this to compile app component
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "module": "system",
    "moduleResolution": "node"
  },
  "exclude": [
    "node_modules",
    "wwwroot/lib"
  ]
}

noImplicitAny : Raise error on expressions and declarations with an implied ‘any’ type.

noEmitOnError : Do not emit outputs if any errors were reported.

Target : Specify ECMAScript target version: ‘es5’ (default), ‘es5’, or ‘es6’.

experimentalDecorators : Enables experimental support for ES7 decorators.

Get more details on Compiler option here.

Create an app folder for .ts file in wwwroot folder.

Image 25

In solution explorer you may add files like below.

Image 26

In main.ts the code snippet, that bootstrap AngularJS with importing the component.

C#
import {bootstrap}    from 'angular2/platform/browser';
import {AppComponent} from './app.component';
import {enableProdMode} from 'angular2/core';

enableProdMode();
bootstrap(AppComponent);

Component: imports the Component function from Angular 2 library, use of "export" that mean app component class can be imported from other component.

C#
import {Component} from 'angular2/core';

@Component({
    selector: 'core-app',
    template: '<h3>Welcome to .NET Core 1.0 + MVC6 + Angular 2</h3>'
})
export class AppComponent { }

MVC View: it’s time to update our layout & linkup the library.

Image 27

Now we will add reference to our layout page.

HTML
<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>

    <script src="~/lib-npm/es6-shim/es6-shim.js"></script>
    <script src="~/lib-npm/angular2/angular2-polyfills.js"></script>
    <script src="~/lib-npm/systemjs/system.src.js"></script>
    <script src="~/lib-npm/rxjs/Rx.js"></script>
    <script src="~/lib-npm/angular2/angular2.js"></script>
</head>
<body>
    <div>
        @RenderBody()
    </div>
    @RenderSection("scripts", required: false)
</body>
</html>

Index.cshtml

HTML
@{
    ViewData["Title"] = "Home Page";
}
<core-app>
    <div>
        <p><img src="~/img/ajax_small.gif" />  Please wait ...</p>
    </div>
</core-app>

@section Scripts {
    <script>
        System.config({ packages: { 'app': { defaultExtension: 'js' } }, });
        System.import('app/main').then(null, console.error.bind(console));
    </script>
}

One more thing to do is enable static file serving. Add this line to startup config method.

JavaScript
app.UseStaticFiles();

7. Build & run application

Finally build & run the application

Image 28

Here we can see our app is working with AngularJS2

Image 29

Hope this will Help :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) s3 Innovate Pte Ltd
Bangladesh Bangladesh
Hi, I am Shashangka Shekhar,

Working with Microsoft Technologies. Since March 2011, it was my first step to working with Microsoft Technologies, achieved bachelor’s degree on Computer Science from State University of Bangladesh(Dhaka). Have 12+ years of professional experience, currently working as Technical Lead at Surbana Jurong Private Limited.

I believe in desire of learning & also love to be a part of .Net Community by sharing knowledge’s.

Comments and Discussions

 
QuestionTypescript cannot find module "angular2/core" and "angular2/platform/browser" Pin
Diogo-Queiroz21-Feb-17 17:02
Diogo-Queiroz21-Feb-17 17:02 
PraiseGreat Pin
ED195424-Nov-16 10:23
ED195424-Nov-16 10:23 
GeneralRe: Great Pin
Shashangka Shekhar24-Nov-16 18:06
professionalShashangka Shekhar24-Nov-16 18:06 
GeneralMy vote of 5 Pin
Member 1082614913-Aug-16 18:46
Member 1082614913-Aug-16 18:46 
GeneralRe: My vote of 5 Pin
Shashangka Shekhar13-Aug-16 19:05
professionalShashangka Shekhar13-Aug-16 19:05 
GeneralMy vote of 5 Pin
Shamim Uddin12-Aug-16 20:48
professionalShamim Uddin12-Aug-16 20:48 
GeneralRe: My vote of 5 Pin
Shashangka Shekhar12-Aug-16 20:55
professionalShashangka Shekhar12-Aug-16 20:55 
QuestionJust a minor corrections Pin
Samir Chakour4-Aug-16 9:03
Samir Chakour4-Aug-16 9:03 
Thanks for the article, its a really a simple start, I get just a few issues after following it :

1. on the package.json file the entry "Dependencies" should be replaced by "dependencies" so that npm could correctly load the specified packages, elsewhere all the packages specified on that entry would not be loaded and gulp will copy nothing to the lib-npm directory.

2. on the tsconfig.json file you should target the "es6" instead of "es5", in my case I am getting the below errors when targeting 'es5' :

JavaScript
 TS2304: Cannot find name 'Promise'.
 TS2304: Cannot find name 'Map'.
 TS2304: Cannot find name 'MapConstructor'.
 TS2304: Cannot find name 'Set'.

AnswerRe: Just a minor corrections Pin
Shashangka Shekhar4-Aug-16 9:15
professionalShashangka Shekhar4-Aug-16 9:15 
QuestionA Good start Pin
buckrogerz4-Aug-16 6:06
buckrogerz4-Aug-16 6:06 
AnswerRe: A Good start Pin
Shashangka Shekhar4-Aug-16 7:26
professionalShashangka Shekhar4-Aug-16 7:26 
GeneralRe: A Good start Pin
buckrogerz4-Aug-16 8:17
buckrogerz4-Aug-16 8:17 
GeneralRe: A Good start Pin
Shashangka Shekhar4-Aug-16 8:38
professionalShashangka Shekhar4-Aug-16 8:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.