Visual Studio 2015 Preview + ASP.NET 5

9 minute read

cover 

I have been following the progression of ASP.NET in particular in relation to the changes made for ASP.NET 5. I’m going to take a look under the covers of Visual Studio 2015 preview at the command line underpinnings of ASP.NET 5 and, as a result, for the first part of this article I’m not going to touch Visual Studio at all; it will all be driven from the command line and Notepad. One of the design goals for ASP.NET was to get free from its Visual studio and Windows dependencies so I feel okay about learning how it works on this layer and hopefully later I’ll get to appreciate the extras that Visual Studio will give me on top.

Hello World

For the purpose of using a ‘clean’ environment I’m going to run up a virtual machine in Azure and create an ASP.NET MVC application without installing Visual Studio. I headed off to the azure portal https://manage.windowsazure.com and I chose Windows Server 2012 R2 with pretty much the default settings and spun up my Virtual Machine.

vm config

A few minutes later, after a nice cup of tea, I find myself ‘remoted’ into the machine and am ready to go. Since ASP.NET is open source I headed along to the associated Github site and followed the Readme.md instructions to get started. The process for installing can be carried out using a command prompt, in summary:

Install the K Version Manager (KVM)

Install the K Runtime Environment (KRE)

Once these are installed we can use their respective commands to configure the environment, our project and its dependencies. I’ll come back to these later but for now it’s useful to note that K was used as a project pseudonym but beyond that has no special meaning.

Using Notepad I created a project.json file (the new project definition file) and a Startup.cs file (entry point to configure the request pipeline) as below:

{
     "dependencies": {
         "Microsoft.AspNet.Hosting": "1.0.0-beta1",
         "Microsoft.AspNet.Server.WebListener": "1.0.0-beta1",
     },
     "commands": {
         "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5001",
     },
     "frameworks": {

         "aspnet50": {},
         "aspnetcore50": {}
    }
}

 

using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
namespace FirstApp
{
     public class Startup
     {
         public void Configure(IApplicationBuilder app)
         {
            app.Run(async c =>
            {
                await c.Response.WriteAsync("Hello from ASP.NET 5!");
            });
         }
     }
}

 

Executing ‘kpm restore’ at the command line collects all of the required dependencies, downloading if necessary and then executing ‘k web’ will start the web server listening at http://localhost:5001 so navigating to that url in the browser gives…

 hello from aspnet

Editing the output string in the Startup.cs file, saving the file and refreshing the browser causes the new string to be rendered by the browser without going through an extra build step. Also, inspecting the project folders using Windows Explorer reveals no binaries on disk. This is because changes to the source files are being continually monitored and when a change is detected the project is rebuilt in memory (using Roslyn, the new .NET compiler platform also hosted on Github) and the resulting code is injected into the web server process (Note. this mechanism is only working for me currently when using IIS Express). This results in a more efficient and faster development process more familiar to web developers.

Moving Parts

We’ve briefly seen KVM, KRE and KPM so let’s have a look into those and see what they can do for us.

K Version Manager

The KVM helps us to keep track of the different K Runtime Environments we may have installed locally, it helps us to download others and manage their usage. For example, ‘kvm list’ will list out all versions of the runtime environment and ‘kvm use’ will specify which to use.

K Runtime Environment

Consists of different builds of the runtime libraries, the K command line and the KPM. The K command takes on the responsibility of bootstrapping the environment. In fact there is a hidden folder within your user folder called .kre where the disk representation of the runtime environments are stored so you can have a look and see what’s there.

K Package Manager

The KPM is responsible for any package related actions required by your app such as restoring packages as we saw earlier. 

Dependencies

Previous versions of ASP.NET are dependent on Windows OS for a number of things; to load the CLR into memory when needed and it’s usage of assemblies which are part of the .NET framework libraries which are installed on the machine. Also the project system was heavily dependent on Visual Studio and, as a result, was difficult to integrate with other external tools. In order to break these dependencies and allow cross-platform development ASP.NET 5 has followed some core design principles:

File system to define the project contents

Command line first

Nuget Packages to define dependencies

Arguably the most significant change is the repackaging of the .NET framework into a light-weight .NET Core which ships as a collection of Nuget packages intended to be distributed alongside your app making it completely self-contained. Alongside this the environment is also much more modular and pluggable so you only need to use bits of the pipeline that you need making requests more efficient. In the past, supporting additional platforms with .NET has resulted in multiple, incompatible ‘cores’ resulting in the need for workarounds like portable class libraries which allow targeting of a subset of common features of multiple frameworks. The building of .NET Core signals a move towards a true common core paving the way for easier cross-platform targeting. By default on windows the full .NET framework is used to use the .NET Core you can run ‘kvm upgrade -runtime CoreCLR’ which will retrieve .NET Core and set it as the default KRE.

 

Request Pipeline

I was using the clean vm without Visual Studio just for illustration, I would recommend installing Visual Studio 2015 Preview as a first step if you want to start experimenting with this or there are also virtual machine images on Azure which you can use. I’m going to switch over to Visual Studio now and look at how to introduce MVC and Web API into the mix.

azure images 

In our original example we were just writing directly to the response – nothing extraneous was being loaded up, no MVC, no Web API. So, if we want those things how do we load them into the pipeline?

First we need to add a dependency on MVC, Visual Studio helps with intellisense in the project.json file:

projectjson

Or, alternatively we can use the Manage Nuget Packages dialog

nugetdlg

As before the code goes into Startup.cs

  1. using Microsoft.AspNet.Builder;
  2. using Microsoft.Framework.DependencyInjection;
  3.  
  4. namespace FirstApp
  5. {
  6.     public class Startup
  7.     {
  8.         public void ConfigureServices(IServiceCollection serviceCollection)
  9.         {
  10.             serviceCollection.AddMvc();
  11.         }
  12.  
  13.         public void Configure(IApplicationBuilder app)
  14.         {
  15.             app.UseMvc();            
  16.         }
  17.     }
  18. }

So, in general the pattern is that you declare that you want to use a component with the Add call and then the Use call goes into the pipeline itself. That’s it – now we can add a controller and have it work as expected!

  1. public class HomeController : Controller
  2. {
  3.     // GET: /<controller>/
  4.     public string Index()
  5.     {
  6.         return "Hello ASP.NET 5!";
  7.     }
  8. }

Since MVC and Web API are now all part of the same pipeline we can mix and match their actions within the same controller. Dependency injection is now built in and used throughout so the IServiceCollection interface passed to the ConfigureServices method allows us to register types and instances scoped to various lifetime policies much as you would expect and these will get automatically injected into your controllers.

 

Visual Studio

Visual Studio provides us with all of the functionality of the command line tools and more really nice features on top.

Project Templates

Visual Studio 2015 provides project templates for ASP.NET 5 development. Currently these consist of the following:

Web Application – creation of web apps using ASP.NET 5 – currently there is an Empty project and a web starter project

Class Library – this gives an easy way to create your own Nuget packages (Note that by default the output is not written to disk – there is currently a setting in project settings to enable this).

Console Application – this uses the new project structure and can be used for self-hosting ASP.NET apps

 

Multiple Target Frameworks

Since our project can potentially declare support for multiple frameworks how do we know from our code when we have errors in one or more of these targets? Visual Studio fully supports this scenario in a number of ways:

There is a context switcher at the top left of code files which enable selection of one of the frameworks supported by your project. When selected the code file will reflect errors\information for the one chosen context. Also, the tool tip is informing us of the availability of the ToUpper() method in each target framework.

contextswitcher

The Combined intellisense shows a warning symbol when a method might not be available.

combinedintellisense

 

Client Side

Visual Studio now has support for client-side frameworks and build management such as Bower, Grunt and Node. This includes configuration file support with intellisense and also tooling support for build tasks and dependency management. There’s a detailed article about this support here Manage Client-Side Web Development in Visual Studio 2015, Using Grunt and Bower

CTP 5

At the time of writing Visual Studio 2015 CTP 5 has just been announced along with ASP.NET 5 beta2. The new features in Visual Studio are detailed here Making It Better: Updates for ASP.NET 5 in Visual Studio 2015 CTP 5

Cross Platform

Since ASP.NET 5 is designed from the outset to be cross platform let’s take a quick look at what this looks like on a Mac. So, back to the Github site to follow the install instructions for Mac OS X https://github.com/aspnet/home. After that I used the project.json and Startup.cs from the first example with one addition; I added a dependency for Kestrel and also a command to run it. Kestrel is a development web server for ASP.NET vNext based on libuv.

{
    "dependencies": {
        "Kestrel": "1.0.0-beta1",
        "Microsoft.AspNet.Hosting": "1.0.0-beta1",
        "Microsoft.AspNet.Server.WebListener": "1.0.0-beta1",
    },
    "commands": {
        "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5001",
        "kestrel": "Microsoft.AspNet.Hosting --server Kestrel --server.urls http://localhost:5004"
    },   
    "frameworks": {
        "aspnet50": {},
        "aspnetcore50": { }
    }
}

Then, running ‘kpm restore’ followed by ‘k kestrel’ results in the following:

aspnet5onmac

The development experience on the Mac is pretty good; I used Sublime Text 3, for which you can get project support and intellisense and yeoman (for project generation). To get started on Mac see Develop ASP.NET vNext applications on a Mac.

Further Information

Since the development is ongoing I would assume some of the above is subject to change, particularly naming conventions – you can keep up with project status here ASP.NET COMMUNITY STANDUP 

You can download Visual Studio 2015 Preview here Visual Studio 2015 Preview Downloads

There is some superb MVA content here What's New with ASP.NET 5 (there are 7 videos covering ASP.NET 5 in depth)

Or for an overview - DEEP DIVE: The Future of .NET on the Server

Nuget intro http://channel9.msdn.com/Events/MIX/MIX11/FRM09

ASP.NET vNext Forum http://forums.asp.net/1255.aspx/1?ASP+NET+vNext

Loads more stuff http://www.asp.net/vnext

Comments