Monday, July 18, 2016

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

Introduction

YouTube Video Link for Part 4:

This is the fourth 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.

In Part 3 of this series, we setup TypeScript, Typings, created a tsconfig.json and wrote our first TypeScript class. In this part, we’ll focus on setting up Aurelia and Webpack. Let us get started.

Prerequisites

Please create a new folder named “part4” under “C:\tutorial”. You’ll need the source code from part3 to practice this part of the series. You can pull the source code from my github repository: https://github.com/rajajhansi/aspnetcore-aurelia-tutorial . After you got the source code, delete the “.git” directory.

Aurelia

Aurelia is developed by Duranda Inc., a company founded by Rob Eisenberg (popular for his blog Eisenberg Effect)  who has proven track record on front end frameworks like Caliburn.Micro, DurandalJs and now Aurelia.  Aurelia is a modern, forward-thinking, conventions based JavaScript framework leveraging web  standards. Aurelia itself is developed using ES2016 and comprises of smaller, focused modules. If you are someone who is more comfortable using an enterprise support and consulting, Durandal Inc., the company that develops Aurelia offers those services as well. I’ve been very impressed with the way they have been developing this framework in open, taking active feedback, involving the community and most importantly quickly releasing beta and RC versions. At the time of this writing, Aurelia is in its RC release.

Aurelia TypeScript-Webpack-Skeleton-Navigation Project

If you would like to setup Aurelia project using TypeScript and Webpack, you can get started real quick using the aurelia-tyepscript-webpack skeleton navigation project. In this part of the series, we are going to use that skeleton project as our base, clean up unwanted files and start building our application. To setup the skeleton project, you need to either clone or download the aurelia/skeleton-navigation project from aurelia’s github repository url: https://github.com/aurelia/skeleton-navigation 

We do not want to clone/download the skeleton-navigation project into “c:\tutorial\part3\modern”. Instead, let us create a staging folder “c:\staging” for the skeleton-navigation and then run git clone from within “c:\staging’'” from cmder as follows:

mkdir staging

cd staging

git clone https://github.com/aurelia/skeleton-navigation

fig1_thumb[1]

Adding skeleton-navigation into our source code

In part 2, we started our development by copying the source code from part 1. In this part, we will copy the skeleton-navigation source code into “c:\tutorial\part3\modern” first and then copy only the asp.net core 1.0 server side code and the associated project.json file. Doing it the other way i.e., first copying the source code from part2 and then copying selected folders/files from skeleton-navigation would be cumbersome and error prone. Please follow these steps to successfully add skeleton-navigation into our source to create the source code for part3:

1. Copy the contents of “C:\staging\skeleton-navigation\skeleton-typescript-webpack” into C:\tutorial\part4\modern”:

fig2_thumb[2].

2. Copy all files and folders from C:\tutorial\part3\modern except the following files/folders into C:\tutorial\part4\modern:

.vscode, bin, node_modules, obj, src, .gitignore, package.json, project.lock.json, tsconfig.json

fig3_thumb[4]

3. While you are copying, if you get conflicts about the files: README.md and tsconfig.json , just go ahead and overwrite them.

4. Copy launch.json and tasks.json from part3\modern\.vscode into into part4\modern\.vscode

5. If you would like to check in the source code in part 3 into github, then you need to merge the .gitignore file from part3 with .gitignore file from part4. Since part3\.gitignore has more entries, it makes total sense to copy the contents of part3\.gitignore into VSCode or any other text editor and copy everything but node_modules from the contents of part3\.gitignore and save the merged content as part4\.gitignore

Running the integrated skeleton-navigation source code without using Kestrel web server

Open up cmder and change your directory to “C:\tutorial\part4nnp\modern”. Then, run the following commands in the same order:

npm install 
npm start

That should start the webpack-dev-server on localhost:9000 after bundling the modules. You can launch chrome browser and visit the url: http://localhost:9000 to see the aurelia-skeleton-navigation application in action. Now, it is time for us to use our Greeter class that we built in part 3. Copy greeter.ts from c:\tutorial\part3\modern\app\src into C:\tutorial\part4\modern\app folder.

Note: Make sure to delete Page.aspx.cs and Redirect.aspx.cs from c:\tutorial\part4\modern\node_modules\selenium-webdriver\lib\test\data because VSCode will try to compile those files and will throw errors because those are Selenium’s ASP.NET pages developed using ASP.NET and not Asp.Net Core 1.0.

Power of easy-webpack

In my previous part, you should have noticed how difficult it is to create a working webpack.config.js. Although Webpack is very powerful, it is changing quickly and the documentation and samples aren’t catching up with the implementation as fast as we would like. This is not a complaint because open source software like Webpack needs more contributors and help. Instead, what we see in their github.io page is developers posting harsh comments about the documentation and demanding everything, which is not correct. Luckily, Aurelia core team member Bazyli Brzóska created Easy Webpack, a project to simplify and modularize Webpack configuration. I want to give a shout-out to Bazyli for his awesome Easy Webpack project. Easy Webpack allows anyone to use the default configuration or augment or completely override the default.

Creating our first Aurelia Component

In MVVM frameworks, UI components have two parts: a view, written in HTML and a view-model that provides data and behavior to the view. Aurelia’ components also use the concept of view and view-model and uses databinding to link them together. Follow these steps to turn our greeter class into an Aurelia view model class and render “greetingMessage” accessor in a view:

Export the class by adding the keyword export before “class Greeter {

We need to export the class so Aurelia and other parts of the application can use our class. If we don’t export the class, it is a private class that no one can access from other classes or html pages. Since Aurelia will invoke this view model, let us add a default value to the message field like this:

constructor(private message: string =”World”) {

}

Let us create a view page that has the same name as the class with .html extension i.e., greeter.html as follows:

<template>
    <div>
       <h1>${greetingMessage}</h1>
       <h2 value.bind="greetingMessage"></h2>
    </div>
</template>

Aurelia leverages the Web Components standards. HTML templates defined using <template> tag is a part of Web Components standard. It allows us to define inert DOM subtrees i.e., HTML chunks that the browser will not act upon. You need to write code to read the chunk and render it. The process of activating that chunk is called “stamping out a template”. In our case, Aurelia takes care of rendering this chunk in browser. If you’re curious about how to do it yourself, check out http://www.html5rocks.com/en/tutorials/webcomponents/template/

Now that we have defined our view model and view, let us focus on wiring them into Aurelia.

Bootstrapping Aurelia

As always, index.html page is where we’ll define the bundle.js, that comprises of all js files that constitute the application.  For Webpack users, aurelia had implemented a package named aurelia-bootstrapper-webpack. There are two kinds of bootstrapping in Aurelia: declarative and manual. In declarative bootstrapping, we need to designate a HTML element using the aurelia-app attribute, where Aurelia’s bootstrapper will load an app and app.html by convention, databind them together and inject them into that HTML element. In our index.html, we have added “aurelia-app” attribute to the <body> tag to indicate the bootstrapper to load our app view-model and its view, conventionally located in app.ts and app.html.

In manual bootstrapping,  you’ll invoke the aurelia bootstrapper’s bootstrap method that takes a function as an argument. That function receives an instance of Aurelia class. Using that instance we can specify the startup configurations like plugins, logging etc., and then invoke the start() function, which is a promise. Upon starting, aurelia sets the Root component of our aurelia application using the setRoot functions that takes 2 arguments: viewmodel and the HTML element where the view should be injected.

Since we are using aurelia with Webpack and Webpack has a way to specify the entry class, we’ll use main.ts as our entry point and use manual bootstrapping as follows:

import {Aurelia} from 'aurelia-framework';
import {bootstrap} from 'aurelia-bootstrapper-webpack';
import 'bootstrap'; bootstrap(async (aurelia: Aurelia) => {
  aurelia.use
    .standardConfiguration()
    .developmentLogging();   const rootElement = document.body;
  rootElement.setAttribute('aurelia-app', '');   await aurelia.start();
  aurelia.setRoot('greeter’, rootElement);
  });

Wiring Greetings API controller into Aurelia

A simple greeter class is a good staring point to understand Aurelia. As you all know, SPA (Single Page Applicatios) build their business logic as RESTfule APIs and invoke them from client side using client side frameworks like Aurelia and then dynamically inject markup into browser’s DOM. It is time for us to wire our GreetingsController’s API method into our greeter class and render the API method’s return value inside the browser;

To invoke a Web API, Aurelia provides two modules: aurelia-http-client and aurelia-fetch-client. Both of them define the class HttpClient but with a different implementation.

aurelia-http-client

aurelia-http-client is a basic HttpClient that provides a nice wrapper interface to the browser’s XMLHttpRequest obect. It provides methods that match the HTTP verbs like GET, POST, DELETE, PUT, PATCH besides supporting a configure method where we can define base url, headers etc., for all requests as well as a createRequest method that we can define base url, headers etc., for each request. It also provides hooks into request and response using interceptors.

aurelia-fetch-client

aurelia-fetch-client embrace and implement the new Fetch API,  a specification that you can find in Mozilla Developer Network (MDN) documentation. This client library also provides default configuration of request parameters, interceptors and centralized request tracking.

Enabling CORS in our API Controllers

Since Asp.Net Core’s Kestrel web server uses port 5000 to serve the APIs and our client webpack-dev-server is running on port 9000, we can’t invoke calls to the API unless we enable Cross Origin Resource Sharing. Using CORS, a server can explicitly allow some cross-origin requests. We should enable cross-origin requests coming from http://localhost:9000 in our APIs. To enable CORS,

1. We need to add reference to “Microsoft.AspNet.Cors

2. Call services.AddCors() extension method in Startup.cs’s ConfigureServices method

3. Call UseCors with required parameters inside Configure method in Startup.cs  like this:

app.UseCors(builder =>
               builder.WithOrigins("http://localhost:9000")
                   .AllowAnyHeader().AllowAnyMethod());

Invoking GreetingsController’s Get method from Aurelia

We are going to aurelia-fetch-client’s HttpClient class to invoke the GreetingsController API’s Get method. Aurelia has DI (Dependency Injection) at its core implemented using @inject decorator. Decorators are defined in ECMScript 7 and TypeScript already implements decorators. Aurelia support Lazy initialization using the Lazy class. Like we did in earlier parts, we need to import those classes defined in the aurelia modules. inject is defined in ‘aurelia-framework’ and HttpClient is defined in ‘aurelia-fetch-client’. Let us import them like this:

import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-fetch-client';

To inject an instance of HttpClient, let us the inject decorator with Lazy.of method right above the like where greeter is defined like this:

@inject(HttpClient)
export class Greeter { 

We need to define a parameter that receives the injected instance of HttpClient like this:

constructor(private httpClient: HttpClient, private message: string = “World”){
http.configure(config => {
     config
       .useStandardConfiguration()
       .withBaseUrl("http://localhost:5000/api/")
   });
}

We are going to leverage Aurelia’s Screen Activation Lifecycle’s activate() hook to wire our web Api. activate() hook allows us to perform custom logic before our view-model is displayed. Our activate() method should be defined like this:

async activate(): Promise<void> {
      this.httpClient.configure( (config: any) => {
      config
     .useStandardConfiguration()
     .withBaseUrl("http://localhost:5000/api/")
      });       const http = this.httpClient;
      const response = await http.fetch("greetings");
      this.greetingMessageViaApi= await response.json();
  }

We have added a new field named “greetingMessageViaApi” in our Greeter class to store the return value from our GreetingsController Web Api’s Get() method. Now, lets change the view to render the greetingMessageViaApi field like this:

<h2>${greetingMessageViaApi}</h2>        
<input type="text" value.bind="greetingMessageViaApi"></input>

value.bind attribute is used for two way binding in Aurelia. To see the two way binding in action, if you modify the text inside the text box, you’ll see the <h2> tag also shows the modified value because both <input> and <h2> are data bound to greetingMessageViaApi field of Greeter view-model.

In this part of the series, we have seen a quick introduction to Aurelia, easy-webpack and wrote our first Aurelia component and saw the two way data binding in action. In the next part of the series, I’ll show you how we can build a simple ToDoMvc application from the ground up using Aurelia. Happy coding!

Wednesday, July 6, 2016

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

Introduction

YouTube Video Link for Part 3:

This is the third 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.

In Part 2 of this series, we setup TypeScript, Typings, created a tsconfig.json and wrote our first TypeScript class. In this part, we’ll focus on setting up Aurelia and Webpack. Let us get started.

Prerequisites

Please create a new folder named “part3” under “C:\tutorial”. You’ll need the source code from part2 to practice this part of the series. You can pull the source code from my github repository: https://github.com/rajajhansi/aspnetcore-aurelia-tutorial . After you got the source code, delete the “.git” directory.

Webpack

Webpack is a powerful module bundler that takes the concept of modules to static assets like image files and stylesheets besides JavaScript files. Webpack supports code splitting via chunks, loaders that can transform resources into JavaScript and has a rich Plugin system. Webpack is well suited for big projects that use lots of 3rd party libraries, modules built using ES2015, 2016, TypeScript and stylesheets built using SASS/LESS. Webpack has a cool featured named HMR (Hot Module Replacement) that improves productivity during development of web applications. The webpack-dev-server is a little node.js Express server that supports HMR. You no longer need to go through that vicious cycle of modify, transpile and serve the application. HMR does that for you out of the box! Do not use webpack-dev-server for production deployment. I’ll show you how you can use ASP.Net Core 1.0 to server the bundles created by Webpack later in this post.

Before I introduce Aurelia, let us see how to configure Webpack to run our Greeter class using modules instead of including using <script src=””></script>. Install the latest version of webpack by specifying the version using npm as follows:

npm install webpack@2.1.0-beta.15 --save-dev

It is very important the fundamentals of Webpack clearly before I start showing you how to use Webpack with TypeScript and Aurelia. So, let me show you one step at a time on how you can use TypeScript compiler outside of Webpack to transpile .ts files into .js, introduce the concept of modules, how you can use TypeScript modules to start using one TypeScript class from another, load the generated modules in JavaScript using Webpack and finally show how to leverage typescript loader from within Webpack.

Modules

The concept of modules has been there for quite some time in JavaScript and are implemented using libraries. CommonJs and AMD (Asynchronous Module Definition) were (and still are) very popular module standards (or should I say non-standards) before the standards body has finally defined the syntax and semantics for modules in ES6.

When it comes to modules, you just need to remember two important things: export and import. As their names imply, “export” is used to export a symbol like class, function or variable and “import” is used to access the exported symbol from another module. In ES6, there are two kinds of exports: named exports i.e., several symbols per module and default exports i.e., only one symbol per module.

TypeScript has support for modules for quite some time. TypeScript’s modulesyntax is slightly different from ES6 but you can transpile TypeScript module into any module formats like: commonjs, amd and es6.

Adding a TypeScript class as an entry point

In any application be it console or windows or web application, we always need an entry point aka “main”. The convention is to either call the main or app classes. So, let us define an entry point class named  main.ts and import greeter class. Before we do that, lets export our Greeter class using the module syntax i.e., “export” as follows:

export class Greeter {
..
}

You can also export the Greeter class like this:

export { Greeter };

Let’s define our main class in main.ts:

import { Greeter } from "./Greeter";
export class Main {
    private greeter: Greeter;
    constructor() {
        this.greeter = new Greeter("World");
    }
    sayHello() {
        this.greeter.sayHello();
        document.getElementById("greeting").innerHTML = "<h1>" + m.greetingMessage + "</h1>";
    }
    get greetingMessage() : string {
        return this.greeter.greetingMessage;
    }
} var m = new Main();
m.sayHello();
console.log(m.greetingMessage);

Let us run tsc compiler in watch mode so it automatically transpiles .ts files whenever we add new .ts files or make changes to any .ts file like this:

tsc –w
Notice that in line 1, we import the Greeter class using the TypeScript "import" syntax. After the class definition, we create an instance of the class Main and invoke its sayHello method as well as greetingMessage accessor. We are doing that mainly to avoid having to import {Main} from "./Main" and invoking those methods from within Index.html because that would require the browser to understand ES6 module syntax and load it, which is not a feature available in current browsers.

Remember that we configured tsconfig.json to output js files with “commonjs” as the module format. So, TypeScript will happily transpile our TypeScript class into JavaScript that uses the CommonJs module syntax. But to use the modules transpiled by TypeScript, you still need a module loader library. Since Webpack is a module bundler that has module loaders as well, we’ll leverage Webpack for loading the modules. Let us bundle our transpiled js files using the webpack command:

webpack main.js bundle.js

We need to load the Main module from index.html in order for us to see the results in the browser. Here’s our index.html:

<html>
<head>
    <title>Welcome to ASP.NET Core 1.0</title>   
</head> <body>
    <div id="greeting">
    </div>
    <script src="app/bundle.js"></script>
</body> </html>

Webpack has a lot of command line options and it will become overwhelming for the users to enter them every time .So, you can create a webpack.config.js file at the root folder, where you can specify the configuration options and can just run wepack. For our example, here’s the webpack.config.js

module.exports = {
    entry: "./wwwroot/app/main.js",
    output: {       
        path: __dirname + "/wwwroot/app",
        filename: "bundle.js"
    }
};

Now, you should be able to run webpack without any arguments. After you run “webpack”, it will generate bundle.js that has the source code of main.js and greeter.js bundled and Webpack knows to how to load the modules inside of bundle.js.

fig0.1


Running the application

We can run our application from Visual Studio Code by hitting F5. After VSCode launches Chrome and shows the default page i.e., /Home/Index, just change the url to load index.html. Make sure to open the developer tools (by hitting F12) and you can see that webpack’s module loader loads bundle.js, which contains 2 other modules: main.js and greeter.js bundled within itself. You should see the message “Hello World from TypeScript!” in the browser window and the same message printed twice in Debugging console as well.

fig0

Although we got Webpack module loader working, we are still running the typescript compiler on watch mode to transpile .ts files. I talked about awesome-typescript-loader and it is time to wire that into our webpack.config.js.

Wiring awesome-typescript-loader into Webpack

We need to install awesome-typescript-loader (lets refer it as atl from now on) as a development type dependency using npm like this:

npm install awesome-typescript-loader --save-dev

After we installed atl, we can configure it in webpack.config.js by visiting the github page for atl at https://github.com/s-panferov/awesome-typescript-loader and copy pasting the sample configuration from there. Our webpack.config.js should look like this:

module.exports = {
    entry: "./src/app/main.ts",
    output: {       
        path: __dirname + "/wwwroot/app",
        filename: "bundle.js"
    },
    // Currently we need to add '.ts' to the resolve.extensions array.
  resolve: {
    extensions: ['', '.ts', '.webpack.js', '.web.js', '.js']
  },   // Source maps support ('inline-source-map' also works)
  devtool: 'source-map',   // Add the loader for .ts files.
  module: {
    loaders: [
      {
        test: /\.ts$/,
        loader: 'awesome-typescript-loader'
      }
    ]
  }
};

We no longer need to run tsc –w. If you’re already running it inside a tab in Cmder, just close that tab. Notice that I changed the entry property from “./wwwroot/app/main.js” to “./src/app/main/ts” because Webpack will take care of the transpiling using atl. Delete the contents of wwwroot\app folder and let Webpack take care of transpiling the .js code, bundling them and loading them for us. Before running webpack, just remove the inlineSourceMap and inlineSources options with “sourceMap”: true in tsconfig.json.  If you run webpack, you should get a warning from atl like this:

fig0.2

The warning clearly says that we should add “exclude”":” property to speed up transpilation, which makes total sense. So, let us go ahead and add the “excludes” into tsconfig.json like this:

"exclude": [
            "node_modules"           
  ]

You can now run webpack and it should generate bundle.js and bundle.js.map files.

fig0.3

Hit F5 from VSCode and after it launches Chrome, change the url to http://localhost:5000/index.html and you should get the same output like before. The main difference is that now transpiling, bundling and module loading are all taken care of by Webpack!!! In the next part of the series, I’ll show how to setup Aurelia framework from scratch and kick start a new project using Aurelia’s typescript-webpack-skeleton navigation project as the foundation. Happy coding!



Sunday, July 3, 2016

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

Introduction

YouTube Video Link for Part 2:

This is the second 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.

In Part 1 of this series, we setup a ASP.NET Core project with simple Mvc and WebApi Controllers. In this part, we’ll focus on setting up the client side tools and frameworks required to build a modern web application. Let us get started.

Prerequisites

Please create a new folder named “part2” under “C:\tutorial” and copy the contents of “C:\tutorial\part1\modern” into “C:\tutorial\part2\modern”. If you are familiar with git and use github, you can pull the source code from my github repository: https://github.com/rajajhansi/aspnetcore-aurelia-tutorial . After you got the source code, delete the “.git” directory before you copy the contents into “C:\tutorial\part2\modern”.

TypeScript

I’ve chosen TypeScript, which is a super set of ECMAScript as the choice for developing client side code. VS Code has very good support for building TypeScript applications. Since TypeScript uses the features in ES2015 (ES6) and ES2016 (ES7) specifications, code written in TypeScript must be converted to ES5, which is the version that is supported on all browsers. Although a subset of ES6 features are available in Chrome, Edge and Firefox, modules and module loaders are not yet implemented natively. The conversion process from TypeScript or ES6/7 to ES5 is known as transpiling. Babel is a very popular transpiler out there.

Since TypeScript is all about types and type checking during transpile time, we need type definitions of popular JS libraries like jQuery, momentjs etc. Luckily, all modern and new JS frameworks like Aurelia, Angular2, React etc., ships the type definition files. Type definition files use the convention <name>.d.ts. We can download the typings of popular JS libraries using a tool named “typings”.

NPM

There are quite a few package managers out there but my choice is NPM because it hosts both server and client side frameworks. For .NET Core, we’ll still be using Nuget package manager. But, for the client side, I don’t want to use bower, jspm etc., because NPM hosts pretty much all popular JS libraries.

Installing client tools and libraries

Open up cmder and change your directory to “C:\tutorial\parts\modern”. Then, install the client side tools: TypeScript and typings using the command:

npm install typescript@next -g
npm install typings -g

Since TypeScript and typings are only required at the development time and need not have to be deployed into the web server, we don’t need to pollute our library dependencies. Hence they are installed globally. For those who get the project from source control like github, it is a good idea to add them as devDependencies into npm’s package.json as well using the following commands:

npm install typescript@next --save-dev
npm install typings --save-dev

NPM command line switch “--save-dev” indicates NPM that the packages are only development time dependencies. NPM updates its own package.json file that tracks whatever you install using npm. To check the versions of TypeScript and typings installed, run these commands:

tsc -v
typings –v
fig1

Project organization for client side source code

You might be wondering where should we create our client side source code files and how would ASP.NET core differentiate between server side vs client side code. Those are very genuine concerns and let us address them. In ASP.NET core applications, there is a dedicated folder named “wwwroot” from where the client side files would be served. So, let us create that folder under our project folder. We need to write code to let ASP.NET core serve static files in order for us to server html, css and image files. Just add a call to UseStaticFiles() method in Configure() method in Startup.cs right above the UseMvc() call where we configured the routes.

app.UseStaticFiles();
          
app.UseMvc(
                routes => { routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
});
          

Writing our first TypeScript class

Now, let us focus on writing our first class in TypeScript. Create a folder named src outside of wwwroot folder. Then, create a folder named “app” inside that “src” folder. TypeScript files should be created with .ts extension. Create a new file named “greeter.ts” with the following TypeScript code under “src\app” folder:

class Greeter {
    constructor(private message: string) {
    }
    sayHello() {
        console.log(`Hello ${this.message} from TypeScript!`);
    }

    get greetingMessage() : string {
        return `Hello ${this.message} from TypeScript!`;
    }
}

 

After creating the folders and greeter.ts, your directory structure should look like this: fig2

 

Transpiling TypeScript source code and using it from HTML

There are many ways to transpile a TypeScript file into JavaScript. Here are a few options:

1. Run tsc compile from command prompt with the source files as arguments. I would prefer running the tsc command with –watch switch so we don’t have to

2. Setup a tsconfig.json with all parameters required for TypeScript compiler. Any folder that contains tsconfig.json will be considered a TypeScipt project. This is the preferred approach because using tsc without any specific source files will use the parameters in tsconfig.json.

3. Use build tools like grunt or gulp and configure their typescript tasks, which would leverage tsconfig.json.

4. Use Webpack with awesome-typescript-loader that will transpile the TypeScript files into JavaScript files

For this part of the series, I’d go with creating tsconfig.json and running the command “tsc –watch” from cmder. Some of you might be thinking why couldn’t I leverage VSCode’s tasks.json to run tsc task. Unfortunately, at the time of writing this blog post, VSCode only supports one top level build task. Although many forums and discussions in Stackoverflow suggest that we can use “bash” or “cmd” as the top level command and add sub tasks to run typescript followed by dotnet CLI tools. IMHO, it is a total waste of time because you would be better off using gulp or grun as the top level command and use subtasks to run the individual tasks/targets within gulpfile/gruntfile.

Since I’ll be showing how to configure Webpack (the module loader/build tool of my choice) to transpile TypeScript into JavaScript in later parts of this series, let us use tsc compiler from the command line with “-watch” switch enabled to watch for changes in our project folder.

Creating a tsconfig.json project file

From within VSCode, add a new file named tsconfig.json that reads like this:

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "inlineSourceMap" : true,
        "inlineSources" : true,
        "sourceRoot": "src/app",
        "outDir": "wwwroot/app"
    }
}

Now, let us start the TypeScript compile with –watch option from cmder as follows:

tsc -watch

As soon as you type the command and hit enter, all .ts files in our project folder will be transpiled into .js files base on the settings inside of tsconfig.json. If you noticed, I have configured the outDir parameter to “wwwroot/app”, where the transpiled .js and .js.map (source map is used by browsers for debugging) will be generated.

fig4

fig5

Using the transpiled JavaScript files from index.html

Now, we need to start using those transpiled JavaScript files in our index.html. Add a <div> element, construct an instance of our Greeter class and use it’s greetingMessage property to set the innerHTML property of that <div>. Here’s the index.html:

<html>
<head>
    <title>Welcome to ASP.NET Core 1.0</title>
    <script src="app/greeter.js"></script>
</head>
<body>   
    <div id="greeting">
    </div>
    <script>
        var greeterObj = new Greeter("World");
        document.getElementById("greeting").innerHTML = "<h1>" + greeterObj.greetingMessage + "</h1>";       
    </script>
</body>

</html>

After making the changes in index.html, hit F5 to launch the browser, navigate to http://localhost:5000/index.html and you should see the message "Hello World from TypeScript!". Since we have enabled source map options inside tsconfig.json, we can also set breakpoints in TypeScript source files and debug in browsers.

fig3

We are now able to write our client side code using TypeScript. In the next part of the series, I’ll show how to setup Aurelia, a powerful, modern JavaScript framework and Webpack module bundler to continue building our modern web application. Happy coding!

Part 1: Building a web application using ASP.NET Core 1.0, AureliaJs, TypeScript, WebPack in Visual Studio Code – Part 1

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!