Creating an App with .NET Core by using MVC 6 & AngularJS

Hesam Seyed Mousavi, May 28, 2017

Developed by Microsoft, .NET framework is a programming infrastructure used for building, deploying and running applications that use .NET technologies. It can provide the required compile time and runtime foundation for building and running languages that conforms to Common Language.

Hesam_Seyed_Mousavi_MVC 6 & AngularJS

The three major parts of .NET framework are

  • Common Language Runtime (CLR)– Features include system services like managing memory, thread execution, code safety verification, compilation and code execution.
  • Framework Class Library — the foundation of .NET framework
  • ASP.NET — Works directly with runtime to enable XML Web applications and ASP.NET applications.

The main purpose of .NET framework is to provide a reliable object-oriented programming, code execution environment that solves conflicts involves version changes and aids in minimizing software deployment.

It promotes safe execution of code even if the code is scripted by an unknown party. .NET also helps in building all communication based on industry standards so the codes based on .NET framework can be integrated with any code.

.NET Core is a general purpose, open source, cross-platform implementation of .NET platform; maintained by Microsoft and the GitHub community. As it is cross platform, it can support all formats like Windows, Linux, Mac OS and in devices, cloud services and most importantly in embedded/IoT devices.

Developers will have access to a library that can be easily deployed across platform. .NET Core makes it easier for developers to import parts of a framework.

There are two major components in .NET Core. They are Runtime, which is built on the same code base as .NET framework CLR and Base class libraries which are the same code as the .NET framework class libraries, but without the dependencies.

Fully open source at GitHub, ASP.NET framework is perfect for building web and cloud applications. It runs on Windows, .NET framework and cross platform .NET Core. The framework combines both ASP.NET MVC and Web API into a single programming model.

The framework is well known for its concept compatibility with ASP.NET MVC. It is a significant redesign of ASP.NET and is mostly used for developing modern web apps. ASP.NET Core is based on a set of granular and well factored NuGet packages and no longer on System.web.dll, making it easier for including only the NuGet packages that you need. This improves security, reduces costs (pay-for-what-you-use model) and improves performance.

Main Features of .NET Core

Being a general purpose platform maintained by both Microsoft and the GitHub community, .NET comes with a variety of features for the developers. Let’s go through them.

1. Cross Platform

One of the best features of .NET Core is that it is cross-platform; meaning it can run on Windows, Mac OS, Linux and even ported to other operating systems. The supported operating systems are expected to grow over time, both for those provided by Microsoft and the ones provided by other companies.

2. Free and Open Source

.NET Core, one of the projects of the .NET Foundation is open source and hence available on GitHub. A more transparent development process is possible, thanks to a vibrant and very active community.

3. Versatile Deployment

The deployment process of .NET is highly flexible. You can do it in two ways: Framework-dependent deployment or Self-contained deployment.

a) In Framework dependent deployment or FDD, it is important for the target system to have a shared system wide version of .NET Core. Porting your app between different installations of .NET Core is possible. As it is framework dependent, only the app’s own code and third-party dependencies, outside of the .NET Core libraries will be present in the app.

b) This is different in Self-contained deployments (SCDs). You are deploying not just your apps and all the relevant third-party dependencies, but also the version of the .NET Core with which you created your app. You can decide on the version of .NET Core deployed in your app. The most important thing here is that you have the guarantee that the target system will run your app.

4. Modular

As .NET Core is released through NuGet in compact assembly packages, you can say that .NET Core is modular. Small feature-centric packages are always better than one large assembly with few of the core functionalities.

And the other advantage of being modular is that you can have an agile development model, that allows you to customize your NuGet packages to include only what is needed. This leads to tighter security, improved performance and reduced cost.

5. Compatible

Microsoft has made .NET Core compatible with .NET framework, Xamarin and Mono.

6. Fast

.NET Core is 8 times faster than Node.js, and 3 times faster than Go, leading to better response time and lesser compute time.

7. Unified Code Framework

.NET Core has a unified code framework that combines MVC and Web API controllers as a single programming model, leading to a functional improvement of the framework.

8. Built-in Dependency Injection

There is built-in support for dependency injection, making it easier for developers to test and maintain the applications easily. Dependency injection is a technique that allows for applications to be integrated with loosely coupled modules.

Components of .NET Core

The components of .NET Core can be used together or separately. And the purpose of these components is to enhance the capabilities of .NET framework. Have a look at a few of its components. Please note, this is not an exhaustive list.

The .NET repositories on Github contains these components.

1. .NET runtime

Also known as CoreCLR. The repository is integrated with complete source code and can be updated to fix bugs and add features. Though it is part of Windows Operating System, it is a cross platform and cross architecture subset which you can deploy as part of the application.

2. .NET Core Foundational libraries

Also known as CoreFX, NET Core Foundational libraries contains several components including System.Collections, System.IO, System.Xml.

3. .NET Command Line Tools

.NET Core command-line interface (CLI) is a new foundational cross-platform tool chain with which developers can develop .NET Core applications. As it is foundational, it is the primary layer on which other high-level tools like Integrated Development Environments can be built on.

4. .NET Compiler Platform — Roslyn

The primary function of Roslyn is to open up C# and Visual Basic compilers so that information can be shared among tools and developers when they develop programs. When tools get smarter and more complex, they need to make use of the huge repository of information present in the compilers. The APIs in Roslyn compilers help developers to use code-related tasks in their tools and applications.

5. .NET app host — Amazon Web Services

It is possible to build and deploy your .NET web applications on AWS (Amazon Web Services) Elastic Beanstalk with the help of AWS toolkit for Visual Studio, an extension of Microsoft’s Visual Studio (which will be discussed later). All you need to do is deploy the code and Elastic Beanstalk can easily handle the deployment, scale your application right through your application’s unique requirements by using Auto Scaling settings.

Quick Overview of AngularJS 2

Before going deep into the process of creating an app with .NET Core, let’s take a quick look at AngularJS 2.

Released in March 2014, AngularJS 2, the front end JavaScript framework (cross platform) based on TypeScript, is much simpler and easier than Angular 1. It is fast because it speeds up the initial load through server side rendering. Angular 2 is also much easier to learn than Angular 1 which has a steep learning curve.

As it is a cross-platform framework focused mainly on mobile apps, it supports the latest browsers including Android 4.1+ and IE9+. Angular 2 helps you to update big sets of data with few minimal overhead.

It works optimally with ECMAScript and other JavaScript compiling languages like ES5, ES6, Dart, etc. It saves developer time in two ways:
(1) by having a simple code structure and
(2) by eliminating the need for writing too many codes, thanks to the deployment of dependency injection. If the application is a heavy load file, Angular 2 makes the UI responsive and quick.

Angular 2 has the upper hand over Angular 1 in the fact that it directly uses the valid HTML DOM elements properties and events. Even though ASP.NET Core is capable of generating HTML on its own (for client side of the application), the presence of Angular 2 makes it even easier.

It helps you build a responsive and interactive client-side application through component based architecture. To enhance the performance value of Angular 2 UI dependencies without jQuery dependencies, developers use Kendo UI. It has got more than 15 beautiful UI controls for you to choose from.

Visual Studio Code — Code Editing Redefined!

You can work with AngularJS 2 with Typescript in ASP.NET MVC 6 by using Microsoft Visual Studio to build highly intuitive apps. The relative safety of Visual Studio is what makes developers choose it to create new projects. With TypeScript and Microsoft Visual Studio Code, developers can write efficient codes so that they can be assured their product will work successfully in user devices.

Microsoft Visual Studio is free, lightweight and open source that helps developers make apps for any platform. The major highlight is that you can write accurate codes without worrying about losing the current file context.

The efficiency of the Visual Studio extends to details of app making, including inspecting API definitions, bug detection, fixing code issues and quick info tools. It helps you navigate your way around a huge code base.

There is an enhanced scrollbar that gives you a 10,000 foot structural view of your code to let you instantly detect problems. Additionally, there is a Solution Explorer feature integrated with inline object browsing capabilities that would help you search files quickly.

Bugs are identified and fixed instantly with light bulb icons and a specific Error List. Thanks to the highly efficient Integrated Development Environment (IDE), restructuring and refactoring someone else’s code is a piece of cake.

Visual Studio 2017, the newest kid on the block is aimed at streamlining your inner loop and speeding up code flow with enhanced features like live unit testing, real time architectural dependency validation, apart from other enhancements. These changes include better code navigation, debugging and saving code fixing time.

Visual Studio 2017 aims to enhance the way daily tasks are done, where developers can enjoy a brand new lightweight and modular installation to a blazingly quick IDE, including innovative ways to fix issues and debug codes. It allows you to build and deploy services and applications on to Microsoft Azure right from IDE.

Creating an App in .NET Core using MVC 6 and AngularJS 2 — in detail

Explore how to build an app in .NET core with MVC 6 and AngularJS 2 through this detailed process.

For setting up the environment, the following prerequisites are required:

  1. Visual Studio 2015 (the updated version)
  2. ASP.NET Core 1.0

For .NET Core, you can download any one of the following:

  1. .NET core SDK or Software Development Kit tools
  2. .NET Core 1.0.0-VS 2015 Tooling Preview 2 (Run apps with the .NET Core runtime)

Start with .NET Core 1.0

  1. To create a unique project with Visual Studio 2015, click File > New > Project.
  2. Click OK on the Empty Template
  3. A new project of ASP.NET Core empty project will be created by Visual Studio

The following are the files displayed in the initial template of ASP.NET Core. Let’s explore the files marked from Solution Explorer one by one.

Program.cs

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

Here .UseKestrel() defines the Web Server ASP.NET Core supports hosting in IIS and IIS Express.

There are two types of HTTP Servers — Microsoft.AspNetCore.Server.Kestrel (cross-platform) and Microsoft.AspNetCore.Server.WebListener (Windows-only)

.UseContentRoot(Directory.GetCurrentDirectory()) : Application base path that specifies the path to the root directory of the Application.
.UseIISIntegration() : For hosting in IIS and IIS Express.
.UseStartup() : Specifies the Startup class.
.Build() : Builds the IWebHost – hosts the app & manage incoming HTTP requests.

Startup.cs
This is the entry point of every .NET Core application. It provides services that the application requires.

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) {}  
    }  
}

Here, there are two methods: ConfigureServices and Configure. In Configure method, three parameters are specified. IApplicationBuilder defines a class, which provides the mechanisms to configure an Application’s request.

MVC (middleware) can be added to the request pipeline by using “Use” extension method. Later, we will use it.

ConfigureServices is an extension method, which is configured to use the several services.

Project.json
Application dependencies are listed here i.e by name & version. This file also manages runtime and compilation settings.

Dependencies
All Application dependencies can add new dependencies, if required, IntelliSense will help us to include with the name & version.

After saving changes, it will automatically restore the dependencies from NuGet.

Now, the code snippet is 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 manages and lists Command Line Tools (CLI). IISIntegration.Tools, a tool that contains dotnet publish iis command for publishing the Application on IIS is added by default.

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

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

Build Options: Options, which are passed to the compiler while building the Application.

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

RuntimeOptions: Manage Server garbage collection at Application runtime.

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

PublishOptions: This defines the file/folder to include/exclude to/from the output folder, while publishing the Application.

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

Scripts: Scripts is an object type, which specifies that scripts run during building or publishing the Application.

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

Add MVC 6

Now, let’s add MVC 6. We know in .NET Core 1.0, MVC & Web API are unified, and become a single class which inherits from the same base class.

To add MVC service to our application, do the following:
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”.

Next, click Save. It will start restoring the packages automatically.

Now let’s add MVC (middleware) 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

Now add MVC folder structure to the sample Application. We have added view files in the views folder & MVC controller in Controllers folder just like old MVC Application.

Here, there is a new file in the views folder “_ViewImports.cshtml”. This file helps in setting up the namespaces, which can be accessed by the views in the project. This work was previously done by the Web.config file in the views folder.

It’s almost done. Modify the view content with the welcome message. Now, run the Application. A welcome message appears in the home page.

Output : Hello .NET Core 1.0 + MVC6

Installing AngularJS 2

For installing AngularJS 2 in our application, follow these steps:
1. Manage Client-side Dependencies
2. Use Package Manager (NPM)
3. Use Task Runner
4. Bootstrapping using TypeScript

Client-side Dependencies: Add a JSON config file for Node Package Manager(NPM). Click add > New Item > Client- Side > npm Configuration File and click OK.

Next, open the newly added npm config file and modify the 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 the dependencies section, add AngularJS 2 with other dependencies:

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

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

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

Open the config file, then add required dependencies in the dependencies section with specific version.
Save the JSON file after edit, it will automatically restore that package in our project. Jquery & Bootstrap package are added with Bower package manager.

Now, let’s add a gulp configuration file to run the task. Click Add > New Item > Client-Side. 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']);  Thanks for you time.

To run the task, right click on Gulp.json file to reload.
Right click on copy-all & click run.
Task run & finish.

In Solution Explorer, all the required packages are copied. Don’t forget 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 : Raises an error on the 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 an experimental support for ES7 decorators.

Create an app folder for .ts file in wwwroot folder. In Solution Explorer, you may add the files, given below.

In main.ts code snippet, 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 import, app component class can be imported from other component.

import {Component} from ‘angular2/core’;

@Component({  
    selector: 'core-app',  
    template: '

Welcome to .NET Core 1.0 + MVC6 + Angular 2

' }) export class AppComponent {}

MVC View

It’s time to update our layout & linkup the library.

Now, add the reference to our layout page.

 
<html> 
 
<head> 
    <meta name="viewport" content="width=device-width" /> 
    <title>@ViewBag.Titletitle> 
    <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>

app.UseStaticFiles();

Finally, build & run the Application.

Now, we have built an app in .NET Core using MVC 6 and AngularJS 2.

Credits: C#Corner

In Closing

As you must have garnered from above, it’s easy to build an app with MVC 6 and AngularJS 2 in .NET Core. MVC 6 has proved to be the most reliable successor to Web API 2, Web Pages and MVC 5. And Angular JS 2 is a much better choice because it is more productive, boasts of a better structure and “confirmability”.

Combining both MVC 6 and Angular 2 would be perfect for building small applications. For the bigger ones, you need to separate the server and client part for best results, to make it easier to deploy.

Advertisements