BlueLemonCode.Com

Yet Another Tech Blog

Advanced Client Side Development in vNext

Introduction

Visual Studio 2015 RC is already out and keeping with "Open Source" theme of Asp.net, there are tons of new features in good old VS which embraces classic frameworks/tools of client side web development.

In this detailed article, I will discuss more about common tools, functionality and "How To".

What's New?

Keeping up the commitment to open source community, Visual Studio now supports commonly used open source tools out of the box.
Not only that but Visual Studio projects now follows open source convention and generates "wwwroot" folder of all static content.
The VS editor also supports LESS, TypeScript out of box with promise to support many more "standards" in future (A definite shift in paradigm).

I am going to discuss the following changes which I am most impressed with.
(Please note that some of these features were already part of VS 2013)

  • Why 'wwwroot'
  • Why Bower and NPM?
  • Gulp and Grunt.. How and how?
  • Improvements in JavaScript editor
To explain these features, I am going to use Visual Studio 2015 RC. If you don't have it already, Now is the time to get it

Why wwwroot?

Once you install VS 2015, create a new project using "Asp.net 5 Preview Starter Web" template (although you can use any other template, the starter template will give you most of files that we are going to discuss below)


Can't find Web.config?


That's true web.config (or rather Asp.net project a whole) is now moving towards JSON based configuration from XML configuration so you can find three important project configuration files.

  • config.json - This is used to store application configuration information typically like application connection string (which is part of application configuration rather than project configuration)
Note: name "config.json" is not fixed name. You can easily change it in startup.cs
  • project.json - This includes all other project specific configuration details which is more readable and slick JSON configuration.

  • global.json - This is another configuration file which is resides in "Solution Items" folder and which basically maintains list of server side dependencies between multiple project. It is typical practice to have different C# projects for data operations, notifications, logging etc. in a single solution. This configuration file in parent directory is used to manage their dependencies

wwwroot is a specially designated folder to store all static content of web application (non-server code). This typically includes CSS, JavaScript and image files. This clearly separates all server code (C#/VB) in "src" folder and static or client side code in "wwwroot"

However, "wwwroot" is just a name of folder and you can name it as you like. You will simply have to change the "webroot" configuration in project.json file accordingly (check first configuration in above screen-grab of project.json)

Apart from separating static and server wwwroot also helps "Grunt" to automate bundling, minification tasks since all static content is combined in separate folder. We will see more details Grunt section

This is all good but what are other files present in root of default project? 

 

Why Bower and NPM?

Before we move to gulp and grunt, lets understand role of purpose of NPM & Bower.

Both of these are "Package Managers" similar to Nuget but they are widely used across different web platforms and are based on Node.js. (I am not going to discuss more about Node.js but I will strongly recommend you to check it out)

Note: Node.js is installed along with Visual Studio 2015 RC. So, if you are using this version of Visual Studio then you don't have separately install Node.js. Also, NPM gets installed along with Node
In summary, VS now contains three default package managers Nuget, NPM and Bower.

  • Nuget - Standard package manager by Microsoft which is mainly used for server side packages such as Entity framework or nHibernate, nUnit etc.
  • NPM - to get developer tools for client side development like Karma, grunt etc.
  • Bower - Client side library package manager for client libraries such as Angular.js, Bootstrap, Ember.js etc.

NPM (Node Package manager)

NPM is commonly used package manager for development tools based on Node.js. That means tasks like minification, installation of gulp/grunt etc. are normally done using NPM

For example, To install bower (another package manager) go to command prompt and run following command

npm install bower -g

This will install Bower in global scope so that you can now run bower command in any folder. 

Bower

Bower is now preferred way to install client libraries like Angular or jQuery. Incidentally the default project template in visual studio has pre-installed jQuery, bootstrap etc. using Bower. 

Open Bower.js file which is available in root of project and you can see default packages.

I like to use angular-ui module of AngulaJS while working with bootstrap. it basically requires combination of some JavaScript and CSS files. To install this, simply add name of package.. VS editor will even assist you in typing package name using smart intellisense.


That's it. Now open solution explorer and expand "Dependencies" node. The dependencies node contains separate sub-folders for Bower and NPM packages. Expand Bower node and you can see all packages installed using Bower.

  • The package list of NPM is generated using "package.json"
  • Bower package list is based on "Bower.js" file

You can see the recently added angular-bootstrap package in the list with the tag "not installed". All you have to do now is right click the package name and click "Restore Package".

Pretty cool.. hmm? But I don't want to manually click "Restore Package" every time I add new package using Bower.js. Although this looks very small thing, we can still automate this task using famous "Task Runners"

Gulp and Grunt.. How and How?

Most likely you already have used and know about Gulp and Grunt. If yes, skip few lines below.

What Is It?

For those who don't know what is Gulp or Grunt, these are two different task/build runners which can be used to automate sequence of tasks which you would perform every time you build or deploy the application.

Typical candidates for task runner are tasks like compiling or validating JS code, minify and bundle files, run unit testing etc. At the same time, you can find that community has created plugins for almost every task that one can think of.

I would strongly recommend trying Gulp or Grunt (I prefer Grunt due to vast community/documentation support) in your project to realize the benefit it brings to the table and now with out of box support in the VS there is every reason why one should use it.

How to In Visual Studio?

Visual Studio web project template is comes pre-configured with Grunt. If you are using empty project template then add following lines in "package.json" file

We have added dependency of jshint and watch. We will explain their use in detail along with Grunt configuration.

{
    "version": "0.0.0",
    "name": "",
    "devDependencies": {
        "grunt": "0.4.5",  //select the version number suggested by VS intellisense
        "grunt-bower-task": "0.4.0",
        "grunt-contrib-jshint": "0.11.2",
        "grunt-contrib-watch": "0.6.1"
    }
}
//After copying these lines in package.json, simply save the file 
//and run NPM task as explained above section.

If you are using web project template then Open the "gruntfile.js" or else, manually add gruntfile.js using below step

Right click project -> Add -> New Item. Select "Grunt Configuration file" and leave default file name.

Basic Blocks of gruntfile

To explain gruntfile in detail lets setup grunt to use "jshint". (jshint is a commonly used tool to check code quality of JavaScript code). I want jshint to automatically validate my JavaScript code whenever I change any JS file.

In the gruntfile.js

  • main wrapper function which contains configuration details of all grunt tasks
module.exports = function(grunt) {
}
  • config object which contains details of each grunt tasks. 
grunt.initConfig({
});
In this case, let's add jsHint configuration

grunt.initConfig({
    jshint: {
        //files to validate
        files: ['gruntfile.js', 'Scripts/**/*.js'],
        options: {
            curly: true, //This option indicates that all loops and blocks are wrapped within {},
            unused: true, //This option will give warning if unused variable definition found,
            globals: {
                jQuery: true  //defines globals exposed by jQuery
            }
        }
    }
});
// Check the full list of jsHint options here
  • Setup tasks to run. Most important is default task

grunt.registerTask('default', ['jshint'); //you can specify multiple tasks separated by comma
  • Finally, load the npm plugin(s). Make sure that npm plugins being loaded are already insalled in npm (package.json)
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch'); //grunt plugin to watch changes in file
You can now run grunt task manully by right clicking gruntfile.js -> Task Runner Explorer. It will be open task runner window. In task runner explorer window, Expand gruntfile.js -> Tasks -> right click jshint -> Run
You can also setup the task to run before or after build process



What About Gulp?

Gulp is alternate of Grunt and pretty much does the same thing but with performance benefit as it uses pipe streams. The Gulp task includes list of source files, plugins to use as readable pipe and destination
To automate above jshint task using gulp, add new JS file in project and name it as Gulpfile.js (do not change the name)
and use following gulp configuration.

var jshint = require('gulp-jshint');
var gulp   = require('gulp');
 
gulp.task('lint', function() {
  return gulp.src('Scripts/**/*.js')
    .pipe(jshint())
    .pipe(jshint.reporter('default'));
});
You can run the gulp tasks using task runner explorer similar to grunt

Improvements in JavaScript Editor

Finally, I would like to highlight some of the JavaScript editor which I liked most.

Navigation bar support

Remember how you use "Ctrl+F" to find function name to jump between the functions in JavaScript editor. Specially when you have thousands of lines of code, it becomes nightmare due to possibility of having many functions with similar names.

So you must have always wanted to see good old class/function navigation bar similar to server side code editor... And it is finally available in Visual Studio.
We have seen this functionality back in Visual Studio 2013 RC but for some reason it didn't make it in the final version.
This is time however I am sure it will be part of final release.
Similar to C#/VB.net code editor, it lists all classes (in ECMA6 and TypeScript) or root variables (in ECMA5) and functions in separate navigation list which can be used to easily switch between different functions.

Consider below basic modular JavaScript code. There are two root variables Product and Sales. There are also different methods and variables inside root. You can jump to different root or function using navigation bar highlighted in Red.
Pretty neat, eh!



Task List

You can also use usual tags like TODO, HACK, UNDONE etc in the JavaScript code and it will be listed in task list window as highlighted in above screenshot (in Green color)
This is not a new feature but this is now available out of box in VS.

Visual studio JavaScript editor also continues to evolve with improved intellisense out of box support for libraries like angular.js and full support for ECMA6 constructs.

Conclusion

Visual Studio 2015 (still in RC) has come up with some amazing productivity and performance improvements. Don't wait for final release, just give it a go.

I am happy to know or discuss any other interesting feature that you might already know :)