Click here to Skip to main content
15,867,686 members
Articles / Web Development / HTML

Baby Steps towards ASP.NET 5 Web Application and see What’s New

Rate me:
Please Sign up or sign in to vote.
4.64/5 (15 votes)
22 Jul 2015CPOL10 min read 48.1K   390   17   11
In this article we are going to see how and where to download Visual Studio 2015 to create a brand new simple Asp.Net 5 Web Application and have a quick overview on what's new in C# 6
Download AspNet2015.zip

Introduction

In this article we are going to see how to

  1. Download Visual Studio 2015
  2. Create a brand new simple Asp.Net 5 Web Application
  3. High Level Overview on whats new in the web project structure and
  4. New C# 6 features

Download Visual Studio 2015:

Visual Studio 2015 is the latest update from Microsoft with new .Net 4.6 framework. I used Visual Studio 2015 Release Candidate (RC) to analyze and check the project structure for this article. By the time I complete this article, Microsoft released Visual Studio 2015 Release to Manufacturing (RTM) and you can download it from here.

Image 1

Creating a new simple ASP.NET 5 Web Application:

Like any other project in Visual Studio we start by creating a new ASP.NET Web Application “AspNet2015” with the .Net framwework version 4.6

Image 2

From the template window, we are going to select Web Site template under “ASP.NET 5 Preview Templates”. Notice that all check boxes (Web Forms, MVC and Web API) have been disabled. Why because in new ASPNET 5, both MVC controller as well as API controllers are referred as Controllers. Also, we can have .aspx web forms within MVC project.

Image 3

In this demo application, we are not concentrating on any kind of authentication. So we change authentication to “No Authentication” in order not to get distracted by Authentication Controller and its corresponding Views.

Image 4

As soon as we create a new project, Visual Studio quickly executes its bootstrapper code to generate an entire solution. Unlike previous releases and templates, Visual Studio team has revamped an entire project structure by adding new concepts and replacing some legacy ones. Here is the project structure:

Image 5

As soon as the project loads the first thing it does is restore Dot Net Executable (DNX) and DNX Core 5.0 libraries under references.

Image 6

Also, it restores external client side packages like CSS and JS files along with its dependencies. If not restored we can always right click on Bower and NPM to restore packages.

Image 7

Image 8

Now build and run the application to view it in browser. Before each build, project will restore all necessary server side and client side packages. Here is how our new Asp.Net 5 application looks in regular browser:

Image 9

And this is how it appears in Responsive (Mobile) Devices:

Image 10

High Level Overview on whats new in ASP.NET 5 Project Structure:

Asp.Net team made a number of architectural changes that make the core web framework much leaner and more modular. It no longer based on System.Web.dll but on set of granular and well factored NuGet packages. ASP.NET 5 is built with the needs of modern Web applications in mind for building Web UI and Web APIs. Cloud-ready by introducing environment-based configuration and by providing built-in dependency injection support. It now supports broader audience of developers, supports cross-platform development on Windows, Mac and Linux. It has simple built-in Inversion of Control (IoC) container that supports constructor injection by default.

Here are some of the highlights:

  • 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

Project.json:

Project.json file is used to define the project’s server side dependencies as well as other project-specific information.

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

  "dependencies": {
    "Microsoft.AspNet.Diagnostics": "1.0.0-beta4",
    "Microsoft.AspNet.Mvc": "6.0.0-beta4",
    "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-beta4",
    "Microsoft.AspNet.Server.IIS": "1.0.0-beta4",
    "Microsoft.AspNet.Server.WebListener": "1.0.0-beta4",
    "Microsoft.AspNet.StaticFiles": "1.0.0-beta4",
    "Microsoft.AspNet.Tooling.Razor": "1.0.0-beta4",
    "Microsoft.Framework.ConfigurationModel.Json": "1.0.0-beta4",
    "Microsoft.Framework.CodeGenerators.Mvc": "1.0.0-beta4",
    "Microsoft.Framework.Logging": "1.0.0-beta4",
    "Microsoft.Framework.Logging.Console": "1.0.0-beta4",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-beta4"
  },

  "commands": {
    "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5000",
    "gen": "Microsoft.Framework.CodeGeneration"
  },

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

  "exclude": [
    "wwwroot",
    "node_modules",
    "bower_components"
  ],
  "publishExclude": [
    "node_modules",
    "bower_components",
    "**.xproj",
    "**.user",
    "**.vspscc"
  ],
  "scripts": {
    "postrestore": [ "npm install", "bower install" ],
    "prepare": [ "gulp copy" ]
  }
}

The webroot section specifies the folder that should act as the root of the web site, which by convention defaults to the wwwroot folder. The version property specifies the current version of the project. We can also specify other metadata about the project such as authors and description. The frameworks section designates which targeted frameworks will be built, and what dependencies need to be included. The exclude section is used to identify files and folders that should be excluded from builds. BundleExclude is used to identify content portions of the project that should be excluded when bundling the site. The scripts section is used to specify when certain build automation scripts should run. Visual Studio now has built-in support for running such scripts before and after certain events.

Image 11

Global.json:

The global.json file is used to configure the solution as a whole.

JavaScript
{
    "projects": [ "src", "test" ],
    "sdk": {
        "version": "1.0.0-beta4"
    }
}

The projects property designates which folders contain source code for the solution. By default the project structure places source files in a src folder. The sdk property specifies the version of the DNX (.Net Execution Environment) that Visual Studio will use when opening the solution.

wwwroot folder:

In previous versions of ASP.NET, the root of the project was typically the root of the website. In later versions of ASP.NET, support for routing was added, making it possible to decouple the locations of files from their corresponding URLs. However, this routing was used only for ASP.NET-specific application logic but not on static files. Resources like images, script files, and stylesheets were generally still loaded based on their location.

Having to specifically block access (also known as blacklisting) to certain files is much less secure than granting access only to those files which should be accessible(also known as whitelisting)

The wwwroot folder represents the actual root of the web app when running on a web server. Static files, like config.json, which are not located in wwwroot will never be accessible, and there is no need to create special rules to block access (blacklisting access) to sensitive files. In addition to the security benefits, the wwwroot folder also simplifies common tasks like bundling and minification process.

Dependencies:

The Dependencies folder contains two subfolders: Bower and NPM. These folders correspond to two package managers by the same names, and they’re used to pull in client-side dependencies and tools.

Image 12

The bower dependencies are controlled by the bower.json file. Each dependency is then further configured in its own section within the bower.json file, indicating how it should be deployed to the wwwroot folder when the bower task is executed.

JavaScript
{
  "name": "ASP.NET",
  "private": true,
  "dependencies": {
    "bootstrap": "3.0.0",
    "jquery": "1.10.2",
    "jquery-validation": "1.11.1",
    "jquery-validation-unobtrusive": "3.2.2",
    "hammer.js": "2.0.4",
    "bootstrap-touch-carousel": "0.8.0"
  }
}

By default, the bower task is executed using gulp, which is configured in gulpfile.js. he current web template’s gulpfile includes tasks for copying and cleaning script and CSS files from the bower folder to a /lib folder in wwwroot. Here is the gulpfile.js:

JavaScript
/// <binding Clean='clean' />

var gulp = require("gulp"),
  rimraf = require("rimraf"),
  fs = require("fs");

eval("var project = " + fs.readFileSync("./project.json"));

var paths = {
  bower: "./bower_components/",
  lib: "./" + project.webroot + "/lib/"
};

gulp.task("clean", function (cb) {
  rimraf(paths.lib, cb);
});

gulp.task("copy", ["clean"], function () {
  var bower = {
    "bootstrap": "bootstrap/dist/**/*.{js,map,css,ttf,svg,woff,eot}",
    "bootstrap-touch-carousel": "bootstrap-touch-carousel/dist/**/*.{js,css}",
    "hammer.js": "hammer.js/hammer*.{js,map}",
    "jquery": "jquery/jquery*.{js,map}",
    "jquery-validation": "jquery-validation/jquery.validate.js",
    "jquery-validation-unobtrusive": "jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"
  }

  for (var destinationDir in bower) {
    gulp.src(paths.bower + bower[destinationDir])
      .pipe(gulp.dest(paths.lib + destinationDir));
  }
});

Server Side Dependencies:

The references folder contains server side dependencies. In Asp.Net 5 we see two different framework dependencies ASP.NET 5.0 vs. ASP.NET Core 5.0. Each reference icon represents whether it is a NuGet package or a project.  All dependencies are checked at compile time and any missing references will be restored from NuGet.

Image 13

Configuration:

As a .Net developer, one thing over the years hasn’t changed is the application configuration (web.config or machine.config) file usually written in XML format. ASP.NET 5 uses a new configuration model for handling of simple name-value pairs that is not based on System.Configuration or web.config. The built-in configuration providers support a variety of file formats (XML, JSON, and INI) and also environment variables to enable environment-based configuration. You can add as many different configuration files as makes sense for your app. You can also write your own custom configuration providers for different environments, like Development, QA and Production etc.

Application Startup:

The projects Startup.cs class wires up configuration, MVC, EF, Identity services, logging, routes, and more. There by allowing us to add modules that add value to our project and skip the ones which are not required and make a lean web project.

There are three parts to the sample startup class: a constructor, ConfigureServices, and Configure. The constructor specifies how configuration will be handled by the app. The ConfigureServices method is used to specify which services are available to the app. Finally, The Configure method is called after ConfigureServices and is used to configure middleware.

Services in ASP.NET 5 come in three varieties: singleton, scoped and transient. Transient services are created each time they’re requested from the container. Scoped services are created only if they don’t already exist in the current scope. For Web applications, a container scope is created for each request, so you can think of scoped services as per request. Singleton services are only ever created once.

K Command Codenames, DNX and DNX Core:

K is the codename stands for .NET Core Version 1. Also used when you run the application in the command line. The K command is your entry point to the runtime.

DNX is nothing but the .NET Execution Environment. Its code name is called as “K” Command Line Tools.

KPM – Core Package Manager. Now it is being represented as DNU (Dot Net Updater) The package manager, KPM, is the command to restore packages, install packages, pack your application for deployment, etc., means anything to do with using packages or packaging your application using packages.json file.

KLR – Core Language Runtime. KLR.exe would be used for scenarios such as building and running from the command line when self-hosting in development.

KRE – Core Runtime Engine. Now called as DNX (Dot Net Executable Runtime). KRE is used to bootstrap and run an ASP.NET environment using projects.json file. You can use KVM to get and manage KRE versions.

KVM – Core Version Manager. Now called as DNVM (Dot Net Version Manager). KVM is a PowerShell script used to get the runtime and manage multiple versions of it being on the machine at the same time. With this you can upgrade to the latest version and switch between versions as required.

Package Manager (DNU) depend on the Runtime Engine (DNX) and Runtime Engine (DNX) inturn depends on Version Manager (DNVM).

So what’s new in C# 6?

Roslyn Compiler:

The best thing about Asp.Net5 is the Roslyn compiler. To discuss entirety about Roslyn we need to check github.

Static Using: Using static for namespaces and thereby eliminating fully qualified names while accessing method, properties etc.,

Old:

C#
Console.WriteLine("Hello World");

New:

C#
// Declaring Namespace
Using static System.Console;

// Somewhere in the code
WriteLine("Hello World ");

Auto Property Initializers: Instead of creating constructor with setters like:

Old:

C#
public Customer()
{
  customerID = Guid.NewGuid();
}

New:

C#
public Guid customerId { get; set; } = Guid.NewGuid();

Dictionary Initializers: The new dictionary initializers will eliminate any confusion while setting Values to its corresponding Key elements.

Old:

C#
public Dictionary<string,string> custNames = new Dictionary<string,string>()
{
    {"Sree", "Chess" },
    {"Vamsi","Carom"}
};

New:

C#
public Dictionary<string,string> custNames = new Dictionary<string,string>()
{
    ["Sree"] = "Chess",
    ["Vamsi"] = "Carom"
};

Selection Exceptions in a Try... Catch Block: Choice of handling the exception based on the certain criteria.

New:

C#
try{
   throw new Exception("More Bad");
}
catch(Exception ex) if (ex.Message == "Some Bad Ex"){
    // Handle exception in A way
}
catch (Exception ex) if (ex.Message == "More Bad"){
    // Handle exception in Another way
}

Async/Await in Error Handling:

C#
public void func(){
    Task task = new Task(SomeFunc);
    task.start();
    task.wait();
}

public static async void SomeFunc(){
    try{
        throw new Exception("Error");
    }
    catch{
        await Task.Delay(2000);
    }
    finally{
        await Task.Delay(2000);
    }
}

nameOf Expression:

Old:

C#
if (name!=null) throw new Exception("name");

New:

C#
if (name != null) throw new Exception(nameOf(name));

String Interpolation:

Old 1:

C#
Console.WriteLine("Name : "+ fName + " " + lName);

Old 2:

C#
WriteLine(string.Format("Name : {0} {1}",fname, lName);

New:

C#
WriteLine($"Name : {fName} {lName}");

We may see more such AngularJS syntax in C# in later releases.

"Dependency Injection" Default implementation using Inversion of Control (IoC): If you look at the Startup.cs file, the constructor itself is implementing dependency injection by passing interface IHostingEnvironment as parameter instead of creating an object.

C#
public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        // Setup configuration sources.
        Configuration = new Configuration()
            .AddJsonFile("config.json")
            .AddEnvironmentVariables();
    }
   // some other configuraton code
}

Environment tags: Render CSS and JavaScript libraries as per the selected environment using <environment> tags.

HTML
<environment names="Development">
    <link rel="stylesheet" href="~/lib/bootstrap/css/bootstrap.css" />
    <link rel="stylesheet" href="~/lib/bootstrap-touch-carousel/css/bootstrap-touch-carousel.css" />
    <link rel="stylesheet" href="~/css/site.css" />
</environment>

Usage of asp-controller and asp-action: Asp.Net5 team now simplified Razor syntax and @Html helpers so that people less familiar with razor syntax (like frontend developers etc.,) could understand and work accordingly. There by adding asp-controller and asp-action attributes to an anchor or form tag.

HTML
<div class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
        <li><a asp-controller="Home" asp-action="Index">Home</a></li>
        <li><a asp-controller="Home" asp-action="About">About</a></li>
        <li><a asp-controller="Home" asp-action="Contact">Contact</a></li>
    </ul>
</div>

Here is the new <Form> tag:

HTML
<form asp-controller="Account" asp-action="Register" method="post" class="form-horizontal" role="form">
    Some html form content
<form>

Render partial views using Async: New @async syntax and helper to load partial views

C#
@await Html.PartialAsync

// or

@{await Html.RenderPartialAsync(…) }

Validation summary with asp-validation-summary:

HTML
<div asp-validation-summary="ValidationSummary.All" class="text-danger"></div>

Amazing "fallback mechanism" for links and script tags: <link> and <style> tags are now going to have fallback mechanism: Isn’t it great?

For <link> using attributes: href, asp-fallback-href, asp-fallback-test-class, asp-fallback-test-property, asp-fallback-test-value

HTML
<environment names="Staging,Production">
    <link rel="stylesheet" href="//ajax.aspnetcdn.com/ajax/bootstrap/3.0.0/css/bootstrap.min.css"
                  asp-fallback-href="~/lib/bootstrap/css/bootstrap.min.css"
                  asp-fallback-test-class="hidden" asp-fallback-test-property="visibility" asp-fallback-test-value="hidden" />
    <link rel="stylesheet" href="//ajax.aspnetcdn.com/ajax/bootstrap-touch-carousel/0.8.0/css/bootstrap-touch-carousel.css"
                  asp-fallback-href="~/lib/bootstrap-touch-carousel/css/bootstrap-touch-carousel.css"
                  asp-fallback-test-class="carousel-caption" asp-fallback-test-property="display" asp-fallback-test-value="none" />
    <link rel="stylesheet" href="~/css/site.css" />
</environment>

For <script> using atttibutes: src, asp-fallback-src, asp-fallback-test

HTML
<environment names="Staging,Production">
    <script src="//ajax.aspnetcdn.com/ajax/jquery/jquery-1.10.2.min.js"
                    asp-fallback-src="~/lib/jquery/jquery.min.js"
                    asp-fallback-test="window.jQuery">
    </script>
    <script src="//ajax.aspnetcdn.com/ajax/bootstrap/3.0.0/bootstrap.min.js"
                    asp-fallback-src="~/lib/bootstrap/js/bootstrap.min.js"
                    asp-fallback-test="window.jQuery">
    </script>
</environment>

Summary

Looking at the changes .Net team applied to Asp.Net 5 and Visual Studio it promises a bright future for .Net developers. Write appliaction in Visual Studio and deploy it on any platform.

Hope you all get something new to learn from this article.

Note: So far there are the changes I found in Asp.Net 5 and C# 6. I will update this article as and when I see new features.

Source Code

Attached is the source code written in Visual Studio RC 2015.

Download AspNet2015.zip

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionvs 2015 updates ? Pin
kiquenet.com7-Jun-16 10:11
professionalkiquenet.com7-Jun-16 10:11 
Questionvery informative Pin
saxenaabhi624-Jul-15 3:55
saxenaabhi624-Jul-15 3:55 
AnswerRe: very informative Pin
Sreekanth Mothukuru24-Jul-15 4:18
Sreekanth Mothukuru24-Jul-15 4:18 
Questionvery informative. Pin
saxenaabhi624-Jul-15 3:56
saxenaabhi624-Jul-15 3:56 
AnswerRe: very informative. Pin
Sreekanth Mothukuru24-Jul-15 4:19
Sreekanth Mothukuru24-Jul-15 4:19 
QuestionShocked that they shipped... Pin
Dewey22-Jul-15 20:33
Dewey22-Jul-15 20:33 
AnswerRe: Shocked that they shipped... Pin
Sreekanth Mothukuru22-Jul-15 22:23
Sreekanth Mothukuru22-Jul-15 22:23 
GeneralRe: Shocked that they shipped... Pin
Dewey23-Jul-15 21:27
Dewey23-Jul-15 21:27 
GeneralRe: Shocked that they shipped... Pin
Sreekanth Mothukuru24-Jul-15 4:18
Sreekanth Mothukuru24-Jul-15 4:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.