Mastering ASP.NET 5 without growing a beard


…or learn the lingo and sound like an ASP.NET 5 expert

So you know ASP.NET like the back of your hand, or so you think, until you hear grunt this, and bower that, and you realize that nothing has changed but EVERYTHING, and all you can do is just sit there and nod like Joey in friends.

If you don’t have time to grow a beard, or go through the Intro to ASP.NET 5 course, but still want to hang out with the cool guys, here is the cliff notes version. Just enough to be conversational.

5 quick facts about ASP.NET 5

In short, what has happened with ASP.NET 5 is that it is a new incarnation of ASP.NET based on a couple of big things that have happened with the web lately. ASP.NET 4.5 still lives on side-by-side with 5.

1. It is open source – You can read, branch and contribute to both asp.net and the underlying framework DNX Core, along with a lot of other parts of .net like the ROSLYN compiler. You can also contribute to the docs, and/or participate in the bi-weekly community standup.

 

PRO TIP: Don’t fall into the trap and start blabbering about how you downloaded the CLI Source way back in 2002.  1. you will sound like a grandpa and 2. you will sound like a grandpa who thinks that museum open source (looki looki no touch) is the same as real open source.

 

2. It is cross platform – earlier ASP.NET was tightly coupled with IIS, but now all you need is a web server that implementsOWIN like the cross-platform development webserver Kestrel, or you can self-host with WebListener. DNX Core is the cross platform .net runtime that lets you run .net apps on Linux or Mac, in the cloud or on prem and you can write the app with your choice of editor/IDE whether it is Visual Studio, Visual Studio Code, Notepad, Sublime or something else.

Trivia: You can run ASP.NET 5 apps on Raspberry Pi 

 

3. It is modular – when you create an asp.net web forms app or ASP.NET MVC app you no longer have to include all of ASP.NET, you just pick and choose the parts you like. If you don’t need authentication, then don’t include it. The modularity means that the footprint is smaller and with less things in the pipeline everything is faster.

 

4. It’s fast – The ASP.NET team takes the performance thing very seriously, benchmarking this and that. But it is not only fast performance wise, the dev cycle is also faster. It has now been shortened from save-build-browse to save-browse, huge improvement YAY!

 

5. It is built for the cloud – with features like environment based configuration, and hiding client secrets so they don’t accidentally end up on GitHub. Because it is modular you can also do things like replace the normal asp.net cache with Redis.

But there is another big thing that has happened to the web, and that is the move from the server to the client. In the last 15 years we have gone from ASP spitting out HTML to SPA Applications with full MVVM JavaScript frameworks like AngularJS that do everything on the client, and just use the server to fetch data. We have nice skinnable css/js component libraries like Bootstrap. And even ways to write easier to read JavaScript with TypeScript or CoffeeScript and CSS with less or sass.

 

PRO TIP:  You can pick up a lot of one-liners from Scott Hanselman’s hilarious JavaScript and the Rise of the new Virtual Machine. Or just watch it to get entertained and marvel at how far JavaScript has come.  The talk starts 8:20 min in, straight after the fabulous introduction, “This is Scott Hanselman, he is a very famous guy on the internet”Smile

 

Now you could either use something like AngularJS to write the whole application and just use ASP.NET Web API to fetch the data. Or you can mix and match ASP.NET MVC and Angular, where ASP.NET MVC could be used to route between multiple smaller SPAs and then you could use Angular routing inside the individual SPAs.

 

To make all this jive together we need to use a few tools:

As .net developers we are used to use NuGet to download .NET modules to use in our apps. There are similar package managers that you can use to download JavaScript frameworks, or Bootstrap or other client side packages. The most common ones are NPM (Node Package Manager) and Bower.

Once you have written all your JavaScript code you may want to minify it or uglify it or do other client side tasks like converting CoffeeScript to JavaScript and this is done with a task runners like Grunt or Gulp.

To get started, you can actually create your ASP.NET 5 project by hand. The only thing that is really needed for a DNX core project is a project.json file and a startup.cs.

The project.json file is where you define your project and add in all your dependencies (watch the magic in the references section when you add a dependency and save). The startup.cs file has two important methods, ConfigureServices where you add in the services you are going to use (like MVC), and Configure, where you add them to the pipeline by calling the Use method.

project.json

{
  "webroot": "wwwroot",
  "version": "1.0.0-*",

  "dependencies": {
    "Microsoft.AspNet.Server.IIS": "1.0.0-beta5",
    "Microsoft.AspNet.Server.WebListener": "1.0.0-beta5",
    "Microsoft.AspNet.Mvc": "6.0.0-beta5"
  },

  "commands": {
    "web": "Microsoft.AspNet.Hosting --config hosting.ini"
  },

  "frameworks": {
    "dnx451": { },
    "dnxcore50": { }
  },
}

 

startup.cs

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

        public void Configure(IApplicationBuilder app)
        {
            app.UseMvc();
        }
    }

Now, if you don’t want to do everything by hand, you can create an ASP.NET 5 project in Visual Studio, or you can scaffold one out with the Yeoman tool (yo) on Mac for example.

That is basically the gist of it, but phew… that was a slew of words and tools and technologies that until recently used to be gibberish to me. A lot of them have been known for a long time by people that develop for the mean stack (MongoDB, Express, Angular, Node.JS) but it is not until now that they have been properly married with ASP.NET and the MS stack.

Oh, so many new words, my brain is exploding…

DNX – DNX is short for .NET execution engine. There are two main flavors, DNX 4.5.X (the full framework) and DNX Core 5.0 (the light-weight open source .NET version that also runs on Linux and Mac). DNX Core contains almost everything but is missing a few Windows namespaces like System.Drawing for example.

ROSLYN – Roslyn is the new .NET compiler and it gives you some pretty neat features like real-time code analysis in Visual Studio (you know the light bulbs with quick hints and tips).

OWIN – Open Web Interface for .NET – a standard interface between .net web servers and web applications.  Earlier, ASP.NET was tightly coupled with IIS. The purpose of OWIN is to break this relationship so that if you have a web server that implements OWIN correctly you can run ASP.NET on that web server. It also allows for more modularization so that you can plug and play things like MVC or authentication.

Katana – A set of OWIN components built and released by Microsoft (open source), with both hosts, servers and functional components like bindings to frameworks like SignalR and ASP.NET Web API.

Self-hosting – If you want to avoid the overhead of hosting a Web API in IIS and want something more lightweight, you can host it in your own process, i.e. self-hosting.  Self-hosting can also refer to a compiler that is written in the language it compiles, like the Roslyn C# compiler.

WebListener – a self-host ASP.NET 5 web server available on NuGet

Kestrel – a cross platform ASP.NET 5 development web server available on NuGet

SPA – Single Page Application. A web app that fits into a single web page (i.e. one get from the server), and where all the HTML, JavaScript and CSS is either gathered in one go, or loaded dynamically. Normally this is used in conjunction with JavaScript MVVM or MVC frameworks like AngularJS, Ember.js or React.

MVVM – Model View ViewModel – a common pattern for apps where you separate the code for a page into 3 separate layers. View is the UI for the page, Model is the data, and ViewModel is an interface between the View and the Data with logic that massages the data so that it fits the view.

MVC – Model View Controller – Very similar to MVVM and also the pattern that MVVM stems from. Instead of using a ViewModel it uses a Controller to communicate between the model and the view.

AngularJSAngular is a client-side MVVM JavaScript framework from Google that does everything from data binding and templating to client-side routing and more. Some claim it is getting to big and monolithic, and lucky for them there is a gazillion other JavaScript frameworks to choose from like Ember.js, Backbone.js, Knockout.js, React etc. etc. etc. For a nice walkthrough, read Stephen Walther’s ASP.NET 5 and AngularJS tutorial

PRO TIP: If people get all in a huff and a puff about which framework is the best, just let them battle it out, and then say: “Sure, but those frameworks are so last week, I’m using redact.js, it’s superfast and easy to use, increases perf on any website by about 60%. It has that Coco Chanel minimalist quality, and it’s open source”

BootstrapBootstrap is a sweet framework with components for responsive web apps written in HTML, CSS and JavaScript. Navigation elements, Jumbotrons, Special buttons, layout sections etc. with a large community of people doing skins/themes like the ones on http://bootswatch.com/ or http://www.bootstrapzero.com/.

TypeScriptTypeScript is kinda like JavaScript for c# developers. You can use classes and modules and interfaces, and then it compiles down to vanilla JavaScript. In Visual Studio, the conversion to JavaScript happens when you save, and you get full intellisense, Roslyn light bulbs and proper code analysis with error lists etc.

Sample TypeScript

class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

Corresponding JavaScript

var Greeter = (function () {
    function Greeter(message) {
        this.greeting = message;
    }
    Greeter.prototype.greet = function () {
        return "Hello, " + this.greeting;
    };
    return Greeter;
})();

CoffeeScript – Similar to TypeScript, CoffeeScript is also a language that compiles down to JavaScript. Its purpose is to simplify JavaScript. If you want to use CoffeeScript in Visual Studio, you can either use a Grunt or Gulp task to compile it to JavaScript on save or you can install the Visual Studio WebCompiler extension that will do it for you.

Sample CoffeeScript

alert "I knew it!" if elvis?

Corresponding JavaScript

(function() {
  if (typeof elvis !== "undefined" && elvis !== null) {
    alert("I knew it!");
  }

}).call(this);

 

Fun from the Interwebs: Before you start rolling your eyes, Yes! I know that Java and JavaScript are about as related as C# and C, but all that talk about Coffee and Java made me remember my favorite article from The Daily WTF about the Brillant Paula Bean

ECMAScript – ECMAScript is a scripting language specification. The more common implementations are JavaScript and JScript.

Less and SassLess and Sass are to CSS what TypeScript and CoffeeScript are to JavaScript. They both aim to make it simpler to write CSS, and you can use Grunt or Gulp or WebCompiler to convert the less or sass files to CSS and/or minified CSS files on save.  Among other things, you can use them to define re-usable CSS content like red and .bordered below, and also nest css nicely.

Sample Less file

@red: #FF0000;

.bordered {
    border-top: dotted 1px black;
    border-bottom: solid 2px black;
}

#menu {
    .bordered;
    a { color: @red; }
    a:visited { color: desaturate(@red, 10%); }
}

 Sample Sass file

$red: #FF0000;

.bordered {
    border-top: dotted 1px black;
    border-bottom: solid 2px black;
}

#menu {
    @extend .bordered;
    a{color: $red; }
    a:visited { color: desaturate($red, 10%); }
}

 Resulting CSS

.bordered {
  border-top: dotted 1px black;
  border-bottom: solid 2px black;
}
#menu {
  border-top: dotted 1px black;
  border-bottom: solid 2px black;
}
#menu a {
  color: #FF0000;
}
#menu a:visited {
  color: #f20d0d;
}

 

NPM – NPM (Node Package Manager) is like NuGet for client-side stuff. Add an NPM configuration file (package.json) to your ASP.NET 5 app and load in the proper references by adding them to the devDependencies section. When you save the file you’ll see them show up under References/NPM. Typical things you would download with NPM are Grunt or Gulp or Bower.

Sample package.json file

{
  "version": "1.0.0",
  "name": "MyASPNETApp",
  "devDependencies": {
    "grunt": "0.4.5",
    "grunt-contrib-uglify": "0.10.0",
    "grunt-contrib-watch": "0.6.1",
    "gulp": "3.9.0",
    "gulp-uglify": "1.4.2",
    "gulp-concat": "2.6.0"
  }
}

 

Bower – Bower is also like NuGet for web stuff. Similar to NPM you add a bower configuration file (bower.json) to your app. The libraries will be downloaded to the wwwroot/lib folder by default. The * here means we will download the latest version of angular.

Sample bower.json file

{
  "name": "ASP.NET",
  "private": true,
  "dependencies": {
    "bootstrap": "3.0.0",
    "bootstrap-touch-carousel": "0.8.0",
    "angular": "*",
    "angular-route": "*",
    "angular-resource": "*"
  }
}

Minify – To avoid sending too much over the wire you can minify CSS and JavaScript. Minification means that you remove any characters that are non-essential, like white-space, new-lines and comments.

Uglify – Uglifying is a little bit like minifying, but usually you also concatenate a number of JavaScript or CSS files into one, and then Minify it. This is a typical task for Grunt or Gulp. 

Grunt and GulpGrunt and Gulp are both task runners that you use to perform tasks like minifying or uglifying css and javascript, or compiling less and sass into css, or TypeScript and CoffeeScript into JavaScript. In Visual Studio you can open the Task Runner window to run the tasks manually. The following sample shows how you can watch for changes in JavaScript files and whenever something changes, concatenate/uglify them into a single app.js file that you place in the wwwroot folder.

The Grunt way:

module.exports = function (grunt) {
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-watch');

    grunt.initConfig({
        uglify: {
            my_target: {
                files: {
                    'wwwroot/app.js': ['Scripts/app.js', 'Scripts/**/*.js']
                }
            }
        },
        watch: {
            scripts: {
                files: ['Scripts/**/*.js'],
                tasks: ['uglify']
            }
        }
    });

    //define tasks
    grunt.registerTask('default', ['uglify', 'watch']);
};

The Gulp way:

var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');

gulp.task('scripts', function () {
    gulp.src(['Scripts/app.js', 'Scripts/**/*.js'])
        .pipe(concat('app.js'))
        .pipe(uglify())
        .pipe(gulp.dest('wwwroot'));
});

gulp.task('default', ['scripts'], function () {
    gulp.watch('Scripts/**/*.js', ['scripts']);
});

Yeoman/YoYo is a scaffolding tool, together with the OmniSharp ASP.NET generator (generator-aspnet) that you can download with npm, it lets you quickly create a new empty asp.net 5 app where you don’t have Visual Studio (like on Mac or Linux).

 

Hopefully that should be enough to make you a little bit more comfortable with the hipster crowd, but if all else fails, just start mumbling about some obscure Powershell cmdlet and they will all dissapear.

Comments (15)

  1. Bill Menees says:

    Loved it!  I'm _almost_ embarrassed to admit that I'm an old geezer that still prefers ASP.NET Web Forms (because it still works great for my needs).  But this was a great overview of the ASP.NET 5 spaghetti/stack/environment!

  2. AnilAwadh says:

    just can say, its "Awesome!"

  3. You Really Need A Name says:

    WOw that didn't teach me anything about coding asp.net 5.

  4. Good one Tess. Interesting to see how ASP.NET 5 has evolved these days. It's definitely not our grandpa's asp.net. btw, I couple of recommendation for further reading,

    #1) Jeff has an interesting article about front end dev stack- medium.com/…/the-front-end-spectrum-c0f30998c9f0

    #2) Scott's H recent talk about asp.net 5 – https://t.co/TS6Ci1PX65

    HTH,

    @MahesKBlr

  5. Mattias says:

    Thanks for this post, super nice!

    (Somehow I doubt you would ever grow a beard regardless of how long time you need to spend on a task… 😉

  6. Shawn Wildermuth says:

    I've got a series of blog posts on this too:

    wildermuth.com/…/A_Look_at_ASP_NET_5_Part_1_-_Getting_Started

    And my @pluralsight course is pretty comprehensive too:

    http://shawnw.me/learnaspnet5

  7. Lex Lavnikov says:

    Cool stuff. But some coolest missing like webpack.

    And redact.js demo does not work in Egde 13 mobile.

  8. Sweet Shawn, Those look really good… Think the plural-sight course (especially the angular parts) will be my weekend entertainment.

    and thanks for the other links Mahesh, interesting

  9. CodeForRe@l says:

    Just fantastic! "Bravo!"

  10. James Parsons says:

    I think I'm gonna grow a beard just waiting for it :/

  11. Caverman says:

    Great stuff! I love the quick simple explanations of the terms I've been hearing lately. I'll be referring back to this for a while until I get my head wrapped around it all.

  12. Don says:

    Excellent post – thank you!!!

    I'm seeking clarification on this sentence "when you create an asp.net web forms app or ASP.NET MVC app you no longer have to include all of ASP.NET, you just pick and choose the parts you like" – I am under the impression that the modular concept is not true for web forms as it is still tied to system.web and thus the full framework. Web forms is supported with 4.6 full framework but not the new core approach in 5 which allows the user to pick desired packages and determine how to manage them(i.e. keep updated, etc.).

    Please advise.

    Thanks again.

  13. Sunil Ravulapalli says:

    Nice recap. Helped me a lot.

  14. Nikunj Dhawan says:

    Very well written. Summarizes ASP.Net 5 nicely!

  15. Malisa Ncube says:

    Nice post.

    I watched a video where you were showing advanced debugging on ASP.NET applications some years back. Would be nice if you would post another video on it taking the new ASP.NET.

    malisancube.com

Skip to main content