AngularJS, MEAN, MongoDB

MongoDB Backup/Dump and Restore

MongoDB Backup/Dump and Restore , one of the most important things we must need to know !

ssh example.host
mongodump --db productionDb
tar czf ./dump.tgz ./dump
scp dump.tgz user@development.host

tar xzf ./dump.tgz
cd ./dump
mongorestore --db example_test ./productionDb

Advertisements
Standard
AngularJS, ExpressJS, MEAN, MongoDB, NodeJS

MEAN.io – Installing in Windows 8.1 (MEAN Stack)

MEAN.io is becoming a Popular Modern Framework for MEAN Stack(Mongo , Express , Angular , Node). I have recently tried it out and had real fun with it , such an awesome Boilerplate for MEAN Stack.

banner-top-ninja

Most of the Developers around the world work on MAC/LINUX when they are with MEAN. But I thought why not to write a Full Process for Windows Users . Cool , lets do the whole thing to get running an MEAN.io app in Win8.1.

First , We need to install the Core Node And Mongo.

1.Lets install Node first.Go to Node Download Center and Download Windows Installer (.msi) based on your OS Architecture and just Install with few Clicks.

2.Lets Install MongoDB , to see How to Install Click Here

3.Some of Mean.io dependencies uses node-gyp with supported Python version 2.7.3.

3.1.Install Python From here

Python

Python

3.2. Install Microsoft Visual Studio C++ 2012/13 for Windows Desktop (Express version works well)

3.3.Install node-gyp

npm install -g node-gyp

4. Install Gulp and Bower

npm install -g gulp

npm install -g bower

5.Install the MEAN.io CLI

npm install -g mean-cli

6.Now create your own app

mean init myApp

cd myApp
npm install

7.To start you application run –

gulp

Alternatively, when not using gulp (and for production environments)

node server.js

And browse http://localhost:3000

You can see your Site , All done by the amazing Mean.io

Mean

Mean

Standard
AngularJS, JavaScript, MEAN

AngularJS One Time Binding Concept

Angular 1.3 added a new feature called One Time Binding . This is definitely an awesome enhancement for performance of an angular app.

We know , If a data changes in angular app, The $digest cycle checks for changes through watchers and gets the new value and renders the view. But if the app gets bigger with so many data , so many bindings , the $$watchers count increases with $digest loop size. Though in a large collection only few data got changed but the whole data gets rendered which is not good for performance.

One-time expressions will stop recalculating once they are stable, which happens after the first digest if the expression result is a non-undefined value

The main purpose of one-time binding expression is to provide a way to create a binding that gets deregistered and frees up resources once the binding is stabilized. Reducing the number of expressions being watched makes the digest loop faster and allows more information to be displayed at the same time.

Lets see how we can do this in angular app.

<div>
        <h1>Angular OneTimeBinding</h1>
        <br />
        <table>
            <tr ng-repeat="profile in profiles">
                <td>
                    {{::profile.Id}}
                </td>
                <td>
                    {{::profile.Name}}
                </td>
                <td>
                    {{::profile.Address}}
                </td>
            </tr>
        </table>
        <br />

        <button ng-click="addProfiles()">addProfiles</button>
        <button ng-click="getWatchers()">getWatchers</button>

        <div>
            <h3>OneTimeBinding Watchers Count :::  {{totalWatchers}}</h3>
        </div>

    </div>

Here I added {{::}} this syntax for One Time Binding.

Lets see our Controller’s code-

app.controller('profileCtrl' , ['$scope' , function($scope){
    console.log('profileCtrl is running...');

    $scope.profiles = [
                    { Id: 1, Name: 'Masoom', Address: 'Dhaka1' },
                    { Id : 2 , Name : 'Talukdar' , Address : 'Dhaka2' },
                    { Id: 3, Name: 'Shahjada', Address: 'Dhaka3' }
    ];

    $scope.addProfiles = function () {
        var id = $scope.profiles.length + 1;
        $scope.profiles.push({ Id: id, Name: 'AAAA' + id, Address: 'Dhaka' + id });
    };

    $scope.getWatchers = function () {
        var watchers = ($scope.$$watchers) ? $scope.$$watchers.length : 0;
        var child = $scope.$$childHead;
        while (child) {
            watchers += (child.$$watchers) ? child.$$watchers.length : 0;
            child = child.$$nextSibling;
        }
        $scope.totalWatchers = watchers;
    };

}]);

Here If we add a new profile by clicking the addProfile Button , it will add a Row , but the Watcher Count will not increase as its One Time Binding But if we remove the OneTimeBinding Syntax , I will increase the count which hampers the performance.

And, if we do not use One Time Binding in Property Level , but in Collection level like below , then If we click and click addProfile button , it will add new item in the collection inside $scope , but the UI will not render the new Items coz we have used OneTimeBinding in the Collection/List Level.

<table>
            <tr ng-repeat="profile in ::profiles">
                <td>
                    {{profile.Id}}
                </td>
                <td>
                    {{profile.Name}}
                </td>
                <td>
                    {{profile.Address}}
                </td>
            </tr>
        </table>

Hope , It helps you.

Cheers

Standard
AngularJS

Apology for not being regular here !

I know and I agree , I was not so much active in writing articles in 2014 ,In fact I was too much busy/sad/frustrated with so many things( New Language/frameworks are also parts of these).

I am planning to be more dedicated on writing new Articles in 2015. And I really need to thank to all the people of the world who visited my site in 2014.

And WordPress sent me an annual report that my site got traffic from 155 countries in 2014 which made me much confident and forced me to be more dedicated here.I thank you all.

Here is the public report : https://shahjadatalukdar.wordpress.com/2014/annual-report/

In 2015 , I am planning to write articles on MEAN stack (Mongo , Express , Angular , Node) .

I have already few articles on Angular.And Will continue more. Please visit/subscribe/like/comment on articles . I really appreciate your valuable comments/suggestions.

Cheers

Shahjada

Standard
AngularJS

UnderscoreJS – sortBy() Trick ::: It is not documented at their Site ! This is very important Shit !!!

In any programming language , Sorting is an extreme important part. In JavaScript , we need to do a lot.

Generally , we do Sorting for items like this a lot , like array containing multiple items(Numbers/Strings/Sometimes Objects etc).

 

1 var myNumberArray = [5,9,8,3,7,9];

UnderscoreJS is an awesome library which provide us so many small and important features to use.

Among those , Sorting is one . And by Underscore Sorting , we can Sort List of Objects to more than one degree. Means -Let We have a List of JSON Objects and that Object has multiple Properties(domain, url etc…) and we need to Sort the List as like –

First Sort the List based on domain and then url,it should be two degree.

Not like First sort the List based on domain and sort that result based on url,in this way we will get the wrong result.

Lets see the example below.

 1 var domainWithUrls =  [
 2             {domain:'abc.com' , url : 'abc.com/aaa.html'},
 3             {domain:'abc.com' , url : 'abc.com/ccc.html'},
 4             {domain:'abc.com' , url : 'abc.com/bbb.html'},
 5             {domain:'xyz.com' , url : 'xyz.com/aaa.html'},
 6             {domain:'xyz.com' , url : 'xyz.com/ccc.html'},
 7             {domain:'xyz.com' , url : 'xyz.com/bbb.html'},
 8             {domain:'pqr.com' , url : 'pqr.com/aaa.html'},
 9             {domain:'pqr.com' , url : 'pqr.com/ccc.html'},
10             {domain:'pqr.com' , url : 'pqr.com/bbb.html'}
11         ];
12 
13         var sortedItems = _.sortBy(domainWithUrls, function (obj) {
14             
15             return [obj.domain, obj.url];
16         });
17 
18         console.log(sortedItems);

And plz see the result in the image.

UnderscoreJS - sortBY() Trick

UnderscoreJS – sortBy() Trick

Unfortunately ,Though This multiple degree Sorting feature is available in UnderscoreJS , But this is not documented !!! Sad !!!

Its awesome and can save a good amount of development time . I needed this and dug into that , and discovered this awesome feature.Thought to share with you all.Hope , it helps.

Thanks.Cheers !!!

Standard
AngularJS, ASP.Net MVC, JavaScript, jQuery, jQuery AJAX, MVC WebAPI

Add Request Header for REST API Calling with AngularJS & jQuery

In the Web World , We always call REST APIs from our Web Applications .

When We call REST APIs through jQuery or AngularJS , they added few default Request Headers .

But many a time , we need to pass Custom Request Headers for different purposes.

A Common scenario is for Authentication we need to pass Customer Request header .

But how we can add this ?

Lets see the below samples :::

for jQuery , we can easily add Request Headers when we do AJAX Calling .

$.ajax({
            type: "POST",
            url: '/api/test',
            data: myObj,
            headers: { 'Custom-Header': 'Value'},
            success: function (resp) {
                alert(resp);
            },
            error: function (x, y, z) {
                alert(x);
            }
        });

In AngularJS , If we use $http for REST API calling , we can add Request Header like below , after we create AngularJS Module , we can do :::

myModule.run(['$route', '$http', function ($route, $http) {
            $http.defaults.headers.common.CustomeHeader = 'Value';
        }]);

Thanks

Standard
AngularJS, HTML5, JavaScript

WebSQL : Welcome to client side DB – Part1

I think , We,all the Devs, know about SQL . Like , we have already worked with MySQL , MS SQL Server etc .

But then what is WebSQL ? If I say in a simple statement – WebSQL is SQL which is available in Client Browser .

Inside Browser :S ? Where is it ? I never saw that :@

Then please see the below image 🙂

WebSQL in Chrome Browser

WebSQL in Chrome Browser

Now lets begin…

With HTML5, there was also a desire to develop applications so that they’d run off-line. Where could they store data when there is no Internet?

Currently , we can store Data in browser in the below ways –

1.Local Storage
2.WebSQL
3.IndexedDB

You can get few browsers do not support all these , like previous versions.

LocalStorage can store data in Key-Value pairs but nothing more than that.To know more about LocalStorage , you can check out my another Article on LocalStorage .

WebSQL is based on a free database product called SQLite which is written in C , Go here

In a WebSQL Database , we can create DB and Tables kinda like MySQL or SQL Server and store Data in the same manner what we knew earlier 🙂

Lets do some Coding…

I have used WebSQL in a AngularJS application . I have created an Angular Service which is separated from another Controllers and can be injected in any controller when needed where I have used WebSQL APIs .

Below is the code of my Service…

app.service('WebSqlDbService', function ($resource) {

    this.createDbAndTables = function () {
        var db = openDatabase('myClientDB', '1.0', 'Mobile Client DB', 2 * 1024 * 1024);
        db.transaction(function (tx) {
            tx.executeSql('CREATE TABLE IF NOT EXISTS User (UserInfo)');
        });
    };

    this.storeUserInfo = function (user) {
        var db = openDatabase('myClientDB', '1.0', 'Mobile Client DB', 2 * 1024 * 1024);
        db.transaction(function (tx) {
            tx.executeSql('INSERT INTO User (UserInfo) VALUES ( ?)', [JSON.stringify(user)]);
        });
    };

});

Then I have used WebSqlDbService in my Controller and called the Functions of the Service something like this…

$scope.userInfo = {
            UserId: 'as34fsdf*i#sad454',
            UserName: 'shahjada',
            IsAdmin: true
        };

        webSqlDbService.createDbAndTables();
        webSqlDbService.storeUserInfo($scope.userInfo);

I have saved the JSON Object by Stringifying , and when we will get this from WebSQL , we will convert it to JSON Object…

After saving Object to WebSQL DB , my DB and Table looks like below…

WebSQL in Chrome Browser - DB and Tables

WebSQL in Chrome Browser – DB and Tables

We can also write SQL Queries like SQL Server Management Studio…

Just follow the Image below…

WebSQL in Chrome Browser - SQL Queries

WebSQL in Chrome Browser – SQL Queries

Its nice and cool , right ?

I will write another Article on IndexedDB very soon .
Keep an eye on my Blog Site , Share/Subscribe…

Thanks and regards

Standard