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

Advertisements
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, 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
AngularJS, ASP.Net MVC, jQuery AJAX, MVC WebAPI

Delete Functionality : REST API with AngularJS $resource and jQuery-Ajax

For every Web Application , an important feature is Delete Functionality . We can not think a single app without it . But we already know how to develop DELETE Functionality inside a Web App . Then why is this article for?

Well , that’s true . But now , we will see how we can develop DELETE Functionality with $resource of AngularJS and/or also with jQuery . and for both cases , we have a REST URL of the server which is doing the real back-end thing .

Lets jump…

First lets see the Server code of REST API Delete Functionality . Here I have used .Net WebAPI . And the Method looks like below :::

public HttpResponseMessage Delete(int id)
        {
            //Delete Related Logics + Data Access calling etc
            return Request.CreateResponse(HttpStatusCode.OK);
        }

Now lets see the client side function of DELETE which is using AngularJS $resource .

$scope.delete = function() {
        $resource('api/Ticket/:id').delete({ id: $scope.ticket.Id }, function (data) {
            alert('Succeeded');
        });
    };

We can do the same thing by jQuery also , if we do not use AngularJS . But after learning AngularJS , you will never use jQuery 🙂 For jQuery lovers , we can do this like below with jQuery Ajax:::

$scope.delete = function () {
        $.ajax({
            url: 'api/Ticket/' + $scope.ticket.Id,
            type: 'DELETE',
            success: function (data) {
                alert('Succeeded');
            },
            error: function (x, y, z) {
                alert('Failed');
            }
        });
    };

Well , Thanks . Hope , you liked it .If you do , please share / subscribe …

Cheers 🙂

Standard
AngularJS, HTML5, JavaScript

Using HTML5 LocalStorage with AngularJS

Today , I will talk about LocalStorage Support of HTML5.

We can store named key/value pairs locally, within the client web browser. Like cookies, this data persists even after you navigate away from the web site, close your browser tab, exit your browser, or what have you. Unlike cookies, this data is never transmitted to the remote web server (unless you go out of your way to send it manually). Unlike all previous attempts at providing persistent local storage, it is implemented natively in web browsers, so it is available even when third-party browser plugins are not.

HTML5 STORAGE SUPPORT
IE FIREFOX SAFARI CHROME OPERA IPHONE ANDROID
8.0+ 3.5+ 4.0+ 4.0+ 10.5+ 2.0+ 2.0+

Based on different browsers , we can get 2 MB to 5MB (even more) space in LocalStorage . To get more idea on space check out this link …

BY the below code , we can check our browser supports LocalStorage or Not !

function supports_html5_storage() {
    try {
        return 'localStorage' in window && window['localStorage'] !== null;
    } catch (e) {
        return false;
    }
}

Also we can use Modernizr to check this .

if (Modernizr.localstorage) {
    // window.localStorage is available!
} else {
    // no native support for HTML5 storage :(
}

Lets develop a simple LocalStorage Cache framework with AngularJS .

For this , am gonna create an AngularJS Factory Service to communicate with the HTML5 LocalStorage .

'use strict';

valApp.factory('storageService', function ($rootScope) {

    return {
        
        get: function (key) {
           return localStorage.getItem(key);
        },

        save: function (key, data) {
           localStorage.setItem(key, JSON.stringify(data));
        },

        remove: function (key) {
            localStorage.removeItem(key);
        },
        
        clearAll : function () {
            localStorage.clear();
        }
    };
});

localStorage keyword in the upper is the core API which is responsible for providing LocalStorage facility .

I have not used this storageService directly in the client .I am gonna use another Mid Layer Factory which will communicate with storageService and client code will call this Mid Layer Factory named cacheService . This is like below :::

'use strict';

valApp.factory('cacheService', function ($http, storageService) {
    
    return {
        
        getData: function (key) {
            return storageService.get(key);
        },

        setData: function (key,data) {
            storageService.save(key, data);
        },
        
        removeData: function (key) {
            storageService.remove(key);
        }
    };
});

You can see , I have injected storageService to cacheService .

Now from my AJs Controller , I will call cacheService’s Function to serve my purpose .

Now below is the example , how you can use this Cache Framework …

In My Controller , I’ve simply injected cacheService and can use all the features of it .

var city = [
                  { Id: 1, Name: 'Dhaka' },
                  { Id: 2, Name: 'Ctg' }
    ];
    cacheService.setData('city', city);

I have used the Mid Layer , if we need any new logic later, we can easily add those to the Mid Layer .

Its easy and awesome , right ?

Cheers 🙂

Standard