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!

Thursday, 25 December 2014

Automating Tasks in Front-end Web Apps Using Gulp

As we started writing a lot of JavaScript and CSS these days, front-end development has matured like anything. We create hundreds of JavaScript source files to make our code organized; but finally we need to ship just one JavaScript file and one CSS file while deploying the application. This conversion is not easy; as it involves several steps like running tests, validating against jshint, concatenating, minifying, uglifying and many other tasks. Thankfully, we have a number of automated task runners and a handful of plugins on each of these task runners to make these tasks easier.

Out of the existing task runners, Grunt and Gulp are most widely used. I use Grunt a lot these days. Though I haven’t blogged about it, I used it in some of my SitePoint articles. Lately, Gulp is becoming more famous. Gulp uses a different approach to address the same problem that Grunt addresses. Let’s see how we can leverage Gulp to automate our tasks.

Gulp is a task runner based on Node.js. It uses streams to carry its tasks. The way Gulp works is, it accepts a source (can be a file, or a set of files), processes them based on a task and passes it to the next task in the pipe for further processing. The pipes continues processing till the last task. Following is the syntax of a typical Gulp task:

gulp.task('task-name', function () {
  return gulp.src([source paths])
    .pipe(task1(parameters))
    .pipe(task2())
    ...
    ...
    ...
    .pipe(taskn())
    .pipe(gulp.dest('destination-path'));
});

Tasks piped in the above Gulp task are tasks loaded using Gulp plugins. Gulp has a huge number of plugins contributed and actively developed by community, which makes it a very good ecosystem. To be able to use Gulp in your project, you need to have it installed globally and locally. Run the following commands in a command prompt to get Gulp installed:

  • npm installed –g gulp
  • npm installed gulp --save-dev (To be ran in your project folder)


Let’s write a Gulp task for cleaning distribution files and regenerating them after concatenating and minifying. For this, we need the following Gulp plugins:

  • gulp-clean
  • gulp-concat
  • gulp-uglify


These can be installed using the following nom commands:
  • npm install gulp-clean --save-dev
  • npm install gulp-concat --save-dev
  • npm install gulp-uglify --save-dev


Add a file to the project and rename it to Gulpfile.js. Load the Gulp tasks in this file:


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


Before generating the files to be deployed, let’s clean the folder. Following task does this:

gulp.task('clean', function () {
    return gulp.src(['dist'])
        .pipe(clean());
});


Now, let’s create a bundle task that concatenates all JS files, uglifies them and copies inside a folder to be distributed. Following is the task:

gulp.task('bundle', function () {
  return gulp.src(['public/src/*.js'])
    .pipe(concat('dist/combined.js'))
    .pipe(uglify())
    .pipe(gulp.dest('.'));
});


The folder public/src contains all JS files of the application. They are concatenated into one file and the contents are then uglified and finally we call the dest task to copy the resultant file to destination, which is the dist folder.

These two tasks can be combined into one task as follows:


gulp.task('createDist', ['clean', 'bundle']);


Now, if you run the following command, you will have the combined.js file created inside dist folder.

gulp createDist

To make a task default, name of the task has to be default.


gulp.task('default', ['clean', 'bundle']);


To run this task, you can run gulp command without passing names of any tasks to it.

We will see explore more features of Gulp in future posts.

Happy coding!

Monday, 27 October 2014

Form Validation and Displaying Error Messages using ngMessages in AngularJS 1.3

AngularJS 1.3 was released around two weeks back. As the core Angular team says, it is the best AngularJS released till date. It comes with a bunch of new features and performance improvements.

One of the key changes in this release is the changes made to forms. The directives form and ngModel went through a number of changes to make it easier to perform validation. The framework has a new module, ngMessages that makes the job of displaying validation messages easier.

In the current release, FormController have following additional APIs:

  • $setUntouched(): A method that sets all controls in the form to untouched. It is good to call this method along with $setPristine()
  • $setSubmitted(): A method that sets the state of the form to submitted
  • $submitted: A boolean property that indicates if the form is submitted

NgModelController has the following additional APIs:

  • $setUntouched(): A method that sets the control to untouched state
  • $setTouched(): A method that sets the control to touched state
  • $validators: A list of synchronous validators that are executed when $validate method is called
  • $asyncValidators: A list of asynchronous validators that are executed when $validate method is called
  • $validate(): A method that executes all validators applied on the control. It calls all synchronous validators followed by asynchronous validators
  • $touched: Boolean property that indicates if the control is touched. It is automatically set to true as soon as cursor moves into the control
  • $untouched: Boolean property that indicates if the control is untouched

For more details on these APIs, read the official API documentation of FormController and NgModelController.

Let’s see these APIs and the new featured in action. Consider the following form:


<form name='vm.inputForm' ng-submit='vm.saveNewItem()' novalidate>
  Item Name: <input name='itemName' type="text" ng-model='vm.newItem.name' required non-existing-name />
  <br />
  Min Price: <input name='minPrice' type="text" ng-model='vm.newItem.minPrice' required ng-pattern='vm.numberPattern' />
  <br />
  Max Price: <input name='maxPrice' type="text" ng-model='vm.newItem.maxPrice' required ng-pattern='vm.numberPattern' greater-than='vm.newItem.minPrice' />
  <br />
  Quantity Arrived: <input name='quantity' type="text" ng-model='vm.newItem.quantity' ng-pattern='vm.numberPattern' />
  <br />

  <input type="submit" value="Save Item" />
</form>

Note: Notice name of the form in the above snippet. It is not the way we usually name the HTML elements. We assigned a property of an object instead of a plain string name. Reason for using this is to make the form available in the controller instance. This approach is very useful in case of controllerAs syntax. (Credits: Josh Caroll’s blog post)

The form has some built-in validation and two custom validations. Built-in validations work the same way as they used to in the earlier versions ( Refer to my old blog post that talks a lot about the validations). We will write the custom validations in a minute.

Following is the controller of the page. As stated above, I am using “controller as” syntax, so no $scope in the controller.


var app = angular.module('formDemoApp', ['ngMessages']);

app.controller('SampleCtrl', function(){
  var vm = this;

  vm.inputForm = {};

  vm.numberPattern = /^\d*$/;

  vm.saveNewItem = function(){
    vm.newItem={};
    vm.inputForm.$setPristine();
    vm.inputForm.$setUntouched();
  };
});

Custom Synchronous Validations

The process of defining custom validations has been simplified in AngularJS 1.3 with $validators and $asyncValidators. We don’t need to deal anymore with $setValidity() to set validity of the control.

In case of synchronous validations, we need to return a boolean value from the validator function. The validation is passed when result of the validator function is true; otherwise, it fails.

In the form, we are accepting min price and max price values. The form should validate that the value of min price is always less than value of max price. Following is the directive for this validation:


app.directive('greaterThan', function(){
  return {
    restrict:'A',
    scope:{
      greaterThanNumber:'=greaterThan'
    },
    require: 'ngModel',
    link: function(scope, elem, attrs, ngModelCtrl){
      ngModelCtrl.$validators.greaterThan= function(value){
          return parseInt(value) >= parseInt(scope.greaterThanNumber);
      };

      scope.$watch('greaterThanNumber', function(){
        ngModelCtrl.$validate();
      });
    }
  };
});

If the above validation fails, it sets invalid flag to greaterThan validation on the control. Name of the method set to $validators is used as the validator string.

Custom Asynchronous Validations

In some scenarios, we may have to query a REST API to check for validity of data. As AJAX calls happen asynchronously, the validator function has to deal with promises to perform the task.

For the demo, I created a dummy asynchronous method inside a factory that checks for existence of the new item name in a static array and resolves a promise with a boolean value. Following is the service:


app.factory('itemsDataSvc', ['$q',function($q){
  var itemNames=['Soap', 'Shampoo', 'Perfume', 'Nail Cutter'];

  var factory={};

  factory.itemNameExists=function(name){
    var nameExists = false;
    itemNames.forEach(function(itemName){
      if(itemName === name){
        nameExists=true;
      }
    });
    return $q.when(nameExists);
  };

  return factory;
}]);

The difference between synchronous and asynchronous validators is the API used to resister the validator and the return value of the validator method. As already stated, $asyncValidators of NgModelController is used to register the validator and the validator method has to return a promise. The validation passes when promise is resolved and the validation fails if the promise is rejected.

Following is the custom asynchronous validator that checks for unique name:


app.directive('nonExistingName', ['itemsDataSvc','$q',function(itemsDataSvc, $q){
  return {
    restrict:'A',
    require:'ngModel',
    link: function(scope, elem, attrs, ngModelCtrl){
      ngModelCtrl.$asyncValidators.nonExistingName = function(value){
        var deferred = $q.defer();

        itemsDataSvc.itemNameExists(value).then(function(result){
          if(result){
            deferred.reject();
          }
          else{
            deferred.resolve();
          }
        });

        return deferred.promise;
      };
    }
  };
}]);

Validation Error Messages using ngMessages

Displaying validation messages of the form in AngularJS had not been too good earlier. It used to take a lot of mark-up and conditions to make them look user-friendly. AngularJS 1.3 has a new module, ngMessages that simplifies this task. If you refer to the module definition statement in the controller script, it has a dependency on ngMessages module. This module doesn’t come by default as part of the core framework, we have a separate file for this module.

The ngMessage module contains two directives that help in showing messages:

  • ngMessages: Shows or hides messages out of a list of messages
  • ngMessage: Shows or hides a single message

The directives in ngMessages module support animations as well. I will cover that in a future post.

In case of displaying form validation messages, ngMessages is set to the $error property of the form object and every occurrence of ngMessage element is set to the condition for which the message is has to be displayed.


<div ng-if='vm.inputForm.$dirty &amp;&amp; vm.inputForm.$invalid' ng-messages='vm.inputForm.$error' class='error-messages'>
  <div ng-message='required'>One/more mandatory fields are missing values</div>
  <div ng-message='pattern'>Data is in incorrect format</div>
  <div ng-message='greaterThan'>Invalid range</div>
  <div ng-message='nonExistingName'>Name already exists</div>
</div>

By default, ngMessages displays the first message out of the list even if more than one message is relevant. It can b overridden using multiple or ng-messages-multiple attribute on the ngMessages directive.

The above message list is generic to the form; the messages are not specific to any of the control in the form. To display messages specific to form, you can use the $error property on the form element.


<div ng-if='vm.inputForm.itemName.$dirty' ng-messages='vm.inputForm.itemName.$error' class='error-messages'>
  <div ng-message='required'>One/more mandatory fields are missing values</div>
  <div ng-message='nonExistingName'>Name already exists</div>
</div>

You can play with the sample on Plnkr.

Happy coding!

Sunday, 28 September 2014

Unit Testing Config and Run Blocks in AngularJS

One of the best-selling points of AngularJS framework is testability. Any piece of code written in an AngularJS application is testable unless it is corrupted by a global object.

All of the blocks in AngularJS except config and run blocks can be instantiated or invoked and tested. Config and run blocks are executed as soon as the module containing the block is loaded into memory. There is no way to call them manually; unless the bodies of these blocks are defined independently and then hooked to a module. But, they are invoked automatically when the module is loaded. So, I don’t see a need to invoke them manually to test their logic.

Say, we have the following module with a config block registering routes and a run block that listens to a global message event to the window:



var app = angular.module('testApp',['ngRoute']);

app.config(function($routeProvider){
  $routeProvider.when('/', {templateUrl:'templates/home.html',controller:'homeCtrl'})
    //definitions of other routes
    .otherwise({redirectTo:'/'});
});

app.run(function($window, $rootScope){
  $window.addEventListener('message', function(event){
    $rootScope.$broadcast(event.data);
  });
});


In test of the config block, we need to see if the methods when and otherwise are called with right parameters. To do that, we must spy these methods and store a reference of $routeProvider as soon as the module in loaded in tests. Providers cannot be mocked using $provide like services as they are not available after config phase. We can pass a callback to module loader and create spies on the methods whose calls have to be inspected.

Following snippet shows how to spy on a provider’s method and a test that checks if the method is called:


describe('testing config block', function() {
  var mockRouteProvider;

  beforeEach(function () {
    module('ngRoute', function ($routeProvider) {
      mockRouteProvider = $routeProvider;
      spyOn(mockRouteProvider, 'when').andCallThrough();
      spyOn(mockRouteProvider, 'otherwise').andCallThrough();
    });
    module('testApp');
  });

  it('should have registered a route for \'/\'', function(){
    expect(mockRouteProvider.when).toHaveBeenCalled();
  });
});


If you run the above test now, it should fail. That’s strange, isn’t it?

I spent a lot of time struggling with it and found two approaches to make the above test pass.

One approach is to have a dummy test before the test that performs an assertion on the logic of config block. You can leave this test empty as it doesn’t have to do anything, or have an assertion that would always pass.


it('doesn\'t have any assertions', function(){});


I didn’t like this approach; as it adds a test that would always pass and doesn’t carry any value. The other approach to make the above test pass is by calling inject() inside a beforeEach block. The inject function is generally used to get references of services that are needed in the tests. Even if there is no need of any service in the tests, the inject block can be called without any callback to bootstrap the modules already loaded using module() blocks.

beforeEach(function(){
  inject();
});


You will see the same issue with run() block as well. It isn’t executed unless a test is executed or inject block is executed.

If you got a better approach to bootstrap modules in tests, feel free to post a comment.

Happy coding!

Saturday, 6 September 2014

Serializing and De-serializing JSON data Using ServiceStack

ServiceStack is a light-weight, complete and independent open source web framework for .NET. I recently started playing with it and I must say that it is an awesome framework. It has several nice features including .NET’s fastest JSON serializer.

Each piece in ServiceStack can be used independently. So is its piece for serialization. The serialization package of ServiceStack can be installed via NuGet using the following command:



The above package can be installed on any type of application. Let’s use the following Person class for creating object to serialize/de-serialize:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string City { get; set; }
    public string Occupation { get; set; }
}


Following is a sample object of the person class:

var person = new Person()
{
    Id = 1,
    Name = "Ravi",
    City = "Hyderabad",
    Occupation = "Software Engineer"
};


To serialize this object to a JSON string, we need to use the ServiceStack.Text.JsonSerializer class. Following statement serializes the above object:

var serialized = JsonSerializer.SerializeToString(person);


The above string can be de-serialized using the following statement:

var converted = JsonSerializer.DeserializeFromString<Person>(serialized);


The JsonSerializer class also has APIs to serialize into or de-serialize from TextWriter or Stream.

The APIs in ServiceStack are light-weight and easy to use. I am working on a series of articles on this great framework. Stay tuned for updates.

Happy coding!

Friday, 27 June 2014

Using Promises in NodeJS Apps

To separate logic of accessing data from the routes, we create separate modules to handle the task of data access. When I started learning Node.js, a common pattern that I saw in some samples to separate the data access logic from routing was as follows:

//Route
app.get(‘/api/students’, getAllStudents);

//In data access file
exports.getStudents = function(request, response){
  mongoDbObj.students.find().toArray(function(err, data){
    if(err){
      console.log(err); 
      response.send(500,{error: err});
    }
    else{
      console.log(data);
      response.send(data);
    }
  });
};


Though this approach separates the logic, we are dealing with request and response inside the data access logic. I am personally not a fan of this approach. But, we cannot return the data or error from the above function as we will get them asynchronously. This is where I started thinking of using promises to refactor the above function.

We have several promise libraries available for Node.js. These days, I am playing with Bluebird. It can be installed using npm.

One of the nice features that bluebird provides is, promisifying existing methods. To turn operations defined by an object into asynchronous, we need to pass the object inside the promisifyAll() method.


var Promise=require('bluebird');
var mongodb=Promise.promisifyAll(require('mongodb')); 


The above snippet creates asynchronous versions of each of the function created inside the object mongodb. Let’s convert some of the snippets from my previous post to use async. Code for establishing a connection to MongoDB changes to:

mongoClient.connectAsync('mongodb://localhost/studentsDb')    
           .then(function(db){
              console.log("Connected to MongoDB");
              mongoDbObj={
                db:db,
                students:  db.collection('students')
              };
            }, function(error){
                console.log(error);
            });


Let’s fetch details of all students and return the results asynchronously to the caller. On the result of calling find() method, we need to call the asynchronous method toArray() to convert data from documents to array. It makes sense to return a promise in such scenario as we can’t say when the result will be available. Following is the snippet for fetching data that returns a promise:

exports.getAllStudentsAsync=function(){
  return new Promise(function(resolve, reject){
    mongoDbObj.students.find()
              .toArray(function(err, result){
                 if(err)
                 {
                   reject(err);
                 }
                 else{
                   resolve(result);
                 }
            });
    });
};


Finally, the REST API that sends the student data to the browser changes to:

app.get('/api/students, function(request, response){
  mongoOps.getAllStudentsAsync()
          .then(function(data){
            response.send(data);
          }, function(err){
            response.send(500,{error: err});
          });
});


To me, this seems to be a cleaner approach as the request and response are sent to the model for manipulation. Feel free to express your opinions in the comments.

Happy coding!