Sunday, October 12, 2014

Changes to model done outside of AngularJS' callback doesn't reflect on UI

Callbacks made outside of AngularJS can't be monitored by AngularJS, hence when there are changes on model it will not take effect on UI. An example:
<div ng-app='theApp' ng-controller='SampleController as c'>
    
    <label>Search</label><p><input type='text' ng-model='c.topic'/>    
    
    <button ng-click='c.getTopMatch()'>Get Top Match</button>
    
    <p>
        <span ng-show='c.topMatch.length !=""'>Top Match: {{c.topMatch}}<span> 
    </p>
        
</div>


var app = angular.module('theApp', ['oitozero.ngSweetAlert']);

app.controller('SampleController',['$http', 'SweetAlert', function($http, SweetAlert) {
    var self = this;
    
    self.topic = 'angularjs';

    self.topMatch = '';

    
    self.getTopMatch = function() {
                        
        $http.jsonp('http://ajax.googleapis.com/ajax/services/search/web?v=1.0&callback=JSON_CALLBACK',
                    {
                        params : { 'q' : self.topic }
                    })
        .success(function(data) {        

            self.topMatch = data.responseData.results[0].url;  
            
            SweetAlert.swal({
               title: "Clear Search?",
               text: "Everyone wants a clear textbox",
               type: "success",
               showCancelButton: true,
                cancelButtonText: 'No',
               confirmButtonText: "Yes!"
            }, 
            function(isConfirm){                        
     
                if (!isConfirm) return;
                  
                self.topic = '';
                
                
            });      
            
        });     
        
    };
}]);


We can solve that by wrapping our changes on model inside of AngularJS $q service:
var app = angular.module('theApp', ['oitozero.ngSweetAlert']);

app.controller('SampleController',['$http', '$q', 'SweetAlert', function($http, $q, SweetAlert) {
    var self = this;
    
    self.topic = 'angularjs';

    self.topMatch = '';

    
    self.getTopMatch = function() {
                        
        $http.jsonp('http://ajax.googleapis.com/ajax/services/search/web?v=1.0&callback=JSON_CALLBACK',
                    {
                        params : { 'q' : self.topic }
                    })
        .success(function(data) {        

            self.topMatch = data.responseData.results[0].url;  
            
            SweetAlert.swal({
               title: "Clear Search?",
               text: "Everyone wants a clear textbox",
               type: "success",
               showCancelButton: true,
               cancelButtonText: 'No',
               confirmButtonText: "Yes!"
            }, 
            function(isConfirm){                        

                if (!isConfirm) return;                

                var deferred = $q.defer();
                deferred.promise.then(function() {
                    self.topic = '';
                });
                
                deferred.resolve();
                
            });      
            
        });     
        
    };
}]);


Note that we need to inject $q service to our controller. If that's a bit overkill, we can skip the use of $q service and use another approach. Another approach is to dynamically add a promise on existing $http's promise when a callback outside of AngularJS is made, an example:

var app = angular.module('theApp', ['oitozero.ngSweetAlert']);

app.controller('SampleController',['$http', 'SweetAlert', function($http, SweetAlert) {
    var self = this;
    
    self.topic = 'angularjs';

    self.topMatch = '';

    
    self.getTopMatch = function() {
                        
        var thePromise = 
            $http.jsonp('http://ajax.googleapis.com/ajax/services/search/web?v=1.0&callback=JSON_CALLBACK',
                    {
                        params : { 'q' : self.topic }
                    })
            .success(function(data) {        
    
                self.topMatch = data.responseData.results[0].url;  
                
                SweetAlert.swal({
                   title: "Clear Search?",
                   text: "Everyone wants a clear textbox",
                   type: "success",
                   showCancelButton: true,
                    cancelButtonText: 'No',
                   confirmButtonText: "Yes!"
                }, 
                function(){                                        
                    
                    thePromise.then(function() {
                        self.topic = '';
                    });                                
                    
                });      
                
            });     
        
    };
}]);


UPDATE


Another good approach is to use $timeout, unlike $scope.$apply/$scope.$digest, $timeout is testable. Though it works, it is not advisable to use $scope.$apply/$scope.$digest in a controller. $timeout works and it is testable:

var app = angular.module('theApp', ['oitozero.ngSweetAlert']);

app.controller('SampleController',['$http', '$timeout', 'SweetAlert', function($http, $timeout, SweetAlert) {
    var self = this;
    
    self.topic = 'angularjs';

    self.topMatch = '';

    
    self.getTopMatch = function() {
                        
        $http.jsonp('http://ajax.googleapis.com/ajax/services/search/web?v=1.0&callback=JSON_CALLBACK',
                    {
                        params : { 'q' : self.topic }
                    })
        .success(function(data) {        

            self.topMatch = data.responseData.results[0].url;  
            
            SweetAlert.swal({
               title: "Clear Search?",
               text: "Everyone wants a clear textbox",
               type: "success",
               showCancelButton: true,
                cancelButtonText: 'No',
               confirmButtonText: "Yes!"
            }, 
            function(isConfirm){                        

                if (!isConfirm) return;
                
                $timeout(function() {
                    self.topic = '';
                });
                
            });      
            
        });     
        
    };
}]);


Happy Coding!

Thursday, October 9, 2014

AngularJS Get Its POJO Back

Earlier AngularJS version (e.g., 0.9) has no $scope:

function GreetingCtrl(){
    this.greeting = 'Hello';
    this.name = 'Michael';
}    

<div ng:controller='GreetingCtrl'>
      <p>{{greeting}} {{name}}</p>
</div>    

Live example: http://jsfiddle.net/ywuwwgu5/


That's one of the things I find elegant when AngularJS was in its infancy. Aside from there's no special class to inherit from, there is no specialized object(e.g., $scope) the framework need to use in order to do model-binding, just a POJO would bind fine

So on later version of AngularJS when $scope was introduced, it felt like, 'oh, my javascript code would be tied to AngularJS!' I'm thinking why the newer AngularJS version can't do the good old magic where the older framework can bind directly to object's properties, to a POJO


Though porting the code to other javascript MV* frameworks it is not the main overriding concern developers has to face when deciding to use AngularJS or not, there's still a value in making a framework able to work with generic code as much as possible. If there's another javascirpt MV* framework that can bind directly to a POJO like the code above, we can just plug that framework to our generic javascript code and we don't have to rewrite a single line of code.

Code portability feels empowering, just like it feel empowering that your SQL knowledge(or at least a subset of) on one RDBMS is transferable to another RDBMS with little to no rewrite. Unlike with using specialized object like $scope, it feels $scope has many moving parts in it and code portability is just a pipe dream, your code is forever tied to AngularJS; nothing wrong with a code associated to high-quality framework like AngularJS, but still



Now that there is Controller as syntax, we could make our javascript code as generic as possible(and portable), again, yay!

With exactly the same generic AngularJS 0.9 controller code above, we can now re-use it on AngularJS 1.2 using Controller as syntax. We just have to adjust our view, we need to prefix the controller's alias on models we wanted to bind to. Neat!
<div ng-controller='GreetingCtrl as g'>
    <p>{{g.greeting}} {{g.name}}</p>
</div>    


Live code: http://jsfiddle.net/x8mwtox9/


A nice insight so AngularJS 1.2's Controller as won't feel too magical, in AngularJS 1.1 we can also use the this approach of AngularJS 1.2 controller above (albeit without the Controller as syntax) and it would still work. AngularJS 1.1 has no Controller as, but we can achieve the AngularJS 1.2 this code and view just by assigning this on a variable in $scope object:
function GreetingCtrl($scope){
    $scope.g = this;
    this.greeting = 'Hello';
    this.name = 'Michael';
}    

<div ng-controller='GreetingCtrl'>
   <p>{{g.greeting}} {{g.name}}</p>
</div>       

Live code: http://jsfiddle.net/hqfhutLo/


With AngularJS 1.2's Controller as feature, aside from it removes the need of assigning this to $scope manually, we don't have to use specialized object such as $scope anymore. Very generic code, neat! :-)



Happy Coding!

Sunday, October 5, 2014

Use citext on PostgreSQL

Case-insensitive text type is not installed by defaut on Postgres, to use, run this in pgAdmin:

CREATE EXTENSION IF NOT EXISTS citext WITH SCHEMA public;

Wednesday, October 1, 2014

404 when accessing a subdirectory from nginx

I deployed an ASP.NET MVC application on Ubuntu + nginx + fastcgi-mono-server4, this works:

http://www.example.com/


However this doesn't:

http://www.example.com/Companies/Search?q=softwaremint


The fix is apparently simple, instead of letting nginx manage the subdirectories, let ASP.NET MVC manage it by removing the following (configuration is in /etc/nginx/sites-available/default) :

try_files $uri $uri/ =404;

Failed reloading nginx configuration nginx

michael@buen:/etc/init.d$ sudo nginx -t &&  service nginx reload
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
 * Reloading nginx configuration nginx                                   [fail]
michael@buen:/etc/init.d$ sudo nginx -t && sudo service nginx reload
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
 * Reloading nginx configuration nginx                                   [ OK ]

Put sudo on service too

Saturday, September 27, 2014

Nested route and folder in Laravel

Nested route and folder in Laravel

First approach:

You have this existing route..

Route::get('/Home/{identifikation?}', 'HomeController@showWelcome');

..and you have this existing code organization:

/controllers
    /HomeController.php


And this home controller:

<?php

class HomeController extends BaseController
{

    public function showWelcome($identifikation = null)
    {
        $p = new Person; // this Person class is residing in the folder: /models
        $p->firstname = 'Michael Angelo ' . $identifikation;
        $p->lastname = 'Buen';
        $p->nick = 'Kel';



        // 'Home/ShowWelcome' resolves to /views/Home/ShowWelcome.blade.php
        return View::make('Home/ShowWelcome')->with('ninjaTurtle', $p);

    }

}



However, you have a need to move the Home url under Admin..

Route::get('/Admin/Home/{identifikation?}', 'HomeController@showWelcome');

..and likewise you wanted to move HomeController under Admin folder so the new url maps symmetrically to your code organization:

/controllers 
    /Admin
        /HomeController.php


After moving HomeController under /controllers/Admin folder, go to command-line and run:
composer dump-autoload


Then re-launch your web server:
php artisan serve


That's it! With Laravel, you can route url that maps symmetrically to your code organization. Whereas in ASP.NET MVC, controllers are just limited in these two places: the Controllers and Areas/AreaNameHere/Controllers folders, the controller's folder can't be nested. I digress


However, every time you need to move your controller to another folder, you have to do the composer dump-autoload command-line ritual in order for Laravel to find your controller. Failing to do so, you'll always receive the error "Whoops, looks like something went wrong."



Second approach:

To avoid the composer dump-autoload ritual, we can do it in another way. We'll use PHP's namespace. With the following code organization..
/controllers 
    /Admin
        /HomeController.php

..we'll have to change the routing as followed, we prefix the Admin\ namespace to HomeController class:
Route::get('/Admin/Home/{identifikation?}', 'Admin\HomeController@showWelcome');


..,then just add namespace Admin to HomeController.php:
<?php


namespace Admin;

class HomeController extends \BaseController
{

    public function showWelcome($identifikation = null)
    {
        $p = new \Person;
        $p->firstname = 'Michael Angelo ' . $identifikation;
        $p->lastname = 'Buen';
        $p->nick = 'Kel';

        // 'Home/ShowWelcome' resolves to /views/Home/ShowWelcome.blade.php
        return \View::make('Home/ShowWelcome')->with('ninjaTurtle', $p);

    }

}


As you noticed we have to prefix backslash character on the classes; failing to do so, PHP (not Laravel) will look for BaseController, Person and View classes under the namespace of Admin. To make PHP look for those three classes under the global namespace, we have to prefix those classes with backslash. As we might have to use those classes multiple times, a better approach is to import those classes using the keyword use so we don't have to prefix backslash on all classes:


<?php


namespace Admin;

use BaseController, Person, View;

class HomeController extends BaseController
{

    public function showWelcome($identifikation = null)
    {
        $p = new Person;
        $p->firstname = 'Michael Angelo ' . $identifikation;
        $p->lastname = 'Buen';
        $p->nick = 'Kel';



        // 'Home/ShowWelcome' resolves to /views/Home/ShowWelcome.blade.php
        return View::make('Home/ShowWelcome')->with('ninjaTurtle', $p);

    }

}


You might think, maybe we can just do "use \;", unfortunately PHP doesn't work that way, it doesn't work like C#'s using functionality


On a side note, it's unfortunate that PHP need to use "\" character for namespace delimiter as the dot character is used for string concatenation, otherwise the controller will not look like a folder:

Route::get('/Admin/Home/{identifikation?}', 'Admin.HomeController@showWelcome');


Anyway, when we use namespace, Laravel enforces the controller's code organization to mimic the namespace structure. The HomeController must be moved under the Admin folder. At least in Windows the backslash resembles the code organization :-)

Route::get('/Admin/Home/{identifikation?}', 'Admin\HomeController@showWelcome');



Happy Coding!

Friday, September 26, 2014

Content-heavy sites, choosing between Ruby-on-Rails and PHP

"Easy training, hard battle. Hard training, easy battle!" -- http://www.leonardteo.com/2012/07/ruby-on-rails-vs-php-the-good-the-bad/


While reading Leonard Teo's article on when to choose Ruby-on-Rails or PHP, reading the first few paragraphs I wanted to learn RoR, then on next few paragraphs I'm leaning towards to learn PHP again, then on the middle paragraphs it seems like learning RoR is a wiser choice, but then on the last few paragraphs it felt to me PHP is not that bad; and then when while reading the comments, I'm gravitating again towards RoR, oh well.. :-) It took some six swings when choosing between RoR vs PHP while reading the article up to the last comment


Can't blame me :-) The article was written in 2012 and then updated this year and there are many insightful comments on that article too, having read the entire article and comments, it looks like there is now a renaissance on PHP. There are now new PHP frameworks which doesn't carry the crufts of the older PHP versions and only the language's latest capabilities are applied to new frameworks, making those newer frameworks cleaner and developer-friendly. A PHP MVC framework like Laravel is such an example



I tweeted:

RoR is a mature framework now, it's boring: http://www.leonardteo.com/2012/07/ruby-on-rails-vs-php-the-good-the-bad/

RT @nguerrera Great code is often boring. Exciting code is often wrong.



While RoR is mature now, I'm gravitating towards Laravel; not because it is exciting, but that helps too :-) I used PHP for about half a year on my first job a long time ago, so I'm new to PHP MVC frameworks now. The insightful thoughts from Pierre sealed the deal for me:

As others have suggested here you really should look at Laravel. The frameworks you mention (with the exception o possibly symphony) are what I would call "legacy" frameworks. They all have a long history going back to PHP 4 and are burdened by that legacy.

Laravel lacks that. The author of the framework was not a PHP developer originally. He came from a .NET/Ruby background and arrived on the scene only a few years ago. As such he started by supporting php 5.3 and didn't bother with legacy support.

So Laravel has some of the best features from Rails and .NET baked in: ORM, Active Records, robust routing, generators, migrations, BLADE (think Razor in .NET) etc.... In addition serious PHP frameworks now use Composer for all their components and most of their core. Just like Ruby Gems and Node's packages everything is centralized and not coupled to a particular framework. So you're only updating components via composer using the command line and not your entire framework. (Symphony is using this method as well)

In short, PHP has grown up in some respects. Laravel really is the closest thing PHP has to Rails, if you want to compare something closer in scope have a look at it.



With the author of Laravel experience in ASP.NET MVC, I'm curious to learn how much of the good ideas in ASP.NET MVC are injected into Laravel


So why not just adopt ASP.NET MVC for content-heavy sites since I have experience with ASP.NET MVC too? PHP is ubiquitous, cloud choices is definitely a plus. Microsoft having decided Windows on Azure should carry a premium price tag, Linux on Azure is budget-friendly



As compared to Ruby-on-Rails, Laravel has the controllers done right. See: http://lostechies.com/derickbailey/2014/01/30/playing-with-laravel-4-the-php-mvc-framework-and-telerik-ui/



And how about Java MVC frameworks? You can forgot Java when your server's resources is limited



Happy Coding!