The Problem Solver Tell me, and I will forget. Show me and I may remember. Involve me, and I will understand Thu, 25 Dec 2014 12:03:49 +0000 en-US hourly 1 Speeding up your AngularJS applications Sat, 20 Dec 2014 15:06:28 +0000 Continue reading Speeding up your AngularJS applications]]> In general AngularJS applications are quite fast, specially when compared to more traditional browser based applications that constantly post back to the server. However there are always a few things that will help performance and make an application even faster.


Disabling Debug Data


   1: demoApp.config(function($compileProvider) {
   2:   $compileProvider.debugInfoEnabled(false);
   3: });


Explicit dependency injection annotations




Reducing the number of $apply() calls


   1: demoApp.config(function($httpProvider) {
   2:   $httpProvider.useApplyAsync(true);
   3: });



]]> 2



Testing the template


   1: files: [
   2:     'app/bower_components/angular/angular.js',
   5:     'app/*.js',
   6:     'tests/*.js',
   7:     {
   8:         pattern: 'app/*.html',
   9:         watched: true,
  10:         included: false,
  11:         served: true
  12:     }
  13: ],



So taking an AngularJS directive like this:

   1: angular.module('myApp', [])
   3:       return{
   4:         scope:{
   5:           clickMe:'&'
   6:         },
   7:         templateUrl:'/app/myDirective.html'
   8:       }
   9:     });


And a template like this:



Can be easily tested like this:

   2:     var element, scope;
   4:     beforeEach(module('myApp'));
   6:     beforeEach(inject(function ($templateCache) {
   7:         var templateUrl = '/app/myDirective.html';
   8:         var asynchronous = false;
   9:         var req = new XMLHttpRequest();
  10:         req.onload = function () {
  11:             $templateCache.put(templateUrl, this.responseText);
  12:         };
  14:         req.send();
  15:     }));
  18:         scope = $rootScope.$new();
  19:         scope.doIt = angular.noop;
  23:         scope.$apply();
  24:     }));
  27:         spyOn(scope, 'doIt');
  31:         expect(scope.doIt).toHaveBeenCalled();
  32:     });
  33: });





]]> 0


Online demo:

Source code:
]]> 0



What is wrong with angular.module(“module”)?














]]> 0

The problem

Consider the following client side code:

   1: // Print a message
   2: utils.print("Hello");


This depends on another piece of script below:

   1: // Expose the utility object with it's print function
   2: var utils = {
   3:     print: function(msg){
   4:         console.log(msg);
   5:     }
   6: };



   1: <!DOCTYPE html>
   2: <html>
   3: <head lang="en">
   4:     <meta charset="UTF-8">
   5:     <title>Browserify demo</title>
   6: </head>
   7: <body>
   2: <script src="demo.js">
  12: </body>
  13: </html>




Browserify to the rescue






   2: // Print a message
   3: utils.print("Hello");


Next the utils.js specifies what it exports:

   1: // Expose the utility object with it's print function
   3: var utils = {
   4:     print: function(msg){
   5:         console.log(msg);
   6:     }
   7: };
   9: module.exports = utils;



   1: npm install -g browserify


With browserify installed we can bundle the files into one using:

   1: browserify demo.js > bundle.js

This will create a bundle.js with the following content:

   3: // Print a message
   4: utils.print("Hello");
   7: // Expose the utility object with it's print function
   9: var utils = {
  10:     print: function(msg){
  11:         console.log(msg);
  12:     }
  13: };
  15: module.exports = utils;



Adding the printIt() function


   1: function printIt(msg){
   3: }
   5: module.exports = printIt;


Note that it’s fine to just export a single function here.


   1: // Expose the utility object with it's print function
   4: var utils = {
   5:     print: function(msg){
   6:         printIt(msg);
   7:     }
   8: };
  10: module.exports = utils;

And the result of running browserify is:

   3: // Print a message
   4: utils.print("Hello");
   7: function printIt(msg){
   9: }
  11: module.exports = printIt;
  14: // Expose the utility object with it's print function
  17: var utils = {
  18:     print: function(msg){
  19:         printIt(msg);
  20:     }
  21: };
  23: module.exports = utils;


Proper scoping






]]> 0
   1: console.log(add(1, 2))


   3: function add(x, y) {

   4:     var sum

   5:     sum = x + y

   6:     return sum

   7: }

  What basically happens is that the JavaScript parser adds a semicolon at the end of each line if that doesn’t cause the syntax to become invalid. See section 7.9.1 of the ECMA-262 standard or read it online here. Now that might sound great but it turns out that Automatic Semicolon Insertion can cause some interesting issues :-(

JavaScript style rules

   1: public int Add(int x, int y)

   2: {

   3:     int sum;

   4:     sum = x + y;

   5:     return sum;

   6: }

   1: function add(x, y)

   2: {

   3:     var sum

   4:     sum = x + y

   5:     return sum

   6: }

   1: console.log(add(1, 2))


   3: function add(x, y) {

   4:     var sum

   5:     sum = x + y


   7:     return

   8:     {

   9:          sum: sum

  10:     }

  11: }

   1: console.log(add(1, 2))


   3: function add(x, y) {

   4:     var sum

   5:     sum = x + y


   7:     return {

   8:         sum: sum

   9:     }

  10: }

  This will print the expected object with a sum of 3.  

Blame JavaScript Automatic Semicolon Insertion

   1: console.log(add(1, 2));


   3: function add(x, y) {

   4:     var sum;

   5:     sum = x + y;


   7:     return;

   8:     {

   9:         sum: sum

  10:     };

  11: }

Notice the semicolon after the return statement?


Best practices



Enjoy!]]> 1


Apologies for the inconvenience.

]]> 0
X things every JavaScript developer should know: Comparisons Tue, 15 Jul 2014 08:52:46 +0000 /blogs/theproblemsolver/archive/2014/07/15/x-things-every-javascript-developer-should-know-comparisons.aspx Continue reading X things every JavaScript developer should know: Comparisons]]> Another item of things every JavaScript developer should know is how comparisons work. Just like with some of the other JavaScript, or I should really say ECMAScript, features anything you know about C# or Java could actually be misleading here.


To == or to ===

One of the weird things is there are actually two comparison operators in JavaScript, the double and the triple equals. The == is called the equals operator, see section 11.9.1 of the ECMAScript standard, and was the original equality operator. Unfortunately the way this operator works is quite some cause for confusion and as a result the === or Strict Equals operator was introduced, see section 11.9.4 of the ECMAScript standard. It would have been nice if they had just fixed the original problem but if they had they would have broken existing JavaScript applications.

In general I would always advise you to use the Strict Equals Operator or === whenever you do a comparison unless you have a specific need for the behavior or the original operator.


What is the problem with ==

I mentioned that == has problems and should be avoided but its still helpful to understand these problems. These problems basically boil down to the fact that the == operator does type conversions if the two types being compared are not the same. For example the following all evaluate to true:

   1: 0 == "0" // true

   2: 1 == "1" // true

   3: 2 == "2" // true

Sounds reasonable enough right?


Unfortunately it isn’t quite that simple all of the following evaluate to false:

   1: false == "false" // false

   2: true == "true" // false

These might seem weird, especially since the following evacuates to true again:

   1: true == !!"true" // true

So what is going on here?

The Abstract Equality Comparison Algorithm

Section 11.9.3 of the ECMAScript standard describes what is happening here. If one operand is a number and the other a string, as was the case in the first examples, the string is converted to a number and the comparison is done based on those. So basically these comparisons where:
   1: 0 == 0 // true

   2: 1 == 1 // true

   3: 2 == 2 // true


So what was the case in the other two comparisons?

In these cases almost the same happens and the Boolean values are converted to a number. That leaves a number to string comparison where the string is also converted to a number. And the result of converting true and false to a number is 1 and 0 but the result of the string to number conversions is an invalid number or NaN. And NaN being not equal to any other number means those comparisons result in false.

So why did the last comparison true == !!”true” evaluate to true? Well simple the double bang operator !! is evaluated first and a non empty string is truthy. End result of that is the expression true == true and that is obviously true. Sounds reasonable but that also means that any non empty string will result in true, so even true == !!"false" evaluates to true :-(



The double equality operator is a confusing part of the JavaScript history. You are best of to avoid it an use the Strict Equals Operator === instead.



]]> 0
Converting the RavenDB Northwind database to a more denormalized form Mon, 07 Jul 2014 12:27:43 +0000 /blogs/theproblemsolver/archive/2014/07/07/converting-the-ravendb-northwind-database-to-a-more-denormalized-form.aspx Continue reading Converting the RavenDB Northwind database to a more denormalized form]]> In a previous blog post I demonstrated how to denormalize the RavenDB sample database and use the DenormalizedReference<T> and INamedDocument types from the RavenDB documentation to make life really sweet. That leaves us with one small problem and that is that the original sample database doesn’t work with our improved document design. With the sample database, small as it is, loading all document as a dynamic type, converting them and saving them would be easy enough but in a real database that would not be practical. So lets look at a better solution fixing the database.


Updating the database on the server

Instead of downloading each document, updating the structure and saving it back to the server it is much better to do these sort of actions on the server itself. Fortunately RavenDB has the capability to execute database commands on the server. These update commands can be PatchRequest objects that will let you do a large number of things using a nice C# API. And a the ultimate fallback there is the ScriptedPatchRequest which will let you execute a block of JavaScript code on the server. Why JavaScript? Well RavenDB stores things in JSON and the server is really not dependent on a .NET client.

Using the ScriptedPatchRequest we can either execute a patch on a single document or on a collection of documents. In this case I want to update all Order documents to reflect their new structure. It turns out this is quite simple


   1: using (IDocumentStore documentStore = new DocumentStore

   2: {

   3:     ConnectionStringName = "Northwind"

   4: }.Initialize())

   5: {

   6:     var javaScript = @"...";


   8:     documentStore.DatabaseCommands.UpdateByIndex(

   9:         "Raven/DocumentsByEntityName",

  10:         new IndexQuery

  11:         {

  12:             Query = "Tag:Orders"

  13:         },

  14:         new ScriptedPatchRequest

  15:         {

  16:             Script = javaScript

  17:         });

  18: }

This code will execute the JavaScript code to patch the document once for each document in the Orders collection.


The JavaScript code to execute is quite simple, just make the changes required to the document and you are set.

   1: var company = LoadDocument(this.Company); 

   2: this.Company = {Id: this.Company, Name: company.Name};


   4: var employee = LoadDocument(this.Employee);

   5: this.Employee = {Id: this.Employee, Name: employee.FirstName + ' ' + employee.LastName};


   7: var shipVia = LoadDocument(this.ShipVia); 

   8: this.ShipVia = {Id: this.ShipVia, Name: shipVia.Name};


  10: this.Lines.forEach(function(line){

  11:     var product = LoadDocument(line.Product); 

  12:     line.Product = {Id: line.Product, Name: product.Name};

  13:     delete line.ProductName;

  14: });


In this case I am converting the Company, Employee, ShipVia and Product properties to have the new structure. Additionally I am removing the ProductName from the OrderLine as that is no longer needed.


Sweet :-)

]]> 0
Denormalizing data in RavenDB Tue, 01 Jul 2014 09:30:59 +0000 /blogs/theproblemsolver/archive/2014/07/01/denormalizing-data-in-ravendb.aspx Continue reading Denormalizing data in RavenDB]]> One of the things with RavenDB, or NoSQL document databases in general, is that you don’t do joins to combine data. Normally you try to model the documents you store in such a way that the data you need for most common actions is stored in the document itself. That often means denormalizing data. When you first get started with document databases that feels strange, after all with relational databases we are taught to normalize data as much as possible and not repeat the same values. Where normalizing data is great for updates and minimizing the size of databases it is less than ideal for querying. This is because when querying we need to join various tables to turn abstract foreign keys into something that is actually understandable by the end user. And while relational databases are pretty good at joining tables these operations are not free, instead we pay for the that with every query we do. Now it turns out that most applications are read heavy and not write heavy. And as a result optimizing writes  actually hurts something like 99% of the database operations we do.

With document database like RavenDB we can’t even do a join action. When we normalize data the client actively has to fetch related data and turn those abstract identities to other documents into, for a user, meaningful values. Normally the documents in a RavenDB database are much more denormalized that similar data in a SQL server database would be. The result is that for most operations a single IDocumentSession.Load() is enough to work with a document.


That data makes sense to denormalize?

Not everything makes sense to denormalize, normally only relatively static data that is frequently needed is denormalized. Why relatively static data? Simple, every time the master document for that piece of data is updated all documents where it might be denormalized also need to be updated. And while not especially difficult it would become a bottleneck if it happened to often. Fortunately there is enough data that fits the criteria.


The RavenDB example data

The de-facto sample data for SQL Server is the Northwind database. And by sheer coincidence it so happens that RavenDB also ships with this same database, except now in document form. With lots of .NET developers being familiar with SQL Server this Northwind database is often the first stop at how a document database should be constructed.


As you can see in the screenshot from the RavenDB studio a relatively small number of collections replaces the tables from SQL Server. Nice :-)


The structure used to save an order is also nice and simple, just the Order and OrderLine classes saved in a single document.

   1: public class Order

   2: {

   3:     public string Id { get; set; }

   4:     public string Company { get; set; }

   5:     public string Employee { get; set; }

   6:     public DateTime OrderedAt { get; set; }

   7:     public DateTime RequireAt { get; set; }

   8:     public DateTime? ShippedAt { get; set; }

   9:     public Address ShipTo { get; set; }

  10:     public string ShipVia { get; set; }

  11:     public decimal Freight { get; set; }

  12:     public List<OrderLine> Lines { get; set; }

  13: }


  15: public class OrderLine

  16: {

  17:     public string Product { get; set; }

  18:     public string ProductName { get; set; }

  19:     public decimal PricePerUnit { get; set; }

  20:     public int Quantity { get; set; }

  21:     public decimal Discount { get; set; }

  22: }


One missing thing

Nice as this may be there is one missing thing. Other than the product name being sold and it’s price there is no data denormalized. This means that if we want to display to the user for even the most basic of uses we will need to load additional document. For example the Company property in an order just contains the identity of a customer. If we want to display the order the very least we would have to do is load the company and display the customers name instead of its identity. And the same it true for the employee and shipper.

While this sample database is not denormalized it turns out is is quite easy to do so ourselves.


Denormalizing the RavenDB Northwind database

The first step is to store the related name along with each referred to identity as seen below.



The order is the same but this time we can do common user interaction operations with just the one document and not be required to load additional documents. It turns out this is quite easy to do. The RavenDB documentation has a nice description on how to do that using INamedDocument and DenormalizedReference<T>. Using this technique makes it really easy and consistent to work with denormalized data and create a document structure like the one above. The change to the Order and OrderLine classes are minimal. All I had to do is replace the string type Company property with one of type DenormalizedReference<Company>.

   1: public class Order

   2:  {

   3:      public string Id { get; set; }

   4:      public DenormalizedReference<Company> Company { get; set; }

   5:      public DenormalizedReference<Employee> Employee { get; set; }

   6:      public DateTime OrderedAt { get; set; }

   7:      public DateTime RequireAt { get; set; }

   8:      public DateTime? ShippedAt { get; set; }

   9:      public Address ShipTo { get; set; }

  10:      public DenormalizedReference<Shipper> ShipVia { get; set; }

  11:      public decimal Freight { get; set; }


  13: }


  15: public class OrderLine

  16: {

  17:     public DenormalizedReference<Product> Product { get; set; }

  18:     public string ProductName { get; set; }

  19:     public decimal PricePerUnit { get; set; }

  20:     public int Quantity { get; set; }

  21:     public decimal Discount { get; set; }

  22: }


The DenormalizedReference<T> and INamedDocument are also really simple and straight from the RavenDB documentation.

   1: public class DenormalizedReference<T> where T : INamedDocument

   2: {

   3:     public string Id { get; set; }

   4:     public string Name { get; set; }


   6:     public static implicit operator DenormalizedReference<T>(T doc)

   7:     {

   8:         return new DenormalizedReference<T>

   9:         {

  10:             Id = doc.Id,

  11:             Name = doc.Name

  12:         };

  13:     }

  14: }


  16: public interface INamedDocument

  17: {

  18:     string Id { get; }

  19:     string Name { get; }

  20: }


The implicit cast operator in the DenormalizedReference<T> makes using this really simple. Just assign a property and it will take case of the proper reference needed.

   1: var order = session.Load<Order>("orders/42");

   2: order.Company = session.Load<Company>("companies/11");


One useful extension method

Loading the single document and doing common operations should be easy now but there are still operations where you will need more data from the related entity. Loading them is easy enough.

   1: var customer = session.Load<Company>(order.Company.Id);


However using the DenormalizedReference<T> the structure and type is already captured in the Order class. Using this with a simple extension method makes the code even simpler which is always nice :-)

   1: public static class IDocumentSessionExtensions

   2: {

   3:     public static T Load<T>(this IDocumentSession session, DenormalizedReference<T> reference)

   4:         where T : INamedDocument

   5:     {

   6:         return session.Load<T>(reference.Id);

   7:     }

   8: }


This simple extension method will let is load the customer as follows:

   1: var customer = session.Load(order.Company);


Saves another few keystrokes and completely type safe. Sweet :-)



]]> 0