Saturday, 7 November 2015

A Few Tips on Gulp

I have been using Gulp a lot these days and have encountered a few cases that are a bit tricky to solve if you are new to Gulp. These scenarios get even trickier if you used Grunt before and just started using Gulp later, like myself. This is because, Grunt is synchronous and the execution of a Grunt task that combines a set of tasks is predictable. On the other hand, Gulp is asynchronous and we need to carefully examine the way a combined task runs in order to get maximum benefits out of it.

The asynchronous behavior of Gulp tasks makes it a bit difficult to perform things like chaining multiple tasks, handling tasks not returning a stream work seamlessly and performing multiple operations in a single task. In this post, we will see how to handle these tasks.

Chaining Multiple Tasks
It is common to define multiple tasks and combining them to create a master task. The master task alone is called whenever there is a need to perform the set of tasks together. Some of these tasks may be dependent on each other and others may be independent. In general, a set of Gulp tasks are combined using the following syntax:

gulp.task('build', ['copy-files', 'concat-files', 'run-tests', 'copy-coverage-results']);
Out of these tasks, the task concat-files is dependent on the task copy-files. The above setup starts executing these tasks at the same time. Execution of the task concat-files is not paused until execution of the task copy-files is completed. It can be solved in two ways. One way is to declare the task copy-files as a dependent task on the task concat-files and have the concat-files task alone as dependency on the build task.

gulp.task('concat-files', ['copy-files'], function(){
  //definition of the task
});


The second way is to run these tasks in sequence using the run-sequence package. It is shown below:

var runSequence = require('run-sequence');
gulp.task('copy-and-concat', function(){
  return runSequence('copy-files','concat-files');
});


We have to use one of these ways to solve this case based on the scenario in hand.

Task not returning a Stream
Sometimes we have to deal with tasks that don’t return streams. Such tasks are difficult to chain, as gulp doesn’t understand about their completion. One of such tasks is gulp-requirejs. We need to wrap execution of such tasks inside gulp pipes to make them return streams. Following snippet wraps the gulp-requirejs task inside a pipe:


gulp.src('undefined.js')
  .pipe(requires(/*configuration of the task goes here*/))
  .pipe(gulp.dest('path-of-destiation'));


Task handling Multiple Operations
A task may handle multiple asynchronous operations. In such case, the task has to return a stream representing the combined execution. Sometimes, we can return the stream returned by the last operation alone, but this approach doesn’t guarantee that all tasks are completed by the time the stream is completed. So, it is a good practice to combine such tasks using the event-stream package. Following snippet combines a number of copy operations into a single task using this package:

gulp.task('copy-files', function () {
  return es.merge(
    gulp.src('app/index.html')
      .pipe(gulp.dest('build')),
    gulp.src('app/JSON/*.json')
      .pipe(gulp.dest('build/JSON')),
    gulp.src('app/requirejs-config.js')
      .pipe(gulp.dest('build/temp'))
    );
});


I have encountered these cases quite a few times and the solutions discussed here worked well for me. These may not be the only possible ways to tackle these cases, but these are just my views. If you got any other ways to solve these problems, feel free to add a comment.

Happy coding!

Saturday, 10 October 2015

Book Review - AngularJS by Example

I have just finished reading the book AngularJS by Example authored by Chandermani Arora. I will share my views on this book in this post.

A typical technology book starts with concepts on the technology and it continues to explain the technology throughout the book with independent examples. This book takes a different approach and start building an application right from beginning of the book. It continues adding features to the same example while explaining different concepts of the framework and covering internal details wherever needed.

Presentation of the entire book can be summarized into following the bullet points:

  • Starts with a brief discussion on problems with building large JavaScript applications. Explains need of patterns like MVC in the ecosystem
  • Doesn't build a regular "Hello World" sample, instead builds an interesting sample to cover basic constructs of the framework
  • Before building any step of the sample, the author spends time in explaining the problem, then tells which feature solves the problem and then explains the feature thoroughly before implementing the next step
  • Covers a number of tips through examples
  • Makes good use of the notes section to clarify some basics and lesser known facts
  • No concept is explained independently. Most of the necessary features of the framework are covered with right examples that are very close to real world problems
  • I particularly like the way some features like animations, ng-model, interceptors and testing are explained in the book
  • Last chapter focuses on a few common scenarios and provides advice containing best practices to solve these problems


This book doesn't just helps someone in gaining knowledge on AngularJS, but also teaches the needs of the features. Once you finish reading the book by following along with it and build the sample, you will have a self-built reference application that you can refer in the future.

The content in this book is relevant to both beginners and experienced developers working on AngularJS. A thorough read of this book will help you in mastering essential parts of the framework. You will also be able to answer most of the common interview questions once you read this book :).

Happy coding!

Friday, 25 September 2015

Writing Gulpfile using TypeScript

Lately, I have been using Gulp a lot at my work and also in the demos of my articles. I also use TypeScript quite often these days while playing with Angular 2. While using Gulp to transpile TypeScript to JavaScript using Gulp, I got thought to use TypeScript itself to write the gulpfile as well. It might sound a bit weird as we use Gulp to transpile the files to JavaScript and the gulpfile itself has to be converted by someone into JavaScript before any other task runs. Thanks to npm scripts, we have a way to achieve this.

The scripts section of the package.json file can be used to register commands and these commands can be executed from command prompt of any OS using the “npm run” command. For instance, if we have the following configuration saved in scripts section of package.json file:

"scripts": {
  "setup" : "npm install && bower install"
}

We can run the command “npm run setup” from the command prompt. This command would install all Node.js dependencies and the bower dependencies. We can transpile the gulpfile using this section and then combine this command with a command to run a task. For this, we need to have TypeScript installed globally. This can be done using the following command:

> npm install –g typescript

To write the gulpfile using TypeScript and take advantage of the type checking system, we need to get the type definition files. Type definitions for the gulpfile are available on tsd. Following command gets the type definitions for the gulpfile:

> tsd install gulp --save

These files are saved inside typings folder of the project. To make our lives easier, the tsd command creates a type definition file that refers to all of the installed type definitions. This file is tsd.d.ts inside the typings folder.

Now, we need to refer the tsd.d.ts file in the gulpfile.ts file and start writing Gulp tasks. Following snippet shows a task that concatenates all JavaScript files:

/// <reference path="typings/tsd.d.ts" />

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

gulp.task('default', function(){
  return gulp.src(["scripts/*.js"])
    .pipe(concat("combined.js"))
    .pipe(gulp.dest("dist"));
});

This example is a simple one. In more advanced scenarios, we can use types as well.

To run this gulp task, we need to define a command in the scripts section to transpile the file and then run the task. Following is the command:

"scripts": {
  "concat": "tsc gulpfile.ts && gulp"
}

All is done. We can now run this command as follows:

> npm run concat

Happy coding!

Tuesday, 30 June 2015

Debugging and Profiling LINQ Queries using Devart LINQ Insight

Language Integrated Query (LINQ) is one of the features that makes .NET developers happy. LINQ opened up the opportunities to uniformly query in-memory objects, data in relational DBs, OData Services and many other data sources. Writing LINQ queries is fun as they reduce the usage of loops in code and keep the code base simple.

There are several ways to write LINQ queries to obtain a given result. As programmers, it is our responsibility to find the best way out of them and use that to make the applications perform better. Also, LINQ queries are hard to debug. It is not possible to debug a LINQ query using immediate window of Visual Studio debugging tools. So, we can’t say if a LINQ query is completely correct unless we write enough unit tests around it. Though unit tests are a good way to verify, nothing beats the ability of debugging the query by changing parameters.

LINQ Insight is a Visual Studio extension from Devart that makes debugging and profiling LINQ queries easier. It also provides profiling data for the LINQ queries and for CRUD operations performed using LINQ to in-memory objects as well as LINQ to remote objects (LINQ to SQL, Entity Framework, NHibernate and others). In this post, we will see a few of the features of this tool.

Debugging LINQ Queries
Once you installed LINQ Insight and restarted Visual Studio, you will see the options to see LINQ Interactive and LINQ Profiler windows under the View menu:




To debug the queries, we need to view the LINQ Interactive window. Select this option to view the window. Say, I have the following generic list of Persons in my application:
var people = new List<Person>() {
    new Person(){Id=1, Name="Ravi", Occupation="Software Professional", City="Hyderabad", Gender='M'},
    new Person(){Id=2, Name="Krishna", Occupation="Student", City="Bangalore", Gender='M'},
    new Person(){Id=3, Name="Suchitra", Occupation="Self Employed", City="Delhi", Gender='F'},
    new Person(){Id=4, Name="Kamesh", Occupation="Business", City="Kolkata", Gender='M'},
    new Person(){Id=5, Name="Rani", Occupation="Govt Employee", City="Hyderabad", Gender='F'}
};

Let’s write a LINQ query to fetch all males or, females from this list using a character parameter. Following is the query:
var gender = 'M';

var males = people.Where(p => p.Gender == gender).Select(p => new { Name=p.Name, Occupation=p.Occupation });

Right click on the query and choose the option “Run LINQ Query”. You will see this query in the LINQ Interactive window and its corresponding results.



As the query accepts a parameter, we can change value of the parameter and test behavior of the query. Hit the Edit Parameters button in the LINQ Interactive window and modify value of the parameters used in the query. On clicking OK, the query is executed and the result is refreshed.

Profiling Calls to Entity Framework
As most of you know, ORMs like Entity Framework convert LINQ Queries and function calls into SQL Queries and statements. The same result can be obtained using different types of queries. It is our responsibility to measure the execution time of all possible approaches of writing a query and choose the best one out of them.

For example, consider a database with two tables: Student and Marks.



The need is to find details of a student and the marks obtained by the student. It can be achieved in two ways. The first way is to find sum of the marks using navigation property on the student object and the other is to query the Marks DbSet using group by clause:
var studMarks1 = context.Students.Where(s => s.StudentId == studentid)
                        .Select(s => new
                        {
                            Name = s.Name,
                            Id = s.StudentId,
                            City = s.City,
                            TotalMarks = s.Marks.Sum(m => m.MarksAwarded),
                            OutOf = s.Marks.Sum(m => m.MaxMarks)
                        });

var studMarks2 = context.Marks.Where(m => m.StudentId == studentid)
                         .GroupBy(sm => sm.StudentId)
                         .Select(marksGroup => new
                         {
                             Name = marksGroup.FirstOrDefault().Student.Name,
                             Id = marksGroup.FirstOrDefault().Student.StudentId,
                             City = marksGroup.FirstOrDefault().Student.City,
                             TotalMarks = marksGroup.Sum(m => m.MarksAwarded),
                             OutOf = marksGroup.Sum(m => m.MarksAwarded)
                         });

Let’s see how much time does each of the above query takes using LINQ Profiler. Go to View menu and choose option to see the LINQ Profiler window. Now debug the application. After both of the queries are executed, visit the profiler window. You will see the data collected by the profiler. Following screenshot shows an instance of profiler’s data after running the above queries:

You can observe how much time each of these queries takes in different instances and with different values of the parameters before concluding that one of them is better than the other one.

As we saw, LINQ Insight adds a value add to the .NET developers. Devart has a number of other tools to help developers as well. Make sure to check them out and use them to make your development experience more enjoyable!

Happy coding!

Saturday, 13 June 2015

Everything You Need to Know to Unit Test AngularJS Code

Unit testing is one of the crucial and necessary parts of software development. This phase improves the quality of product, assures accuracy in behavior and also reduces the cost involved in fixing the bugs. There are some good advantages for a developer writing unit tests as well.

AngularJS is one of the most popular framework for building Single Page Applications. One of the key reasons behind its success is, testability. Every piece of code written in AngularJS is unit testable. The features like Dependency Injection make the code written on the framework easier to test.

In the past, I wrote a few posts on unit testing AngularJS controller using Jasmine and QUnit and I also covered a few tips. Over past two years, I worked a lot on AngularJS and thus I wrote a lot of code and tests. This process taught me a lot of tips on unit testing AngularJS code that I wanted to share with the community. As some of you might be aware that I am a regular author for SitePoint, I have put together a series of four articles covering tips on mocking and testing almost every block in AngularJS. Following are the links to these articles:


  1. Mocking Dependencies in AngularJS Tests
  2. Unit Testing in AngularJS: Services, Controllers & Providers
  3. AngularJS Testing Tips: Testing Directives
  4. AngularJS Testing: Bootstrap Blocks, Routes, Events, and Animations


The process of putting these articles together has not been easy for me and at the same time, I enjoyed a lot while writing them. Read them when you get time and feel free to drop any feedback to me.

Happy coding!

Sunday, 26 April 2015

Getting Started with Benchpress

Lately, most of us are quite busy with writing great front-end centric applications to make the look and feeling of our apps jazzy. Despite of the jazziness, the application won’t give a great experience to the user unless it performs really well on the browser. Performance of any piece of code can be improved only if we know that there is some scope for the improvement. Benchpress is one of the tools available to measure performance of AngularJS applications. In this post, we will see how to install benchpress and get started with using the data it provides us.

Benchpress is a performance measuring tool built on top of Protractor. It is built by the Angular team and is extensively used by them to measure performance of the framework. It is made available and can be used by anyone to measure performance of the Angular apps.

Installing Benchpress

Benchpress is an NPM package. So, it needs Node.js to be installed. As it uses protractor, you need to install protractor globally. Use the following command to install protractor:

npm install –g protractor

If you are installing it on a Windows machine, webdriver-manager may throw an error. To oversome this, you will have to update the webdriver-manager. Following command updates it:

webdriver-manager update

Restart the command prompt after this command completes execution.
Install protractor again after updating the webdriver-manager and it shouldn’t fail this time. You can find more details on installing protractor in its official documentation on GitHub.
Now that the system has protractor available as a global package, we can install benchpress. Benchpress also has to be installed globally. Following is the command:

npm install -g generator-benchpress

Getting a Glimpse of Benchpress ng-tasty
Now that we have all of the required setup, we can apply benchpress on a project. For this post, I will show the benchpress results using the yeoman scaffold of ng-tasty. I will explain the process of getting benchpress results on an existing piece of code in a future article. As we need to install a yeoman scaffold, you must have yeoman installed. If you don’t already have, run the following command to install it:

npm install –g yo

Create a new folder at your desired location and install the following NPM packages locally:
  • http-server
  • benchpress


Benchpress needs these packages to start the Node.js HTTP server and run the scenarios tests. The final thing that we need to get is, the yeoman scaffold. Run the following command in the same folder where the above NPM packages are installed: yo benchpress ng-tasty

This scaffold adds a folder called benchmarks and inside this folder and the folder has following content:
  • protractorBenchmarks.conf.js: It is the configuration file for benchpress. It contains the browser details, spec files to run, test framework to use, the task to be performed before launching benchpress and a config object for jasmine
  • index.html: This file is inside the ng-tasty folder and it is the page to be inspected on
  • benchmark.spec.js: This file is inside the ng-tasty folder. The spec file that uses Selenium web driver to perform operations on the page
Now, we have everything to run benchpress and see some results. Run the following command on the console and see the outcome:

protractor benchmarks\protractorBenchmarks.conf.js

This command starts Selenium Web Driver and loads the index.html on Chrome. It performs the set of operations configured and prints results on the console.


Happy coding!

Wednesday, 7 January 2015

Private Members in ES6 Classes

Classes in ECMAScript 6 are easy to write and use. Yet, they have certain limitations. One of them is, there is no direct way to create a private member inside the class.

The classes don’t allow us to declare variables directly inside body of the class. All members defined/declared inside the class or attached to an instance using this keyword are directly available to the instance of the class.

When I Googled it, I found a few posts on it and answers suggesting to use Symbol. I think, Symbol was private sometime back but according to the current draft of ES6, properties created using Symbol values are not private anymore. Though value of Symbol can't be reproducible, one can read Symbol properties using Object.getOwnPropertySymbols.

For example, consider the following class and object:


const ID = Symbol();
class Employee{
  constructor(id, name){
    this.name = name;
    this[ID] = id;
  }
}
var emp = new Employee(1001, "Ravi");


Though value of id is not accessible using emp[Symbol()], as it returns a different Symbol, we can extract all Symbols used for properties and values of these properties as:

var symbolsInEmp = Object.getOwnPropertySymbols(emp);
symbolsInEmp.forEach(function(symbol){
  console.log(emp[symbol]);
});


The above snippet will print value of id stored in the object emp. If there are multiple Symbol properties, you may not be able to find which value corresponds to what value, but the data is not private.

To make a value private, we can do one of the following:

  • set and use the value inside a closure
  • create the variable inside a module and not export it


WeakMap seems to be a good option for creating the private fields. Because, it accepts any value as key and it doesn’t prevent the key object from getting garbage collected when the WeakMap object still exists. It removes entry containing the object once it is garbage collected. For each private field, we need to create a new WeakMap object.

Following snippet shows how WeakMaps can be used as private fields:


const ID = new WeakMap();
const PAN = new WeakMap();

class Employee{
  constructor(id, name, pan){
    this.name = name;
    ID.set(this, id);
    PAN.set(this, pan);
  }
  getPan(){
    return PAN.get(this);
  }
}
var emp = new Employee(1001, "Ravi", "FFHH1919JJ");
console.log(emp.getPan());

export default Employee;


As you see, we are exporting the Employee class alone from the module. Here, the classes don't contain the fields themselves, but they are relying on the private objects of the module to keep the data private.

Happy Coding!

Thursday, 1 January 2015

Static Class Members in ES6

I have been playing with ECMAScript 6 for some time now and I must say that the new features added in this edition are worth taking a look. One of the significant language feature added in this specification is, support for classes. If you are not aware of the features of ES6, checkout the specification on official site for ECMA Script or, the un-official HTML version of the specification on Mozilla’s site.

ES6 classes support most of the features like creating object, constructor, inheritance and overriding that are supported by Object Oriented programming languages like C# or Java. And because it is JavaScript, there is no static type checking.

I found it interesting when I saw the support for static members in the specification. The specification says, we can add a static method to a class using the following syntax:


static methodName(){
}


But, if you attempt to declare a static property as follows:

static propertyName;


It results in an error. So, we can’t declare a static property. But, we can create it inside a method and use it. To access a static member inside a static method, we need to use this keyword. Because, this reference in JavaScript refers to the object using which the method is invoked. Static methods are called using name of the class to which they belong and name of the class in JavaScript refers an object that has a prototype property containing instance members of the class. For example, consider the following class:

class Employee
{
  constructor(){
    this.name = "Ravi";
  }
  setName(name){
    this.name = name;
  }
}


The above code is similar to:

function Employee(){
  this.name="Ravi";
}
Employee.prototype = {
  setName: function(name){
    this.name=name;
  }
};


Here Employee is name of the class and at the same time, it is also an object. All static members of the Employee class are attached to the Employee object.

Let’s add a static method to the Employee class:


class Employee
{
  constructor(){
    this.name = "Ravi";
  }
  setName(name){
    this.name = name;
  }

  static getCounter(){
    if(!this.counter && this.counter!==0){
      this.counter=0;
    }
    else{
      this.counter++;
    }
    return this.counter;
  }
}


The property counter used in the getCounter method of the above snippet becomes a static property, as it is assigned to this reference inside a static method. Similarly, another static method of the class can be called from a static method using this reference.

The following console.log statements will print the results specified in the comments:


console.log(Employee.getCounter());  //0
console.log(Employee.counter);       //0
console.log(Employee.getCounter());  //1
console.log(Employee.counter);       //1
console.log(Employee.getCounter());  //2
console.log(Employee.counter);       //2


Happy Coding!