Saturday, July 2, 2016

Building a web application using ASP.NET Core 1.0, Aurelia, TypeScript, Webpack in Visual Studio Code – Part 1

Introduction

YouTube Video Link:

This is the first part of Building a web application using ASP.NET Core 1.0, Aurelia, TypeScript, Webpack in Visual Studio Code.

The source code for this tutorial is available on GitHub.

It is very exciting to see Microsoft developing their .NET platform, libraries and languages out there in github as open source. It is also nice to see that .NET Core and ASP.NET core are now cross platform, which means that developers using OSX and Linux can start using .NET and C# in their favorite Operating Systems without having to install Windows. On the front end side, JavaScript has become ubiquitous and every day you see some new JavaScript library or framework coming into existence. Everyone is talking about ECMAScript, TypeScript, standardization, web components, modules etc. Node.Js took JavaScript to server side and opened up endless possibilities. NPM hosts a lot of JavaScript libraries and frameworks (both client and server side). JavaScript frameworks that already leverage the future standards like ECMAScript 2015 (ES6), ECMAScript 2016 (ES7), TypeScript, a super set of ECMAScript with additional compile time (or transpile time :) ) type checking to avoid runtime errors etc., require support for modules, minification, bundling etc. So, quite a few build tools like grunt, gulp started appearing to support the needs of modern web applications. Webpack took building modular web applications to the next level by treating anything and everything as modules and not only your JS files and other productivity enhancements like hot module replacement, compilation of TypeScript/ECMAScript to JavaScript, LESS/SCSS to CSS etc.

If you were to a build a modern web application today, you have plenty of choices for the back end, front end and build tools. In this series of posts, I'm going to show how to create a modern web application using ASP.NET Core 1.0, AureliaJs, TypeScript and Webpack in Visual Studio Code. Lets get started.

 

Pre-requisites

Please have the following tools/frameworks installed before following this tutorial to create a modern web application.

Tool/Framework

Url

.NET Core 1.0

https://www.microsoft.com/net/core#windows
Cmder
http://cmder.net/
NodeJs (NPM)

https://nodejs.org/en/
Visual Studio Code v1.2
VS Code Extensions:
C#


TSLint

https://code.visualstudio.com/Download 

https://marketplace.visualstudio.com/items?itemName=ms-vscode.csharp

https://marketplace.visualstudio.com/items?itemName=eg2.tslint

 

Creating the web application

Launch Cmder and create a folder named "tutorial\part1" in your C:\ as follows:

fig1

Install Yeoman and asp.net code generator using npm:

npm install -g yo generator-aspnet
Now, let us create a template asp.net application using the ASP.NET generator for yo:
yo aspnet
The generator is an interactive application and you can use arrow keys to select the menu options and hit enter. For our tutorial, select Empty Web Application as the application type and give it the name “modern”.
fig2
 
Now, let us launch Visual Studio Code to take a tour of the application generated by yeoman. You need to change your directory to “c:\tutorial\part1\ modern”and type “code .

fig3

Once VS Code is launched,  it will ask you if would like VS Code to add the required assets to build and debug the project and you just click “Yes”:

fig4

VS Code will create 2 files: launch.json and tasks.json under the folder “.vscode” within the project directory. The file “launch.json” contains the settings to launch the asp.net core application. To start the application, press Ctrl+Shift+D and then click the green play button or just hit F5, which will launch the application in debug mode. There is one known limitation of the project.json generated by yeoman, which will prevent us from setting breakpoints in our code from within VS Code. Luckily, the fix is very straightforward. We just need to add the setting "debugType": "portable" inside "buildOptions" setting in project.json.

fig7

Now, you should be able to run the application. By default, asp.net core uses Kestrel webserver that starts serving the application using the url: http://localhost:5000. You should see the message “Hello World!”

fig5

Congratulations! We have just created a Hello World web application in ASP.NET Core! It is time that we add MVC framework and render an actual view instead  of directly sending a string like “Hello World” into the response stream.

Adding MVC framework

In ASP.NET MVC 4.6 applications developed in Visual Studio 2015, we have this nice “References” hive inside the solution explorer. We are used to right clicking on that hive and “Add References” or “Manage Nuget references” to add references to any .NET Assemblies. How do we that in ASP.NET Core? It is very simple. We just need to open up project.json and add our dependencies into project.json

fig10

For MVC framework, we’ll add the dependency “Microsoft.AspNetCore.Mvc”: “1.0.0” into project.json. VS Code provides intellisense support for all of these json files like project.json, which means that if you start typing the first few characters, VS Code will show the suggestions and you can autocomplete it. Now that we’ve added the Mvc dependency, we can start using it. The place to wire Mvc in ASP.NET Core application is Startup.cs.

Startup class has two important methods: ConfigureServices and Configure. As the name implies, you should add the services inside ConfigureServices method and use them inside Configure method as shown below:

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

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        
{
   ...
   app.UseMvc(routes => {
        routes.MapRoute(    
             name: "default",
             template: "{controller=Home}/{action=Index}/{id?}");          
        });   
}

It is not enough if we just wire MVC in the Startup class. We need to define at least one controller and a view that goes along with the controller. In the UseMvc method, we defined the template for the url routes like this: {controller}/{action}. If no controller and action are specified, the route will default to Home/Index. So, at the least we need to define a controller named HomeController and a view named Index if we were to just navigate to the default url:  http://localhost:5000 without specifying the controller and action in the url. Let us use yeoman aspnet generator to generate an MvcController and a MvcView. Mvc is a convention based framework, which expects certain folders to be present inside the project. For e.g., a Controllers folder where you can create the C# Controller classes and a Views folder with the sub folder that matches the name of the Controller class without the word “Controller” where you can create CSHTML razor views.

Adding Mvc Controllers, Views using Yeoman aspnet sub generators

Aspnet generator has a very good list of sub generators for generating Controller, View, WebApiController etc.,  to help us develop ASP.NET Core applications faster. To see the full list of aspnet sub generators, use the command:

yo aspnet --help

Now, lets create those folders: Controllers and Views inside our project. Using yeoman’s aspnet sub generator, create the HomeController class as follows:

yo aspnet:MvcController Home

After the controller class is created, create a sub folder named “Home” under “Views” folder and then create Index razor view using yo as follows:

yo aspnet:MvcView Index

After yo generated the Index.cshtml in “\Views” folder, remember to move the file into “\Views\Home” subfolder. Your folder structure should look like this after generating the controller and view:

fig8

Change the implementation of the Index method in HomeController to explicitly return the “Index” view and pass a model argument to that view.

public IActionResult Index()
{
   return View("Index", "Hello World from ASP.NET Core 1.0!");
}
Add a @model directive with the data type as “string”. Assign the model argument passed from the controller method into “ViewBag.Titile” property and display the property using h1 tag.
@model string
@{
    ViewBag.Title = Model;
}
<h1>@ViewBag.Title</h1>

It is good to see Mvc in action! In the introduction, I talked briefly about a plethora of choices available in the back end, front end and build tools. The trend towards building applications has changed a lot in the last few years. Instead of building the web application using server side frameworks and custom server side markups using ASP.NET MVC and Razor,  people prefer using the ASP.NET Web API to build the RESTful API endpoints leveraging the power of C#, .NET Framework, Entity Framework etc., and build the front end using HTML5, CSS3 and several JavaScript libraries like jQuery, momentjs or full blown frameworks like Aurelia, Angular2 or React.

Adding a Web API Controller

So, before we dive into the client side, let us add a simple Web API into our web application. In ASP.NET Core, you no longer need to think about if you should be inheriting your Controller class from “Controller” or “ApiController” because they are now unified into just “Controller”. You must have guessed by now that I’d be using our friend “yo” to create a Web API controller. Here’s the “yo” command to create our GreetingsController:

yo aspnet:WebApiController GreetingsController

Let us clean up the GreetingsController to just include a simple Get() method to return the This is the first part of Building a web application using ASP.NET Core 1.0, Aurelia, TypeScript, Webpack in Visual Studio Code. string “Hello Word from ASP.NET Core 1.0 Web API!”. Your Get() method should look like this:

[HttpGet]
public string Get()
{
      return "Hello World from ASP.NET Core 1.0 Web API!";
}

Hit F5 and change the url in the browser to http://localhost/api/greetings . You should see the message “Hello World from ASP.NET Core 1.0 Web API!” displayed in your browser.

fig9

That concludes part 1 of this series! Happy coding!



4 comments:

  1. Hello Mani,

    Nice post, you have introduced cmder to me which is cool.

    Thanks.

    ReplyDelete
  2. Praveen, glad to hear that you found Cmder to be useful to you.

    ReplyDelete
  3. I am looking for something like this but using Visual Studio rather than Code. There will be plenty new to learn without a new IDE.

    Kal

    ReplyDelete
  4. Great Content. It will useful for knowledge seekers. Keep sharing your knowledge through this kind of article.
    Visit us: Java Online Training Hyderabad
    Visit us: Java Training
    Visit us: Java Course
    Visit us: java course
    Visit us: Java Online Course

    ReplyDelete