Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

.NET CORE 1.0, MVC6 & ANGULARJS2 - STARTUP

0.00/5 (No votes)
24 Nov 2016 1  
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

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 > Project

Choose empty template click > OK.

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

We will now explore all initial file one by one.

4. Explore Initial Template

Marked from solution explorer are going explored one by one.

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.

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.

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.

After save change it will automatically restore dependencies from NuGET.

Here the code snippet that I have changed.

"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

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.

"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

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

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

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

RuntimeOptions: Manage server garbage collection at application runtime.

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

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

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

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

"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.

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

Click Save.

It will start restoring the packages automatically.

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

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();

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.

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.

Output:

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.

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

{
  "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.

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

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.

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.

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

Gulp.json

/*
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.

Right click on copy-all & click Run.

Task run & finished as you can see.

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'".

Bootstrapping with TypeScript

tsConfig.json

{
  "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.

In solution explorer you may add files like below.

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

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.

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.

Now we will add reference to our layout page.

<!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

@{
    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.

app.UseStaticFiles();

7. Build & run application

Finally build & run the application

Here we can see our app is working with AngularJS2

Hope this will Help :)

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here