Wednesday, December 16, 2015

Understanding ASP.NET 5 and .NET Core


**Update  - New ASP.NET 5 video coming soon, follow me on Twitter to keep an eye on announcements **

Most of my enterprise career was web based. In around 1997 my first major web project was to create the sign-up 3.5" floppy disks that were distributed with a good amount of Bell Atlantic phone books. This used all sorts of c-based cgi, Python scripts, and a mish mosh of tech. Things were so very very different then. We were actually the very first all Windows NT Internet Service Provider in the country. Good times but was web tech surely in its infancy.

When ASP (Active Server Pages) first came out, it was amazing - it so we thought at the time as we spaghetti coded away our scripts. Fast forward nearly 20 years to ASP.NET 5. A technology that shares only letters with its predecessor. It's unbelievably fast. It runs an entirely different model than any of its predecessors. It is cross platform - even running on Linux and OSX. This is indeed a new Microsoft.


What is ASP.NET 5?


ASP.NET 5 is a new version of ASP.NET that has been built from the ground up with performance in mind, it is modular, and supports multiple platforms such as Windows, OSX, and Linux. ASP.NET 5 no longer contains Web Forms, it is purely MVC based and supports both C# and VB.NET. This may be a difficult point for some. Going forward, there was a lot of baggage Web Forms carried around and it was an abstraction to the web, which isn't how most modern frameworks work. As such, MVC 6 is the only supported option in ASP.NET 5. You can however still create Web Forms apps in Visual Studio 2015 (for ex. on .NET 4.6), just not for ASP.NET 5.

The WebAPI technology (that released back with MVC 4) has now been merged into a unified controller model in ASP.NET 5. ASP.NET 5 now has out of the box support for Dependency Injection without the  need for any third party DI containers (although several major ones work with it if that's your use case), and performance that can meet or exceed NodeJS applications. Let's not forget self hosting (running without installing into a web server) as well across all the supported platforms and of course you can host in IIS. You can be up and running self-hosting a RESTful api in minutes, publish to Azure and support millions of users, or host in your web server.

ASP.NET 5 has a modular design so you only run the components that you need in your application. Prior versions of ASP.NET had significant overhead loading libraries that may have never been used. The memory footprint of ASP.NET 5 is significantly smaller and you can truly run your application now side by side with multiple versions of .NET and your application code.

As stated in the docs website

  • New light-weight and modular HTTP request pipeline
  • Ability to host on IIS or self-host in your own process
  • Built on .NET Core, which supports true side-by-side app versioning
  • Ships entirely as NuGet packages
  • Integrated support for creating and using NuGet packages
  • Single aligned web stack for Web UI and Web APIs
  • Cloud-ready environment-based configuration
  • Built-in support for dependency injection
  • New tooling that simplifies modern web development
  • Build and run cross-platform ASP.NET apps on Windows, Mac and Linux
  • Open source and community focused
ASP.NET 5 is now RC (Release Candidate) which means you will get support for it in production - although expect some further changes.

What does ASP.NET 5 run on?


ASP.NET 5 runs on Windows, OSX, Linux, and even Docker containers. It loads under .NET 4.5+, .NET 4.6, Mono, and .NET Core (more on that later).

As a side note, there are some interesting future changes brewing here in determining what defines the .NET system your app will run on, and that is the .NET Platform Standard which defines a minimum set of base classes required to run your app.This is something to keep an eye on as it changes how our apps will refer to .NET to run.

Getting Started

First you need the bits for ASP.NET 5 which you can retrieve from http://get.asp.net. You can use all of your favorite code editors to create ASP.NET 5 applications. My preference is Visual Studio 2015 or Visual Studio Code as it has all the tooling to understand your apps better, but it's fairly trivial to do this with Sublime, Notepad, Brackets, etc.



Next create an application. You have a couple options here. The first is in Visual Studio, do a File-New Project->Web, select ASP.NET Web Application. This launches then a new dialog where you could select the .NET 4.6.1 template for One ASP.NET (IE using MVC, Web API, and Web Forms all in one project) which I want to stress is not ASP.NET 5. You must select one of the ASP.NET 5 projects from the ASP.NET 5 section (makes sense, right?).





Yeoman


If you like using Yeoman (no idea what Yeoman is? Check out our free video here on Microsoft Virtual Academy) you can use Yeoman generator for ASP.NET 5. This will code-gen your base project for you. The commands (assuming you have NPM installed by installing NodeJS) are simply:

npm install -g yo
npm install -g generator-aspnet
yo aspnet

That will generate your project and you can simply right click on that generated folder and open in Visual Studio Code to see your entire project. There's actually a great article on this Visual Studio Code ASP.NET 5 workflow already, so I won't repeat that here.


Project.json and the Three Commands

There are three commands used in managing your ASP.NET 5 project. Either you execute them from the command line or your IDE like Visual Studio executes them for you. I like to understand what is going on behind the scenes so lets dive into that a little bit.

DNVM - This is the .NET Version Manager. It is this utilities job to install the run times for your ASP.NET 5 app to use. You can have multiple runtime versions at the same time.

DNX - Your ASP.NET 5 apps are launched via the DNX executable. DNX is the host for _all_ of your ASP.NET 5 applications - be it a console app or running inside of IIS. Even if it's transparent to you, behind the scenes DNX is running your application. If you remember this, life will be easier. DNX is the bootstrapper, compilation system, utilities, and more for running ASP.NET 5 on a variety of runtime versions like .NET 4.5.1, .NET 4.6, .NET Core, and Mono.

If we look at the Startup.cs class generated in a File->New Project template we can see the following Configure method:

// 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)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    if (env.IsDevelopment())
    {
        app.UseBrowserLink();
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    //..
}

The DNX runtime actually is responsible for injecting IApplicationBuild, IHostingEnvironment, and ILoggerFactory into your application. You are communicating with DNX here. This is quite different than we've been used to with standard .NET applications.

DNX does really has four layers to its execution
1. Boot the CLR for the version you have specified or default ie full .NET, CoreCLR etc.
2. Create the LoaderContainer and IL Loaders (those resolve your assemblies)
3. Resolve assemblies in project.json and call the entry point in your managed code
4. Your application code executes

As you can tell by now, DNX is the most important executable in this process.

DNU - .NET Utilities. Yea - it's a generic name but think of this as your multi-tool to install packages (ie NuGet), build your app, or publish your app. There is no packages.config in your ASP.NET 5 projects, only the project.json.

The project.json file is the most important file in your project. It defines the runtime version that will need to run your application. It also specifies dependencies for your applications - IE NuGet packages that will need to be restored before your project runs for the first time.

Let's check out a portion of a project.json file with only the portions I want to discuss here shown below. The dependencies section are NuGet packages that your application depends on. Visual Studio will automatically restore these for you.

{
  "dependencies": {
    "Microsoft.AspNet.Diagnostics": "1.0.0-rc1-final",
    "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
    "Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
    "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
    "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
    "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
    "Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.FileProviderExtensions" : "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final"
},

  "commands": {
    "web": "Microsoft.AspNet.Server.Kestrel"
  },

  "frameworks": {
    "dnx451":{},
   
    "dnxcore50": {}
  }
}
Visual Studio Code will also prompt you to restore these packages.
Behind the scenes, both VS & VS Code are simply using the command:
dnu restore

This command pulls in the packages from the NuGet source, which just pulls them down from the NuGet servers and caches them locally under for ex. c:\users\\.dnx
If you are using the command line (what both of the prior options use behind the scenes) you simply can run dnu restore in your project root folder.

I want to stress that these commands will happen automatically in Visual Studio when you create/run your project. You only need to know these commands if you want to work at the command line, for ex. if you are working on Linux.


Running your application happens via several methods. Publishing I'll cover in a future post. From Visual Studio simply click on the IIS Express button and it will have already configured IIS Express to support this via an HttpPlatformHandler, which is a back-end module that launches processes that listen on HTTP Ports and proxies requests to them in IIS. This will make more sense in a second.



See those other options above that say 'web' and 'ef'? Those are commands. Commands are somemthing brand new to ASP.NET 5, they are simply a way to have multiple ways to load your application or perform actions on it. In the above example, we can run in IIS Express. If we click 'web' then this is going to launch Kestrel (still through DNX though) to act as a lighweight web server to run your app. If we want to generate code for Entity Framework to create our database for us we can use the 'ef' command to call into Entity Framework's Code-First Migrations for ASP.NET 5. BTW - if you have no idea about the power of EF Code-First Migrations, check out our free Microsoft Virtual Academy course on Entity Framework - specifically Module 4.

What is going on behind the scenes when all this happens? Its pretty simple.

dnx web

That's it :) If the command was named 'MyWebServer' instead of 'web' then of course it would be dnx mywebserver.


What is .NET Core?


.NET Core is a new lightweight open source .NET that is comprised of two components, CoreCLR which is essentially the runtime, and CoreFX which is the additional libraries like IO, Collections, etc that you would use in your applications. The major difference here is it is a pull mechanism. You start with a very lightweight framework and bring in the modules you need via NuGet packages. This is how the ASP.NET 5 templates are setup out of the box.


You can run ASP.NET 5 on the full .NET framework. There's baggage there though. Many extra libraries are loaded that you likely don't need.

Looking back to the project.json file you can see the frameworks element. This will define what supported frameworks this app will run on. Here we see dnx451 (ie DNX support for the FULL .NET Framework 4.5.1) and dnxcore50 - the lightweight version.




You have the ability to launch from Visual Studio and specify the default framework to load against by going into your project properties



In reading up on .NET Core you'll find several ways of running this that are exclusive of each other. There's a dotnet utility if you want to compile or run a .NET Core app (the command line interface supports other operations as well) available at https://github.com/dotnet/cli. When it comes to ASP.NET 5 though, the .NET Core bits are loaded via the DNX utility. DNX allows you to specify which runtime you are launching the app with via:

dnx --framework dnx451 web

You have the flexibility to choose which framework you are going to run on. Marc Gravell from Stack Overflow fame has a good series on moving on over to DNX called The Road to DNX as there are definite API changes if you've been used to developing on Full .NET (ex .NET 4.5) and moving to .NET Core.


Serving Up Content

ASP.NET 5 is decoupled from a web server implementation. DNX runs out of process and currently has support for IIS and the open source Kestrel web server. Previously the WebListener was an option, but that has been removed for RC as the move is towards using Kestrel to self-host. If you are running cross platform, the nginx web server/proxy can be used to proxy requests on over to Kestrel, just like the HttpPlatformHandler does for IIS. to be clear, IIS hosts DNX (through the HttpPlatformHandler), just as Kestrel hosts DNX as well. See the image below, note how in each case Kestrel is the host to listen to HTTP traffic on. The web server simply proxies traffic to it, whether its IIS or NGinx.





We talked about the project.json file which is a change from past versions of MVC, but it is also important to note that ASP.NET 5 projects will serve up static content by default only from the wwwroot folder. Views and Controllers work in much the same manner they did previously (if you are not familiar with that, I'll be posting a video shortly on this process).

Wrapping up

There's much more to go into, this was a high level overview of what differences ASP.NET 5 bring to the table. Stay tuned for some more posts on the lower level details, process execution / hosting, and more.

Follow me Twitter to keep an eye on updates, I try to post only useful stuff :)

Enjoy!

15 comments:

  1. Very informative and helpful to understand Microsoft .NET Core move. Thanks

    ReplyDelete
  2. The article clarified lots of things to me -- thanks!

    ReplyDelete
  3. Wow amazing i saw the article with execution models you had posted. It was such informative. Really its a wonderful article. Thank you for sharing and please keep update like this type of article because i want to learn more relevant to this topic.

    SAP Training in Chennai

    ReplyDelete
  4. Hi, am a big follower of your blog. I am really happy to found such a helpful and fascinating post that is written in well manner. Dot Net Training in Chennai | Android Training in Chennai

    ReplyDelete
  5. The blog gave me idea about the ASP.NET 5 and .NET Core My sincere thanks for sharing this post and please continue to share this kind of post
    Dot Net Training in Chennai

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. It was a wonderful chance to visit this kind of site and I am happy to know. thank you so much for giving us a chance to have this opportunity... Cloud Computing Training in Chennai | Salesforce Training in Chennai

    ReplyDelete

  8. You've made some good points there. I looked on the internet for more information about this

    Mainframe Training In Chennai | Informatica Training In Chennai | Hadoop Training In Chennai

    ReplyDelete
  9. This is a much needed information thank you for sharing and it's very helpful to know about this information. Thanks for sharing it.
    Guest posting sites
    Technical updates

    ReplyDelete
  10. Really nice blog post.provided a helpful information.I hope that you will post more updates like this Dot NET Online Training

    ReplyDelete

Note: Only a member of this blog may post a comment.