Sunday, August 25, 2013

Minimizing Angular.js in .NET MVC4 the right way

Introduction

When we write angular application we cannot minimize javascript file as we do regularly. This is because in angular most of the injectables are declared as strings bus used as properties. If we would minimize the js files the properties would be changes into letters (a, b,etc...) and angular won't be able to find these injectables declarations. 

In MVC4 we can use bundles to minimize js and css files. Unfortunately to my experience these classes are not working well with O.O javascript. I have also encountered other problems with naming conventions in files. If error is thrown while minimizing js file, the file will be served, but, will include stack trace of the error appended into the beginning of the javascript file, and this is not good to say the least. 

YUI Compressor

Yahoo has a pretty good compressor engine that allows to do the same and even more. Luckily, in MVC4 we can import YUI dlls to our project and override default compression engine of MVC bundles to use YUI instead. It can the be configured to leave angular injectables as-is while compressing and concatenating all the rest. 

Importing YUI 

First of all be sure you use 4.5 framework as YUI dlls requires that. Open "Package Manager Console" and enter the following line:

install-package YUICompressor.NET.Web.Optimization


This will install all the prerequisites and the YUI dlls.

Switching to YUI

Now we should override the default behavior of the bundles and direct MVC to use YUI minimization engine instead.
Inside BundleConfig.cs file we should create javascript compressor configuration instance and set ObfuscateJavascript = true. This configuration will direct YUI engine to leave the variables naming as is.

            var jsCompressorConfig = new JavaScriptCompressorConfig
            {
                ObfuscateJavascript = true
            };
            var jsTransform = new YuiCompressorTransform(jsCompressorConfig);

We now can start switching our bundles to work with YUI.
Assuming we keep naming conventions in our project file system we can bundle our js files as follows:

            bundles.Add(new Bundle("~/js/controllers.js", jsTransform).Include(
                        "~/js/controllers/controllers.js",
                        "~/js/controllers/*-controller.js"));

            bundles.Add(new Bundle("~/js/filters.js", jsTransform).Include(
                        "~/js/filters/filters.js",
                        "~/js/filters/*-filter.js"));
Taking into account that all of our controllers end with -controller.js we now have bundle that will include all the controllers in the controllers directory without the need to add anything after creating the new controller.

Sunday, August 18, 2013

Angular.js example from usergroup

Introduction

At 19/08/13 I've spoke at Gil Fink  UserGroup at Sela about introduction to Angular.js. Below a short overview of the example app presented.

Structure

When building Angular application is is most important to divide it into modules. The current example was relatively small so the modules division was made by different components of the framework (e.g. controller, services, filters, etc..). 
Note, that if the application is large and complex the division to modules should be made by features rather than by components. Each module should then contain everything related to the feature. It will allow us to take the feature to another Angular project with ease.

Please note, there are 5 examples in the main directory from the most basic to the most complex, I'll overview the last as it includes all the other examples as well

Bootstrapping

As an entry point I have the application.js file which defines all the modules available for the projects including the dependencies between them.

window.directives = angular.module('directives', [], function () {
});
window.services = angular.module('services', [], function () {
});
window.filters = angular.module('filters', [], function () {
});

Right after that, the main module configures the routes.

window.application = angular.module('myMovies', 
    ['directives', 'services', 'filters'], function ($routeProvider) {
    $routeProvider
        .when('/', {
            controller: 'mainCtrl',
            templateUrl: 'templates/movies_list_view.html'
        })
        .when('/about', {
            templateUrl: 'templates/about_view.html'
        })
        .when('/movieDetail/:id', {
            controller: 'movieDetailController',
            templateUrl: 'templates/movie_detail_view.html'
        })
        .otherwise({
            templateUrl:'templates/404.html'
        })
});

The $routeProvider has two functions. when - used to declare a valid route either with or without parameters and otherwise - will redirect at any illegal route entered.

Controllers

Two controllers are available one for displaying the movies on the main page and the other for displaying additional details about a movie
The mainController requests the mockService to get the movies data, and also defines event to remove movie on click.
The movieDetailController uses the same service to get movie by id. Note, the movie id is passed as a parameter in url (not as querystring). The controller then reads the parameter with the $routeParams provider.

Services

One service is available. the mockService gets it's data statically from another js file with timeout to simulate a delay.
Because I used timeout function there I need to call $scope.$apply() inside controller to notify Angular about changes to the data. 

        $scope.$apply(function () {
            $scope.model = {
                movie: movie
            }
        });

Normally, when fetching data from server we should use $http service to get the data, the $http service will take care for notifying about changes

Filters

Build-in filters are used in movies list template to filter movie results by the search field. Also, one custom filter is available to convert minutes to more visualisable format.

Templates

Templates for every page is available and are loaded when route gets resolved. Also 404 template is available for the 'otherwise' function.

Conclusion

To create this example I've simplified the structure of the project. The file structure should be a bit different and I hope that soon I'll post a full project example showing the structure as I see it. 
I also simplified the code for the sake of this example, so probably it won't look 100% the same in real life project.

The code examples are available here: http://goo.gl/1xlQFS

I'll be glad for every input you may have about this post or the examples. 

Sunday, May 26, 2013

Angular.js: Using promise injectable inside callback

Often when I want to make a http request from angular.js I write a service. Service can be used as injetable whenever needed.
In angular however there are promise service that implements the promise pattern. Using them can make the asynchronous work easier. For those who are unaware of what promises are there is a documentation available here.

When implementing the promise pattern inside service you probably will have to run the deffered.resolve() command inside the callback as javascript is most of the time asynchronous. The weird thing for me was that it does not work  from the callback. The function registered inside .then function will not run!

Consider the following example:
angular.module('myModule', [], function () {
})
    .service('dataService', ['$q', '$timeout', function ($q, $timeout) {
        this.getData = function () {
            var deferred = $q.defer();
            $timeout(function () {
                someHttpGetter.getData(data);
                deferred.resolve(data);
            }, 2000);
            return deferred.promise;
        };
    }]);

In this example the callback inside .then function will work correctly. On the other hand, this example:

angular.module('myModule', [], function () {
})
    .service('dataService', ['$q', '$timeout', function ($q, $timeout) {
        this.getData = function () {
            var deferred = $q.defer();
            $timeout(function () {
                someHttpGetter.getData(function (data) {
                    deferred.resolve(data);
                });
            }, 2000);
            return deferred.promise;
        };
    }]);

Here, the deffered.resolve() is inside a callback. It will not work.
The reason for that is that in the first example the resolve will happen inside the digest cycle of angular, while in the second example the resolve happens in callback, thus, outside the cycle.
The solution for this (as I found) is to inject the rootScope to the service and invoke the $rootScope.$apply() right after the resolve method. The complete working example should look like this:

angular.module('myModule', [], function () {
})
    .service('dataService', ['$rootScope', '$q', '$timeout', function ($rootScope, $q, $timeout) {
        this.getData = function () {
            var deferred = $q.defer();
            $timeout(function () {
                someHttpGetter.getData(function (data) {
                    deferred.resolve(data);
                    $rootScope.$apply();
                });
            }, 2000);
            return deferred.promise;
        };
    }]);

Wednesday, May 22, 2013

AngularJS User Group @ Microsoft Raanana

Yesterday I gave session about AngularJs at Microsoft Raanana. The sessions gave first impression about AngularJS.

You can find the presentation and the code here

Thanks for everyone who came! Hope you enjoyed.

Sunday, December 23, 2012

Mobile Single Page Application

Intorduction

A few days back I’ve started to think about creating a mobile SPA at work. Now, we work with jQuery Mobile to create mobile apps. jQuery Mobile has some sort of a behavior that can make your website look like a SPA website.

Now, jQuery Mobile looks at each html page for div with data-role “page” and every time one navigates to another page, the next page retrieved by AJAX request and the “page” div is gets injected into the DOM. It also adds a transition animation and thus it looks like the page is changing on-the-fly. There are a couple of potential problems with this technique:

  • The whole html is retrieved per page request resulting in high-bandwidth calls which actually has impact on the amount of data used (which is limited to a couple of GBs per month) and on the speed.
  • You cannot add scripts in the next page outside the “page” data-role div because it won’t get injected to the main page and so won’t exist. Also, the jQuery document.ready event will only fire once on the initial page request, although jQuery Mobile provides another method to deal with this problem (e.g. pagecreate) it’s less convenient.
  • Since more than one page gets injected into the same html document you need to be sure not to use same id attributes in two different pages because it will create more than one element with the same id and will create id conflicts on the DOM.

There is one thing though that in my opinion works very well in jQuery mobile. The mobile UI and layout. It is relatively easy to create and customize the UI with jQuery Mobile. Also, you do not need to worry about device-width issues, since they are resolved automatically by the framework.

So to start with something I had to choose libraries to work with.

So what do we need?

We work extensively with knockoutJS to gain the MVVM behavior in javascript. This framework looks mature enough so no reason to skip it. Now, knockout will also give the ability to use templating ability to dynamically display data. One limitation with the knockout templates is that you can only place them in the same html file they are used in. To handle this we can use another library which, can be found here.

For additional info please visit knockoutJS website

We will also need routing engine. Two libraries were considered:, sammyJS and pathJS. And of course the jQuery Mobile framework to get the mobile look & feel. So, we end up with the following:

  • jQuery Mobile
  • knockoutJS
  • pathJS
  • external template engine

After trial and error I was able to create a small SPA example using all of this component.

There are good MVC client side frameworks for SPA like backbone or ember. I did not try to reinvent the wheel. The purpose of this example was to check if we can use simple matured libraries we already use on daily basis in order to create simple SPA without suffering from high learning curve which exists in other frameworks.

The full example is included in the following git.

Thursday, November 29, 2012

MongoDB–NoSQL database

Lately I’ve been hearing a lot about so called NoSQL databases, Google has one, the BigTable. These databases are highly optimized for retrieving and saving data. They do not use SQL-like languages for data manipulation, and save data not in tables but in collections under key:value objects.

When writing rich client web applications you often find yourself moving data from the database through server side and to the client while serializing and converting the data to JSON in the process. Because of this the idea of a database that will save data as objects and will on start deliver the data to you in JSON seems very appealing.

After little research on this topic I’ve found the MongoDB database that can be found here. This database is used by number of companies e.g. SAP, Disney, Github, and many others. So, I’ve decided to take it to a test drive.

Installation

So, first of all we need to download the MongoDB from the website. There is not installation, just a zip file that should be extracted into a directory of your choice.

Inside MongoDB\bin directory you will find two files of interest, the mongod.exe and mongo.exe files. mongod file is the one we will use to startup the server, mongo file will is a console to run commands against the server. By default MongoDB will try to save all the databases into c:\data\db directory. If this directory does not exist mongod will fail to start unless we will create it or specify another directory where to save the databases.

To start MongoDB with specific save directory the following command should be initiated:

mongod –dbpath <directory>

After this, the following lines should be displayed:

image

You can also start MongoDB as a windows service. The following command line should be initiated:
mongod –install do not forget to add –dbpath if needed

Actually this is it, we have just installed and started a MongoDB server. Now we can start mongo.exe to run script commands on the database. We can also open web browser and navigate to localhost:28017 to be able see web adminsitration window:

image

Giving it a try

When we start the mongo console it will by default connect to test database, the database does not yet exist, it will be created when we save our first data in some collection. It is important to note, MongoDB does not have tables, it has collections instead. Instead of rows it has documents (objects). To save data we should run the save function on collection of our choice and pass a json object to it. For example, if we need to add a person with it’s first and last name to people collection it should look like this:

image

Now, to get all the documents from a collection we should run find function:

image

You can see we received the object we added to people collection and with it can back an _id field. This field was given to the document by the MongoDB and it represents a unique ID. If we would try to imagine how this function would look in SQL it should look like this:

SELECT * FROM People

You can get documents from collection on condition, for example:

db.people.find({firstName:”Israel”})

will be equals to

SELECT * FROM People WHERE firstName = ‘israel’

And of course you can get only part of the members in documents like so:

db.prople.find({}, {firstName:true})

is as same as

SELECT firstName FROM People

Last but not least for this post: we are free to change database whenever we want, for this we should run the use <database> command. Again, if the database does not yet exist it will not be created right away, it will be created when we save command.

Other options for the console can be printed out if you initiate help command

Conclusion

No-SQL database seems as a great and easy way to save and administer large amounts of data and then retrieve them as object right from the database. At MongoDB website you can find some of the user cases when you should consider using a No-SQL database, page can be found here.

There is also MongoDB ports for various programming languages that can be found here.

Wednesday, November 28, 2012

jQuery.inputFilter

Just wrote small jQuery plugin to filter text inside inputs. The plugin will limit characters input for the option chosen. The following options are available:
jQuery.inputFilter{{
    type: 'onlyNumbers|onlyEnglish'
});
onlyNumbers options is a default.

Plugin available here:
https://github.com/dimkinv/jQuery.inputFilter