It’s likely that this post will become out of date soon, as MVC 5 moves from preview to RTM. Due to the lack of good documentation on setting up an ASP vNext Web project, I’m detailing the steps I used — not least because I found the process confusing myself.

I have the luxury of creating a new Web project from scratch. Because I hope to be able to work on this for several years, I want to adopt technologies carefully. As much as possible, I want to avoid technology dependencies that I will regret using three or five years from now. This series documents my choices and what it took to get everything setup; hopefully it helps you move more quickly.

Like me, you have probably been excited to upgrade to the latest version of Visual Studio. The transition from VS 2005 onwards has been rewarded with incrementally better features and better tooling. Visual Studio 2015 will fool you into thinking that this is the same thing. Your existing projects will probably smoothly upgrade and you’ll be able to better manage your project.

Two Paths

What you won’t realize — because there are no warnings or flashing lights to this effect — is that there are really two paths in Visual Studio 2015. If you want to continue as before, then you can lean back in your comfy chair and continue to use Visual Studio 2015 just like you did before. There will be improvements to your development experience, just as you’ve come to expect from a Visual Studio upgrade. If you have a lot of legacy code, this may be the only viable path. However, if you’re creating a new project and just following the rutted tracks you’ve lain, you’ll be headed the wrong way.

If you are working with a new (or new-ish) project, switching to the DNX Core framework requires an almost complete re-education in how Visual Studio works. The world has changed; I found it both disorienting and breathtaking (which also sounds unbelievably nerdy when I hear myself actually say it). The good news is that I was able to get my existing MVC code changed within a couple of days (already using the Razor engine, so the switch was actually rather easy); the bad news is that it took far longer for me to understand the environment changes.

Since the help I needed was scattered throughout the internet, that adventure became the genesis of this article.

A secondary concern of mine was knowing how to keep my project dependencies current. Project dependencies are now being updated at completely independent release cycles. I want to take advantage of the latest bug fixes and performance improvements — when it’s smart to do so — so how should one track and update these components?

Web Tech Overview

To create a web page, you essentially need HTML for content, Cascading Style Sheets for layout, JavaScript for automation, and a backend server to render the page and also provide additional data as needed. In today’s development world, HTML, CSS, and JavaScript are the output, to be consumed by browsers; Razor, SASS, TypeScript, etc. are what developers use to create to generate that respective output.

Theoretically, could create HTML, CSS, and JavaScript directly — but, theoretically, you could program your web site in Assembly too. Modern Web development now functions at the higher level. And VS 2015 since exposes all of this, there is a lot to learn.

HTML • Razor

“Traditional” ASP.NET Web Forms are out. (And good riddance). The way forward was introduced in Visual Studio 2013 with the Razor engine. The big change for me was the transition from HtmlHelpers to TagHelpers in VS 2015.

CSS • SASS

The development world has moved to SASS for generating CSS files. Visual Studio 2015 supports SASS (.SCSS files), but it requires some extra setup to make it work.

Of course, our web should be responsive (i.e. automatically adjust to accommodate various screen sizes and mobile devices), which means using a responsive grid. The non-empty ASP.NET MVC project template in Visual Studio uses the Bootstrap 3 framework for its grid. That seems like a strong endorsement from Microsoft for Bootstrap. However, I personally don’t like how Bootstrap requires you to embed layout information in the HTML. HTML is for content; layout information should be in CSS files. I also don't have much need for Bootstrap’s controls and I prefer to avoid Bootstrap’s dependency on jQuery.

I looked around for a more amenable CSS-only grid. So far I am impressed with Susy, which is exactly what I wanted. This walkthrough will show you how to use Susy, but of course you can use whatever you like.

JavaScript • TypeScript

Despite its popularity, for professional developers, working in JavaScript was a huge step backwards. TypeScript changes all that. It provides type checking, Intellisense, and object-orientation (prior to EC6). I am no longer willing to create JavaScript without using TypeScript.

Furthermore, the JavaScript framework that I am most excited to use is Angular 2, which is actually written in TypeScript. I’m including Angular 2 setup in this walkthrough.

The Server Engine

The change from legacy .NET to .NET DNX is pretty substantial. Frankly, I found understanding how DNX worked harder than making the necessary code changes to account for missing framework objects.

For me, the logic of switching to DNX has less to do with running on Linux or OSX than with cloud hosting generally, especially Azure.

Also: Testing

Currently, you cannot create tests against the DNX Core framework using MSTest. The means a migration to xUnit.

That's a lot of (poorly documented) changes. Much of what I knew about setting up a Visual Studio Web project is now wrong; and VS templates are really not helpful in getting things setup.

Solution Strategy

Visual Studio project types are optimized for certain tasks, and there isn’t a way to include the full functionality from a different type into a project of a different type. So, for example, a SQL Server Database Project has functionality for working SQL; if you want that functionality, you need to add separate SQL project to your solution. The same thing is basically true of TypeScript also.

Unexpectedly (to me), ASP.NET DNX projects and traditional ASP.NET projects are also different project types. Like me, you are probably used to upgrading the targeted .NET framework (from, say, .NET 4.0 to 4.5). You can’t do that with .NET 5! They are different project types.

A complete web solution will need multiple projects, including (an optional) one for database work, one for TypeScript (but not the one you think), one for shared components, like TagHelper controls, and (at least) one for tests.

Setup Steps

Visual Studio Components

1. Install Visual Studio 2015

I am using the Enterprise Edition, well, because I can. If you are using Professional or Community editions, I assume that this walkthrough may work for you, but I haven’t tested it.

2. Install the “ASP.NET” Visual Studio Extension

This is an example of how I suspect future functionality will be delivered. Visual Studio 2015 RTM does not natively handle ASP.NET projects? Really?  You have to install the ASP.NET extension.

Within Visual Studio, click on the Tools menu and select the Extensions and Updates... menu item. In the dialog window that appears, search for “ASP.NET”. One of the top results should be Microsoft ASP.NET and Web Tools. Click on the list item to select it. When you do so, an Install button should appear. Click the Install button and follow whatever instruction follow.

If you have already installed the extension, the Install button will be replaced with Disable and Uninstall buttons.

3. Install “Web Essentials 2015”

Technically, this isn’t required for our Web project, but if you’re working on a Web functionality, it would be silly to not include this great extension.

Follow the instructions for the previous item, substituting “Web Essentials” for “ASP.NET” in your search.

4. Install the Newest TypeScript Version

TypeScript is installed with Visual Studio, but you should ensure that you start your project with the latest version. You can download the latest version here.

5. Update the .NET Updater

The first step is to update the “Dot Net Version Manager” (DNVM) itself, since the Visual Studio 2015 RTM version manager has some issues.

Open a command window (this does not need an Administrator token), and run the following commands:

dnvm install
dnvm update-self

6. Update the .NET DNX Core Framework

To simply get the latest version of the .NET Core framework, run the following command in your command window (already opened from the previous step):

dnvm install latest

You can also, use this to specify a specific framework. For initial development, I prefer to always start with the latest.

If you don’t update the updater first (see previous step), this will not work (guess how I know).

7. Create an ASP.NET MVC 5 Project

Within Visual Studio 2015, create a new solution. You will be prompted for the project type. Select the Web project type, then select ASP.NET Web Application.

In the first dialog, select Web, then ASP.NET Web Application.

In the subsequent dialog, select an Empty ASP.NET 5 Preview Template, then click OK.

Of course, you can select one of the other preview templates, but you may find yourself cleaning out more than you keep. I found it easier to understand what was happening with the blank project.

Note that you cannot convert one Visual Studio project type to another (or merge project types). So if you’ve previously started with an ASP.NET 4.x template, you can’t make that a DNX project.

8. Update your project framework

Now we need to tell Visual Studio to use the framework we downloaded in step 6.

In Solution Explorer, right-click on the project name and select Properties in the pop-up menu (or Alt+Enter). In the Properties window, ensure the Application left-hand tab is highlighted. The combo-box labeled “Solution DNX SDK version:” allows you to select among the installed .NET DNX frameworks.

If the latest framework is already selected, you’re done. Otherwise, select the latest framework, then save your changes (ctrl+S, or click the disk icon on the toolbar).

9. Update your project dependencies

If you updated the framework version, it is quite likely that many of the project dependencies will also need to be updated.

Within your Visual Studio project, open the project.json file. In the section labeled "dependencies", you will see a list of library references and a version number. Select the opening double-quote in the version string, then type a double-quote character (essentially replacing the double-quote with the double-quote you just typed). A popup window should appear, listing available versions of the named dependency. Select the latest one (or the one the corresponds to your current framework).

Repeat this until each dependency has been updated. When you save the project.json file, Visual Studio will update its references list to reflect the newer components.

10. Update Visual Studio’s node engine

The automation scripts we will later require need a newer version of the node engine. The one that ships with Visual Studio is already outdated and will cause the tools to fail.

On Visual Studio’s Tools menu, select the Options menuitem. That should open the Options dialog. Expand the Projects and Solutions navigation node, then select External Web Tools.

Reorder the items in the location list so that $(PATH) is higher than the Extensions folders (as illustrated in the picture).

Click OK to save this change.


Setup TypeScript and Angular2

An earlier version of this post explained how to create a separate project for your TypeScript work using the built-in “TypeScript” project templates. The purpose was to manage TypeScript with the nice UI in the project properties. Don’t do this!

You can certainly create and compile TypeScript files in a “TypeScript Project” — and the TypeScript settings in the project properties are handy — but you will not get this to work with Angular2! I spent a long time trying; you can get part-way there, but the solution will be fragile and frustrating.

The key to getting Angular2 to work with your TypeScript project is to use the same ASP.NET 5 Core DNX project type (i.e. without the TypeScript tab in the project properties), rather than the legacy .NET 4.5 ASP.NET project. This gives you access to the tsconfig.json and package.json files you need to get Angular2 working (these files are not allowed in a legacy ASP.NET project).

In other words, the nice TypeScript tab UI in a “TypeScript Project” hides as much as it helps. To get something as complicate as Angular2 to work, you need access to the real TypeScript configuration files. Because of the many TypeScript configuration steps involved in setting up Angular2, the setup for both TypeScript and Angular2 are combined in this walkthrough.

11. Modifying the Project for TypeScript

Using a new or existing ASP.NET 5 web project, open the project.json file. In the “dependencies” section, add a new line for “Microsoft.AspNet.StaticFiles", specifying the current DNX version.

The dependencies section should look something like this:

"dependencies": {
"Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
"Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final"
},

Next, open the Startup.cs file in the Visual Studio editor. If the Configure method doesn’t have the following lines, add them:

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

If this is a web new project dedicated to serving JavaScript files, you can delete the other code within the Configure method. Only those two lines are necessary to render scripts and static pages.

12. Add a TypeScript Folder and Configuration file

Add a “scripts” folder to your project by right-clicking the project name, and selecting Add, then New Folder from the popup menus.

This folder will contain your TypeScript files. A “scripts” folder isn’t technically necessary and you can certainly manage your TypeScript files from the project root or a different folder name, if you’d prefer. If so, just be sure to keep the items destined for the “scripts” folder together.

With the scripts folder selected (or whatever), right-click on the folder and select Add, then New Item... from the popup menu. In the Add New Item dialog, select TypeScript JSON Configuration File. Do not change the filename. Click the Add button.

Incidentally, the presence of this file in the “scripts” folder will make the “scripts” folder the root of your TypeScript project.

Open the tsconfig.json file you just created, then modify the contents so it looks like this:

{
"compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5",
    "outDir": "../wwwroot/app",
    "module": "system",
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
},
"exclude": [
    "node_modules",
    "wwwroot"
]
}

A couple of notes:

  • The “outDir” line causes TypeScript to place the JavaScript result in the wwwroot folder. If you want to place these in a dedicated folder, just add the folder and add the folder to the path.
  • "experimentalDecorators" and "emitDecoratorMetadata" allow TypeScript to compile Angular2 code.
  • In the Angular2 Quick Start, they specify that the “module” should be “system”. That doesn’t work in Visual Studio; “CommonJs” does.

13. Adding Angular2 to the Project

Next, add a “NPM Configuration File” to your project, if one does not already exist. Do this by right-clicking on the project and selecting Add, then New Item... from the popup menus. In the resulting dialog window, select NPM configuration File, don’t change the default filename, and click the Add button to create the file.

Open the package.json file you just created. By adding a “dependencies” section, we’ll cause Visual Studio to include these files in our project.

Here’s what the package.json file should look like, with the dependencies section included:

{
"name": "MyTypeScriptProject",
"version": "1.0.0",
"private": true,
"dependencies": {
"angular2": "^2.0.0-beta.1",
"es6-shim": "^0.34.1",
"systemjs": "^0.19.6"
},
"devDependencies": {
}
}

Of course, your project might have some additional items listed.

As you save the package.json file, select the Show All Files icon in Solution Explorer, or just open the project file location. You should see a “node_modules” folder created on the file system. (This will not be included in your project).

In Solution Explorer, under the Dependencies node of your project, you should see several new items listed. These will include “angular2”, and also items like “rxjs” and “systemjs”. If you don’t see these listed, you may need to force the download of these items. To do this, open a command window and change the current path to your project root. At the command prompt, type “npm install”.

Some early online guidance will direct you to create a typing folder and load the TypeScript definitions for Angular2 and the others. This is no longer necessary. The TypeScript definition files are now included with the npm install.

14. Testing with the Angular2 “Quick Start”

To validate that this is working we can create a simple test using the “Quick Start” code on the Angular2 website.

Select the scripts folder, then open the Add New Item dialog twice to create two new TypeScript files. Name the first one “app.ts” and the second one “boot.ts”.

Open the app.ts file and add the following code:

import { Component } from 'angular2/core';

@Component({
selector: 'my-app',
template: '<h1>My First Angular 2 App</h1>'
})
export class AppComponent { }

Next, open the boot.ts file and add the following code:

import {bootstrap} from 'angular2/platform/browser'
import {AppComponent} from './app';
bootstrap(AppComponent);

Finally, select the wwwroot node in Solution Explorer and again open the Add a New Item dialog window. Select the “HTML Page” option and rename the page to “index.html”.

Open the index.html page in the editor and replace the default code with the following:

<!DOCTYPE html>
<html>
<head>
<title>Angular 2 QuickStart</title>
<!-- 1. Load libraries -->
<script src="https://code.angularjs.org/2.0.0-beta.1/angular2-polyfills.js"></script><!--ALWAYS FIRST (angular2-polyfills)-->
<script src="https://code.angularjs.org/tools/system.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.1/Rx.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.1/angular2.dev.js"></script>
<!-- 2. Configure SystemJS -->
<script>
System.config({
packages: {
'app': {
format: 'register',
defaultExtension: 'js'
}
}
});
System.import('app/boot').then(null, console.error.bind(console));
</script>
</head>
<!-- 3. Display the application -->
<body>
<my-app>Loading...</my-app>
</body>
</html>

 

Save the web pages and build and run the application. If all goes well, you should see “Loading...” briefly before it’s replaced by “My First Angular 2 App”.

(Note: as of this writing, the Angular2 Quick Start page fails to reload on refresh [although it does on opening a new tab] and it doesn't seem to work in IE. Updates are pending).


Setup SASS

15. Add a folder and SCSS file

Since your project probably doesn’t have one, add a folder called “SASS” to your web project. When done, right-click on the new SASS folder and select Add > New Item from the popup menu.

In the Add New Item dialog, find the SCSS Style Sheet item. Give this a file name the corresponds to the CSS file name you want to use for your project.

Also, create a new folder called “css” within the wwwroot folder. This is where the SASS output will live.

16. Install SASS Compiler

Weirdly, Visual Studio 2015 intellisense fully support SCSS files — which is awesome — but Visual Studio does not know how to compile them for you.

(UPDATE: An alternative to using gulp may be to download and use Mad Kristensen’s Web Compiler. It seems to do the same thing, although I haven’t yet tried it)

To installed the compiler, open the command window. Change the current path to the root folder for your web project (project, not solution, and not SASS folder). If you type “dir” you should see the SASS folder. At the command prompt, type the following two commands:

npm install gulp
npm install gulp-sass

This will cause the node package manager to download and install the SASS compiler.

17. Create the SASS compilation script

Visual Studio knows about SASS files, but it can’t compile them. So far we’ve installed a SASS compiler, but Visual Studio doesn't know to run it. That’s what we’re fixing now.

In Solution Explorer, right-click on your Web project and choose Add > New Item. Scroll through the item types until you come to a Gulp Configuration File. Select this, and don’t change the filename.

Open the gulpfile.js file that you just created. The gulpfile needs to include the following lines (which you may need to merge with existing code):

var gulp = require('gulp');
var sass = require('gulp-sass');

gulp.task('sass', function () {
gulp.src('./SASS/**/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./wwwroot/css'));
});

gulp.task('sass:watch', function () {
gulp.watch('./SASS/**/*.scss', ['sass']);
});

This script will save theCSS files to a folder called CSS. If you want the files written elsewhere, you need to modify the path following “gulp.dest”.

Save the gulpfile.js file. If you haven’t changed the CSS location, you should add a CSS folder to the solution.

18. Tell Visual Studio When to run the script

In Visual Studio, open the Task Runner Explorer window. You can do this from the View menu by selecting Other Windows, then Task Runner Explorer, or by simultaneously pressing the Ctrl+Alt+Bkspace keys.

In the Task Runner Explorer window, ensure that your Web project is selected in the combo-box. You should see the gulp task we created also listed.

If the tasks are not listed, make sure that you followed the instructions described in step 10.

Right-click on the sass task in the list. Select Bindings, then Before Build in the popup menu. Next, right-click on the sass:watch task. Selet Bindings, then Project Open.

To test the SASS compilation, add a simple SASS or statement to the SCSS file in your project. It might be as simple as:

body {
	color:black;
}

In the Task Runner Explorer, right-click on the sass node and select Run from the popup menu. the Task Runner will show the command being executed. You will find a CSS file added to your CSS folder. For the previous example, the content of the CSS file would be:

body {color: black; }

19. Install the Susy grid

Susy consists of SASS partials and a few scripts to build the output. We just implemented the scripts to build the output, so we only need the SCSS files. You can get the Susy file on GitHub. Just click the button to download the ZIP.

Inside the ZIP file is the solitary susy-master folder, which contains the rest of the project. Inside susy-master is a folder called sass. Copy the contents of the sass folder (currently, 3 files and a susy folder) to the SASS folder in your web project.

That’s it! It’s that easy. You’re ready to use the Susy grid.

For media query breakpoints, Susy is complimented by the Breakpoint library. Just as with the Susy library, download the zip file and extract contents of the SASS folder in the file into the SASS folder in your project.

The links to the documentation for the respective projects are:


Angular 2

20. Install Angular2, etc.

Open a command window (without Administrator privileges). Change the current path to the root path of the TypeScript project. Then, at the command prompt, type:

npm install angular2
tsd install angular2 es6-promise rx rx-lite --save
npm install systemjs

These commands will cause the Node Package Manager to download and install the current version of Angular2 and its dependencies, as well as the Angular 2.0 type definitions for TypeScript. SystemJS isn’t technically a dependency, but you’ll probably need it, so you have to load that explicitly.

In your Visual Studio project, click the “show all files” icon in the Solution Explorer pane. This should show two new folders that are not included in your project, “typings”, and “node_modules” (if you don’t see the new folders, then you may not have correctly set the current path when you ran the commands).

Right-click on the “typings” folder and select Include in Project from the popup menu. Do not include the “node_modules” folder in your project!

21. Configure TypeScript for Angular2

In order to work with Angular2, you need to enable support for Experimental Decorators in TypeScript. At this writing, there isn't a way to do this through the UI. Instead, you have to edit the project configuration file.

In Solution Explorer, right-click on the project name and select Unload Project from the popup-menu. Then, right-click on the project again and select Edit <ProjectName> from the popup-menu. The XML for the project should open in Visual Studio.

Scroll down through the project’s XML file until you find the TypeScript configuration settings. You should see elements like “TypeScriptOutFile” and “TypeScriptNoEmitOnError”. Within that PropertyGroup, you need to add two more elements:

    <TypeScriptExperimentalDecorators>True</TypeScriptExperimentalDecorators>
    <TypeScriptEmitDecoratorMetadata>True</TypeScriptEmitDecoratorMetadata>

Save the file and close the editor tab.

In Solution Explorer, right-click on the project name once more, and select Reload Project.

22. Reference Angular 2

In the HTML page, you need to add the necessary Script tags to load Angular 2. Ideally, you should reference a CDN, especially for Production, since this give you great download performance and reliability and it also greatly increases the chance that the scripts will already be in the browser cache. I spent days trying to sort this out. I got it to work, but there are side effects. You should not simply change to a CDNs in your Production deployment without through testing.

To startup Angular 2, this is the HTML scripts tags I used in the <HEAD> section:

<script src="https://code.angularjs.org/2.0.0-beta.0/angular2-polyfills.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/systemjs/0.18.4/system.src.js"></script>

<script>
System.defaultJSExtensions = true;
System.config({
map: {
rxjs: '/node_modules/rxjs',
angular2: '/node_modules/angular2'
}
});
</script>
<script src="https://cdn.jsdelivr.net/rxjs/4.0.7/rx.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.0/angular2.js"></script>

<script>System.import('app').then(null, console.error.bind(console));</script>

 

In short, I wasn’t able to fully use a CDN because Angular 2 has folder references that exist in the node_modules Angular 2 folder, but do not exist on the CDNs. This is a kind of hybrid. I’ll update this if I figure out a better solution. If you want to abandon CDNs for now, simply change the script source to reference your local node_modules folder.

You may notice that the last Script tag loads a file called “App.js”. The default TypeScript project has a default TypeScript page called “App.ts”. You can keep this to load your Angular 2 application; if you create your Angular 2 control in a separate TypeScript file, you need to change this so that your alternative gets loaded instead.

You should consider using ASP.NET’s new “<environment>” tags for these script references, to enable Development, Staging, and Production environments to reference the correct script sources. For example, you’ll want a source with MAP files in Development, but not so much in Production.

 

23. Implement Angular 2

The steps in this section is simply an example of an Angular 2 implementation. You will likely change each of these steps in your own work.

In the HTML page, you add a tag that corresponds to a new Angular 2 control. For our example, this control is called “my-control”. Within the HTML body, wherever you’d like it to appear, simply add:

<my-control>Loading...</my-control>

Angular 2 will come along and replace this with the template you specify.

Either open and edit the default “app.ts” file, or create a new TypeScript file for our Angular 2 application (if you create a new one, modify the last of the script tags in the previous section to reference the new file).

A very simply example of a TypeScript Angular2 file is:

import {Component, View} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';

@Component({
selector: 'my-control'
})
@View({
template: '<h3>Hello {{ name }} !</h3>'
})
// Component controller
class Angular2Control {
name: string;
constructor() {
this.name = 'Angular2';
}
}
bootstrap(Angular2Control);

When you save and run this, you should see the HTML page’s “<my-control>Loading...</my-control>” rendered as “<h3>Hello Angular2!</h3>”!


Set up MVC

24. Create Folders for Models, Views, and Controllers

If you had selected the ready-to-run ASP.NET Web template, your project would already contain these folders. Since ours was empty, you have to create these manually. (You probably already know how to create folders: in Solution Explorer, just right-click on the web project. Then, in the popup menu, select Add > Folder).

Create three new folders, at the root of the project: “Models”, “Views”, and “Controllers”.

Within the the Views folder and add a “Shared” folder to it, and a “Home” folder also.

25. Create the MVC System files

In Solution Explorer, right-click on the View folder, then select Add > New Item in the popup menu (or Ctrl+Shift+A). In the list of items, find and select MVC View Start Page. Do not change the default file name (“_ViewStart.cshtml”) and click Add.

Again on the View folder, add a new item. This time select the MVC View Imports Page. And again, accept the default filename.

Finally, we need to add the MVC View Layout Page. Add this to the Shared folder. Again, do not change the default name (“_Layouts.cshtml”).

26. Add a default page and an error page

Within the Home folder, open the Add New Item dialog. Select MVC View Page from the list. Do not change the default filename (“Index.cshtml”). Click Add.

Likewise, on the Shared folder, open the Add New Item dialog again and again select MVC View Page. This time, change the name to “Error.cshtml”.

With the folders and file added so far, your project should look like this:

Open the two pages in the editor. For the Index view, add a some basic content. For example,

<h1>Welcome to ASP.NET MVC 5!</h1>

For the error page, add a generic error message (this will only be displayed in production environments). For example:

<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>

27. Add DNX Dependencies

The empty project has only the DNX references that it needs to render a very simple response. To render a real ASP.NET web page using MVC and the Razor engine — or even to load a configuration or render a static page — you need to add more libraries.

Open the project.json file. In the dependencies section, add the following references. As with the existing references, use double-quotes around the name. Type a colon, then as you continue typing you should be prompted with version information for each library.

The basic minimum set of references that I need to specify in my project.json file were:

  • Microsoft.AspNet.Mvc
  • Microsoft.AspNet.Mvc.TagHelpers
  • Microsoft.AspNet.Identity.EntityFramework
  • Microsoft.AspNet.StaticFiles
  • Microsoft.AspNet.Tooling.Razor
  • Microsoft.Framework.Configuration.Abstractions
  • Microsoft.Framework.Configuration.Json
  • Microsoft.Framework.Configuration.UserSecrets
  • Microsoft.Framework.Logging
  • Microsoft.Framework.Logging.Console
  • Microsoft.VisualStudio.Web.BrowserLink.Loader
  • Microsoft.AspNet.Diagnostics
  • Microsoft.AspNet.Diagnostics.Entity

When you save the JSON file, Visual Studio will download and install the libraries from NuGet.org.

28. Configure Startup.cs

Every ASP.NET 5 application must have an class named “Startup”. The startup class must have a method called “Configure”, and it may also have a method called “ConfigureServices” (which is called first, if it exists). Even your “empty” ASP.NET project still contains a Startup.cs class. With a welcome move to dependency injection, the Configure method accepts an ApplicationBuilder object, and optional HostingEnvironment and LoggerFactory arguments. You build your application by working with those three provided objects.

The Startup class in the “empty” project does the bare minimum for a “Hello World” response. We need to add in application logic to render our web site. Without this, the DNX ASP.NET engine can’t even serve a static web page.

To add MVC services into the DNX engine, modify ConfigureServices like this:

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

Following guidance online and via the other ASP.NET template (while removing unnecessary steps), the Configure method should look like this:

public void Configure(IApplicationBuilder appBuilder,
HostingEnvironment env,
ILoggerFactory loggerFactory)
{
	loggerFactory.MinimumLevel = LogLevel.Information;
	loggerFactory.AddConsole();
	if (env.IsDevelopment())
	{
		appBuilder.UseBrowserLink();
		appBuilder.UseDeveloperExceptionPage();
		appBuilder.UseDatabaseErrorPage(DatabaseErrorPageOptions.ShowAll);
	}
	else
	{
		appBuilder.UseExceptionHandler("/Home/Error");
	}
	appBuilder.UseStaticFiles();
	appBuilder.UseMvc(routes =>
	{
		routes.MapRoute(
			name: "default",
			template: "{controller=Home}/{action=Index}/{id?}");
	});
}

29. Update Kestrel Hosting changes (if necessary)

 

With Beta8, ASP.NET MVC 6 moved from the “Helio” (IIS) host to the “Kestral” host. If you project origin predates Beta8, you may have some configuration changes to the project.json template file. The startup class, above, already reflects the name changes released with Beta8 (so it won’t work with earlier versions).

If the project.json file references a dependency of “Microsoft.AspNet.Server.IIS”, change that to “Microsoft.AspNet.Server.Kestrel”. Likewise, under the web command, change the references to “Microsoft.AspNet.Server.Kestrel”.

At this point, you should be able to start your web project and see the content you put in your Index page successfully render in a browser!

30. Reference your TypeScript project (And CSS)

First, in your TypeScript project, open the project properties and select the Web tab. Copy the value labelled" “Project URL”. Next, click on the TypeScript Build tab. If there is a checkmark next to Combine JavaScript output into file:, then make a note of that filename. (You might also want to ensure that Generate source maps is also checked).

Now go to your web project. If you want to be able to invoke your TypeScript code for every page, open the _Layout.cshtml file in your editor. (If you don’t use _Layout.cshtml, then you’ll have to follow these same instructions for each page that requires it, starting with the Index.cshtml page).

Normally, you’d simply add the link to the TypeScript output with a script tag's src attribute. Remember, however, that our TypeScript URL is going to be different in development than in other environments. ASP.NET now has an elegant way of handling this. The environment tag will cause the server to output different HTML based upon the code environment; this is how we can use our own VisualStudio instance for development (which allows use to use MAP files for debugging), but change to a different URL or CDN for later environments.

<environment names="Development">
	<script src="http://localhost:12345/myscripts.js"></script>
</environment>
<environment names="Staging,Production">
	<script src="http://myCompanyCDN.com/myscripts.js"></script> </environment>

Environments are discussed in more detail when we get to the upcoming “Manage Configuration & Environments” section.

Finally, since you’re already at the spot where you would do this, it make sense to also add the reference to your CSS file (you can also make this environment specific, or not). Use same path as you specified in your gulp file:

<link rel="stylesheet" href="~/css/MyProject.css" />

Add Localization

 

31. Create the Resources Folder and files

In the Web project, add a new folder and name it “Resources”. If you want to use a different name, fine; later, just specify the alternate name as the “ResourcesPath” property.

As of this writing, Visual Studio 2015 doesn’t have a Resources File template for DNX projects (presumably this will be fixed someday). However, the Typescript project is not using the DNX framework, so you can add Resources to that project, then move them to the DNX one.

In the TypeScript project, open the Add New Item dialog. Navigate to Visual C#, then Code. Select Resources File from the list, and rename the file to Views.Home.Index.cshtml.resx (yes, really). Click Add. Do the same with filename Views.Home.Index.cshtml.fr.resx.

Once you’ve added the Resources files, right-click on each o them and Exclude From Project. You can then copy the files to the Resources folder in your Web project (using Windows Explorer).

You may have noticed that our example file support french in any locale. If you are interested in supporting other languages or specific locales, copy and rename the Resources file to include the new ISO language signifier (like “Startup.ch.resx” or “Startup.es.resx”, for example). Of course, you can always add the region code too; the standard fallback mechanism still works (i.e. if a resource isn’t in a region-specific resource, the system will fallback to the language-specific resource, if still not found, it will use the neutral resource).

32. Add the Resources framework Library

Again, you can use the NuGet package manager, or open the project.json file. The library you need to add is: Microsoft.Framework.Localization.

33. Load the Resources Objects

There are several changes that need to be made to the Startup.cs file. Open the file in your editor.

In the using section, add:

using Microsoft.AspNet.Localization;
using System.Globalization;

In the ConfigureServices method, find the line that calls “services.AddMvc”. We need to call AddViewLocalization method on the resulting building object. The new line should look like this:

IMvcBuilder mvcBld = services.AddMvc();
mvcBld.AddViewLocalization(options => options.ResourcesPath = @"Resources");
mvcBld.AddDataAnnotationsLocalization();

Note that this example assumes that you named your Resources folder “Resources”.

Next, in the Configure method of the Startup.cs class, configure the localization service by including the following:

app.UseRequestLocalization();

34. Add Resource Data

Open the default Resource file in Visual Studio. Add the Name: “Demo1” and the Value “Welcome!”. If you want to open the corresponding French or Spanish resource files, you can add the same name and “Bienvenue!” and “¡Bienvenida!” respectively.

35. Use the Resource data in your View

To use the localized resource in your View, open the Index.cshtml file. Add the dependency

Now you can invoke the localizer in your View. At the top of the View, add the dependency injection for the localizer:

@inject IViewLocalizer Translate;

Now you can add:

<h1>@Translate["Demo1"]</h1>

Anywhere on your page. When you run the project, you should see “Welcome!” in place of “Demo1”.

Shared Class & Controls

36. Add a new Controls project to the solution

Following good development practices, you will like want to move re-usable code and controls into a separate project, so that you can use them on other web solutions. If you already, have a DNX-based shared library, then you should include that into this solution, as an existing project, and skip the rest of this step.

Within Solution Explorer, right-click and add a new project to your solution. In the Add New Project dialog, navigate to Visual C#, then Web. Select Class Library (Package). This will create a class library for use with NuGet.

Because there are now several flavors of .NET portable class libraries, you should confirm that the correct one is being used. Open the project.json file and note the “frameworks” section. If the framework is something other “dnxcore”, you will likely want to change that to the ASP.NET specific “dnxcore”.

37. Load the ASP.NET references

Open the project.json file, in the dependencies section you might consider removing the existing references (as I did). You might also consider simply including all of the dependencies included in your web project.

So far, I’ve included only these references as the necessary to create a ASP.NET TagHelper control:

  • Microsoft.AspNet.Mvc
  • Microsoft.AspNet.Mvc.TagHelpers
  • Microsoft.AspNet.Diagnostics
  • Microsoft.AspNet.Diagnostics.Entity
  • Microsoft.AspNet.Tooling.Razor
  • Microsoft.AspNet.Razor.Runtime

As with the project.json file in our web project, Intellisense should prompt you with the available version information.

Finally, change the framework in the project.json file to “dnxcore50”.

"frameworks": {
"dnxcore50": { }
}

 38. Add a TagHelper control

The new shared controls project, add a new class file. The name of the class should end in “Helper”, such as “ProgressHelper” (to wrap a progress bar, for example), or “OkHelper” (to wrap an OK button).

You can find lots of code elsewhere for examples of creating a custom TagHelper class. Only the simplest implementation is required to get started.

39. Add shared controls to the web project

In the original web project, add a reference to the new shared controls project (right-click on the References node. In the Reference Manager dialog, put a checkmark next to your shared controls project, then click OK).

Open the _ViewImports.cshtml file we created earlier in the web project. We need to add instructions to include our new TagHelper class. While we’re at it, we should also include the tag helper controls included with ASP.NET. You can do this with wildcards (to include all helper in a library) or by loading only what your project requires. the following lines in the _ViewImports.cshtml file will include your custom TagHelper in your new web project. Note that you should rename “MySharedControls” with the actual name of your project.

@using MySharedControls
@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"
@addTagHelper "*, MySharedControls"

40. Localize your Shared Controls project

Make the same localization changes to your Shared Controls project as you did for your Web project. You might suppose that you could use dependency injection to supply the localized strings, but as you are likely to have error and validation messages that will be seen by users, you are not likely to escape needing to use localization strategies in this project too.


Manage Configuration and Environments

41. Create the Configuration files

The web.config file that you may be used to is gone. The new configuration architecture is designed from the beginning to be environment aware (i.e. easily accommodate different values in, say, dev vs test vs production). It is also designed to avoid having sensitive information, such as passwords and keys, checked-in to source code; consequently, these are stored outside of the project folder.

If you are putting configuration information anywhere other than your web project, you probably aren’t really getting injection dependency. The best way to help enforce this is to not have configuration files anywhere other than your web project.

To create the configuration file (something like web.config), in your web project, open the Add New Item dialog, select JSON file, and rename it to “config.json”. Save the file and open it for editing. In this example, adding a SQL connection string requires changing the file to:

{
	"Data": {
 		"SQLConnection": {
			"ConnectionString": "<connect string here>"
		}
	}
}

Obviously, you should replace “<connect string here>” with something valid. Don’t forget to save the changed file.

Now add three more JSON files to your project: ”config.development.json”, “config.staging.json”, and “config.production.json”. As you’ve likely intuited, these allow you to have different configurations depending upon the environment. By convention these three values are defined for the ASPNET_ENV environment variable, but you can certainly use others.

42. Create the Configuration object

In ASP.NET 5, the means of managing configuration data is via a Configuration object. This consolidates configuration data from three difference sources (potentially more): the config.json files (or whatever name you gave them), IIS environment variables, and the user secrets store.

The Configuration object is created by the ConfigurationBuilder. The new configuration logic in ASP.NET is designed to avoid accidental check-in of passwords and keys (which then become available to anyone with source code access). This is the UserSecrets part of the Configuration object. As you have seen, a Configuration object is not needed in order to run an ASP.NET project. It’s only required if you need that functionality. Realistically, only a few web sites don’t.

The recommended implementation is create the Configuration object in the constructor of the Startup class, then expose the Configuration object as a property of that class. Consequently, we need to edit the Startup.cs class.

Add the following usings:

using Microsoft.Dnx.Runtime;
using Microsoft.Framework.Configuration;

Add the new Configuration property to the class:

public IConfiguration Configuration { get; set; }

Add our new constructor, which builds the Configuration object, the sets the property:

public Startup(IHostingEnvironment env, 
	IApplicationEnvironment appEnv)
{
	ConfigurationBuilder cblder = new ConfigurationBuilder();
	cblder.SetBasePath(appEnv.ApplicationBasePath);
	cblder.AddJsonFile("config.json");
	cblder.AddJsonFile(
		$"config.{env.EnvironmentName}.json", optional: true);
	if (env.IsDevelopment())
	{
		cblder.AddUserSecrets();
	}
	cblder.AddEnvironmentVariables();
	Configuration = cblder.Build();
}

Now you can reference Configuration data anywhere in you code, just by using the string index. In the example above, this would be:

Configuration["Data:SQLConnection:ConnectionString"]

Add Test Projects

43. Add the Test Project(s) to your solution

You’ll certainly want to create a Test project to contain the unit tests for your web project. You will probably also want to create a second Test project for your Shared controls project. As with much else, Test projects have been a Visual Studio staple for so long, you may not realize how much has changed.

The general trend seems to be a move toward xUnit tests. In fact, that is the only framework that supports the DNX framework, as of this writing. So, as you open the Add New Project dialog to add this new “Test” project, do not add a test project! To create DNX xUnit tests, navigate to Visual C#, then Web, then finally select Class Library (Package) from the list. Name your test project and click OK. The good news is that Visual Studio handles xUnit tests just as well as any other tests.

You should be aware that the setup instructions for xUnit tests are not correct (again, as of this writing). The instructions indicate that the configuration should be all lowercase; if you want things to work, follow the instructions below.

In the new test project, open the project.json file in the editor. You need to add a reference to two libraries: xunit and xunit.runner.dnx, as well as a test command for the project.

Modify your project.json file so that it looks like this (modifying the version numbers to reference the latest version):

{
	"version": "1.0.0-*",
	"description": "Test Class Library",
	"authors": [ "john" ],
	"tags": [ "" ],
	"projectUrl": "",
	"licenseUrl": "",
	"dependencies": {
		"Xunit": "2.x.x",
		"Xunit.runner.dnx": "2.x.x"
	},
	"commands": {
		"test": "Xunit.runner.dnx"
	},
	"frameworks": {
		"dnxcore50": {
			"dependencies": {
				"Microsoft.CSharp": "4.0.x",
				"System.Collections": "4.0.x",
				"System.Linq": "4.0.x",
				"System.Runtime": "4.0.x",
				"System.Threading": "4.0.x"
			}
		}
	}
}

As I mentioned, pay attention to the casing; it took me a few days to straighten that out.

44. Create some Tests

To create a test, open the default class and add a simple xUnit test. This example is taken from the walkthrough on GitHub:

using Xunit;
…
[Theory]
[InlineData(3)]
[InlineData(5)]
[InlineData(6)]
public void MyFirstTheory(int value)
{
	Assert.True(value % 1 == 1);
}

[Fact]
public void PassingTest()
{
	Assert.Equal(4, 2 + 2);
}

You’ll notice from the example how a xUnit Theory allows you to run multiple tests by specifying different input parameter data. Very cool. If you want a simple test without parameters, you can use a Fact.

45. Run the Tests

In Visual Studio 2015’s Test menu, expand the Windows item and select Test Explorer. When you build the Test project, you should see a status indicator showing that the Test Runner is looking for tests.

As Visual Studio discovers your tests, they should appear in Test Explorer, like so:

 

To run the tests, simply select Run All from the Test Explorer command bar.


Updating

Given all of the various technologies, dependencies, and framewords, each with their own release cycles: how to we keep our ASP.NET 5 project current?

Updating Visual Studio 2015 & Tools

The easiest way to keep Visual Studio (and related tools) current is to periodically open the Notifications window. This will list any updates to Visual Studio and various VS tools. Try not to dismiss relevant notifications without actually updating. The notifications list can be a little stale (i.e. updates can be released without immediately being reflected in the list)

A major update to the web tools in Visual Studio 2015 is typically offered as a distinct download. You can check the .NET Web Development and Tools Blog for the latest release information.

Update the DNX runtime

Open a command windows (without the Administrator token). Enter the following commands:

dnvm update-self
dnvm install latest -Ngen

If a new version is available, the command output will indicate that it is downloading the new version; otherwise, it will report that it is already installed.

Open the project properties and select the newer framework.

Updating NuGet dependencies

Open project.json and update the version number for each of the references. Intellisense will generally prompt you with the latest version number.

If you have updated the base DNX version, there will typically be a corresponding update to each of the essential libraries. This isn’t always true or consistant, however. Visual Studio will start complaining if the DNX version is newer (and incompatible) that the dependencies. (Oddly, the error is NU1006, something about a lock on project.json and a suggestion that you run “dnu restore”).

Ensure that you follow the same upgrade process on each of the projects.

Updating TypeScript

Go to http://www.typescriptlang.org to see if a newer version exists. You can usually find a link to the installer for Visual Studio 2015.

Updating Gulp, SASS, and SUSY

To update the SASS compiler, go to your web project, expand dependencies, then npm. Find the gulp-sass entry in the list, right-click, then select Update Package. You can also do this to update gulp itself.

To update Susy, simply go to the GitHub site, download the newer zip file, extract the SASS partials, and replace the existing ones with the newer ones.

 

Hope this helps.