Alternatives to build todays Web Applications and different hosting choices

Dears,
While we are so confused with What to follow for the optimal Architecture and what tool to use and what is the best integration to build a stable and responsive WEB application. and also where to host for stable accessibility. i have defined three alternatives for building a Web APP. with optimal hosting for each.

Note that you can comment with more alternatives and i promise i will update the post directly.

Alternative 1: For Mission Critical Apps

DataBase : SQL Server or ORACLE

Server Side APIs :

  1. Entity Framework  : For Database object representation and Database Operation management
  2. ASP.net WEB APIs : For Fast and Simple REST APIs.
  3. WCF Services : for Dual Binding and Custom Security.

Data Binding and Manipulations :

  1. AngularJS 1.x : If your UI is Template Oriented and no UI Dynamic creation expected.
  2. ReactJS : If you you seek a Script First Data Driven APP, and if your UI is highly Dynamic upon the Data with different Conditions.
  3. ReactJS : If you want to create a WorkFlow.
  4. D3JS : For Fancy SVG Charts, Comparisons, Interactive and Organized and Dynamic Data Representations.
  5. ThreeJS : If you want to add 3D or Animation.

Front End Business logic :

  1. JavaScript : If you and your team have no problems with Heavy Scripting and not fully customized Object Oriented code.
  2. ECMAScript : If you are like the above but need to write less code and more structured and readable, and want to keep the Un-Typed Scripting features (variables are not typed, all vars).
  3. Type Script : for sake of minimal code, as much like C# and Java, Fully Object Oriented with interfaces, for building modules with access modifiers (public, private , ..etc), and for Type and Build  Error Check in Compile Time.
  4. CoffeScript : Just like the ECMA but wants to witie RUBY or PYTHON like Code with space separation for code block.

Host : Windows Server

Alternative 2: For Non-Mission Critical and Huge Data Manipulation

DataBase : MongoDB, Cassandra (I recommend Mongo)

Server Side APIs :

  1. NodeJS : For Database object representation and Database Operation management.
  2. ASP.net WEB APIs : REST APIs
  3. WCF  Services : for Dual Binding and Custom Security.

Data Binding and Manipulations :

  1. AngularJS 1.x : If your UI is Template Oriented and no UI Dynamic creation expected.
  2. ReactJS : If you you seek a Script First Data Driven APP, and if your UI is highly Dynamic upon the Data with different Conditions.
  3. ReactJS : If you want to create a WorkFlow.
  4. D3JS : For Fancy SVG Charts, Comparisons, Interactive and Organized and Dynamic Data Representations.
  5. ThreeJS : If you want to add 3D or Animation.

Front End business logic :

  1. JavaScript : If you and your team have no problems with Heavy Scripting and not fully customized Object Oriented code.
  2. ECMAScript : If you are like the above but need to write less code and more structured and readable, and want to keep the Un-Typed Scripting features (variables are not typed, all vars).
  3. Type Script : for sake of minimal code, as much like C# and Java, Fully Object Oriented with interfaces, for building modules with access modifiers (public, private , ..etc), and for Type and Build  Error Check in Compile Time.
  4. CoffeScript : Just like the ECMA but wants to witie RUBY or PYTHON like Code with space separation for code block.

Host :

  1. DataBase Server : Windows Server or Linux (I recommend)
  2. Application Server : IIS over Windows in case of WCF or WEB APIs , Linux for the NodeJS.

Alternative 3: For Cloud Ready Application

DataBase :

  1. Create a Cloud VM [Windows or Linux – Linux is better for low prices](From AZURE or Google Compute pr AMAZON) and install mongoDB.  (NB. MongoDB required High Memory Machine so focus on the RAM).
  2. Use AZURe mongoDB service or Google Mongo Service, that is more scaleable and will take you out of the headache of Database Server management and Configuration, but much more costly compared with the last option.
  3. Store Your Data Over Cloud Provider Storage Service (I recommend AZURE Table Storage for Tabular Data and AZURE Blob Storage for File Storage) NB. Revise this post before using The Table Storage.

Server Side APIs :

  1. NodeJS : For Database object representation and Database Operation management.
  2. ASP.net WEB APIs : REST APIs
  3. WCF  Services : for Dual Binding and Custom Security.

Data Binding and Manipulations :

  1. AngularJS 1.x : If your UI is Template Oriented and no UI Dynamic creation expected.
  2. ReactJS : If you you seek a Script First Data Driven APP, and if your UI is highly Dynamic upon the Data with different Conditions.
  3. ReactJS : If you want to create a WorkFlow.
  4. D3JS : For Fancy SVG Charts, Comparisons, Interactive and Organized and Dynamic Data Representations.
  5. ThreeJS : If you want to add 3D or Animation.

Front End business logic :

  1. JavaScript : If you and your team have no problems with Heavy Scripting and not fully customized Object Oriented code.
  2. ECMAScript : If you are like the above but need to write less code and more structured and readable, and want to keep the Un-Typed Scripting features (variables are not typed, all vars).
  3. Type Script : for sake of minimal code, as much like C# and Java, Fully Object Oriented with interfaces, for building modules with access modifiers (public, private , ..etc), and for Type and Build  Error Check in Compile Time.
  4. CoffeScript : Just like the ECMA but wants to witie RUBY or PYTHON like Code with space separation for code block.

Host :

  1. DataBase Server : as illustrated in the DataBase part
  2. Application Server :

If you use WEB APIs or WCF : Use AZURE APP Service for easier and faster updates or indeed Windows VM.

If you use NodeJS you can host in Linux VM or Windows VM.

General Notes From My Experience:

  1. NodeJS is implemented over Chrome V8 Engine (compiler), so it supposed to be faster that the WEB APIs and indeed the WCF.
  2. WCF Service is best choice when it comes to Dual HTTP Binding with Custom Security Configurations.
  3. AZURE Cloud is easier than Google compute when it comes to Scaling Up/Down.
  4. Google Compute Engine is much more Lower in price than AZURE even for Windows Machines.
  5. Google Compute Engine team might suspend your VM for days if they felt that you are misaligned with the Terms Of Use , and they might re open when they discover that they were wrong !!
  6.  Angular2 will introduce the Dynamic Component like the ReactJS with much more better performance than Angular 1.x.

Useful Links Regarding the Above:

Click For more Info about how to install and Configure MongoDB in Windows.

Click For more Info about how to install and Configure MongoDB in Linux.

Click For more Info about how to create a REST API using node JS over MongoDB.

Click For Getting Started with ASP.net WEB APIs

Click For Angular Official website

Click for ReactJS Official website

Click for D3Js Official website

Click for ECMAScript Official website

Click for TypeScript Official website

Click for ThreeJS Official website

Advertisements

Step X Step : Start with NodeJS to create REST API with CRUD operations over MongoDB

Dears,

As one of the long list of Posts targeting the  Mean Stack, as i’ve already published a couple of posts targeting MongoDB for MS Windows Users and Linux Users , we will illustrate in this post how to build a REST API using NodeJS over MongoDB and a simple Client to Use the API.

Assumption

I will assume that you already know  what is NodeJS and also will assume that you installed MongoDB in your Local Machine (for detailed step x step reference , get back to my post here).

Note that its all JavaScript and nothing more, so you must be scripting lover to stand until the end of the post.

Step 1 : Installing the NodeJS Prerequisites

NodeJS is a Server Side Artifact, it means it is not Client Exposed JavaScript, so you have to know that while we moving through the Post steps, its not the real case to have the NodeJS and the Client project in the same device.

Now, lets start.

1 – Create a Folder anywhere in your machine, for my demo will be on the Desktop, Name it Node Scripts.

2 – Open Node.js command prompt and navigate to the created folder

cd C:\Users\sselim\Desktop\Node Scripts

3 – Install the Express Module in your Project

npm install express

Note that Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications and as we are going to use NodeJS to expose Crud Functions as a REST HTTP APIs, so we have to install it.

3 – Install the MongoDB Module in your Project

npm install mongodb

This is Mandatory indeed to let the NodeJS Express Compiler to understand the MongoDB Scripting we are going to build in farther step.

4 – Install the Body Parser Module in your Project

npm install body-parser

Like any CRUD Operations (GET, POST, PUT, DELETE), to let the Post Method to read from the request body and parse the contents and start using, you have to install the body-parser module first.

5 – Install the Multer Module in your Project

npm install multer

Multer is a NodeJS middleware for handling multipart/form-data

by reaching this step you installed all the prerequisites required for compiling and running your code and you have to find a folder with name node_modules created inside your project root folder (Node Scripts in my case) and inside this folder you will find 4 folders created (one for each module installed).

Step 2: Scripting the REST API

we are going to build a REST Function using NodeJS Syntax and compile using the Express and access using simple HTTP request.

I will work on a Film model with three Props. (Name, Language, Category), so we will start building the Controller JS that holds the CRUD methods for this Model.

1 – Inside the last created folder (Node Scripts) create a JS file and name it Film.js.

2 – In the created blank JS file we will start including the installed modules references

var express = require('express');
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer();
var MongoClient = require('mongodb').MongoClient, format = require('util').format;

var app = express();
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true }));

3 – Add a line for MongoDB Connection String

var ConnectionString = 'mongodb://127.0.0.1:27017/';

4 – Create the Server object to listen to requests to the Port of interest (i will use 8080 for my Demo)

var server = app.listen(8080, function () {
    console.log("FILMS API running at http://127.0.0.1:8080");
});

Note that as i mentioned before, the IP is 127.0.0.1 (localhost) and you should replace with the production IP when it comes to real work.

Step 3: CRUDing

We will create four function for covering the (Get All, Get By Key, Insert, Delete and Update) over the Film model.

1 – GetAll (Get Function read no parameters or even from the body)

app.get('/GetAll', function (req, res) {
    MongoClient.connect(ConnectionString + 'mongonodetest', function (err, db) {
        if (err) throw err;
        var collection = db.collection('Films')
                           .find({})
                           .toArray(function (err, docs) {
                               if (docs)
                                   res.json(docs);
                               else
                                   res.json(new Array());
                           });
    });
});

2 – GetByKey (Get Function Reads the Film Name parameter ‘Key’ from the request URL Parameters )

app.get('/GetByKey/:key', function (req, res) {
    MongoClient.connect(ConnectionString + 'mongonodetest', function (err, db) {
        if (err) throw err;
        var collection = db.collection('Films')
                           .find({ "Name": req.params.key })
                           .toArray(function (err, docs) {
                               if (docs)
                                   res.json(docs);
                               else
                                   res.json(new Array());
                           });
    });
});

3 – UpdateByKey (Post Function Reads the Film Name parameter ‘Key’ from the request URL Parameters and parse the new Film object from the the quest body)

app.put('/UpdateByKey/:key', function (req, res) {
    MongoClient.connect(ConnectionString + 'mongonodetest', function (err, db) {
        if (err) throw err;
        var collection = db.collection('Films')
                           .replaceOne({ "Name": req.params.key }, req.body
                           , function (err, docs) {
                               if (docs)
                                   res.json(docs);
                               else
                                   res.json(new Array());
                           });
    });
});

4 – InsertByKey (Post Function  parse the Film object from the the quest body)

app.post('/Insert', function (req, res) {
    MongoClient.connect(ConnectionString + 'mongonodetest', function (err, db) {
        if (err) throw err;
        var collection = db.collection('Films')
                           .insertMany(req.body
                           , function (err, docs) {
                               res.json('Done');
                           });
    });
});

5 – DeleteByKey (Get Function Reads the Film Name parameter ‘Key’ from the request URL)

app.get('/DeleteByKey/:key', function (req, res) {
    MongoClient.connect(ConnectionString + 'mongonodetest', function (err, db) {
        if (err) throw err;
        var collection = db.collection('Films')
                           .deleteMany({ "Name": req.params.key },
                            function (err, docs) {
                                res.json('Done');
                            });
    });
});

Now your REST API is ready, one last step is to run the API to be available for HTTP requests, or to make the server object we created above specific socket (IP:Port) to start listening to requests.

Do this by writing the command inside the Node.js command prompt

node Films.js

a line display the following should come up

FILMS API running at http://127.0.0.1:8080

Step 4 : Creating the Client

Now, lets build a very simple AJAX calls to request the NodeJS APIS at the Predefined Socket (127.0.0.1:8080), here and to me real MeanStacker, you should use AngularJS to do this step, but for sake of generalization and focus on the concept of (Client/Server) communication, i will use the most regular AJAX calls.

1 – Request Insert Film

Create the Followoing Class inside the Client JS file as a Client representation for the Film Model.

function Film(_Name, _Language, _Category) {
    this.Name = _Name;
    this.Language = _Language;
    this.Category = _Category;
}

Then Create a Function to Request the Remote NodeJS REST Inset function

function InsertFilms() {
    var Films = new Array();
    Films.push(new Film('Home Alone','English','Comedy'));
    Films.push(new Film('Night For Counting Years','Arabic','Drama'));
    $.ajax({
        type: "POST",
        data: JSON.stringify(Films),
        contentType: "application/json; charset=utf-8",
        url: "http://127.0.0.1:8080/Insert",
        dataType: "json",
        processdata: true,
        success: function (data) {
            alert(data);
        },
        fail: function (error) {
            alert(errors);
        }
    });
}

2 – Get ALL Films

function GetAllFilms() {
    $.ajax({
        type: "GET",
        data: '{}',
        contentType: "application/json; charset=utf-8",
        url: "http://127.0.0.1:8080/GetAll",
        dataType: "json",
        processdata: true,
        success: function (data) {
            alert(data);
        },
        fail: function (error) {
            alert(errors);
        }
    });
}

3 – Gey By Film Name

function GetFilmByName(filmName) {
    $.ajax({
        type: "GET",
        data: '{}',
        contentType: "application/json; charset=utf-8",
        url: "http://127.0.0.1:8080/GetByKey/"+filmName,
        dataType: "json",
        processdata: true,
        success: function (data) {
            alert(data);
        },
        fail: function (error) {
            alert(errors);
        }
    });
}

4 – Update Film

function UpdateFilm(filmName, filmObject) {
   $.ajax({
        type: "PUT",
        data: JSON.stringify(filmObject),
        contentType: "application/json; charset=utf-8",
        url: "http://127.0.0.1:8080/UpdateByKey/"+filmName,
        dataType: "json",
        processdata: true,
        success: function (data) {
            alert(data);
        },
        fail: function (error) {
            alert(errors);
        }
    });
}

5 – Delete Film By Name

function DeleteFilmByName(filmName) {
    $.ajax({
        type: "GET",
        data: '{}',
        contentType: "application/json; charset=utf-8",
        url: "http://127.0.0.1:8080/DeleteByKey/"+filmName,
        dataType: "json",
        processdata: true,
        success: function (data) {
            alert(data);
        },
        fail: function (error) {
            alert(errors);
        }
    });
}

and we done, you can create an html page and test your code as you like , but usually don’t forget to run the Controller JS file before you start requesting it.

Step X Step : Install and Configure MongoDB in Ubuntu.

Hi There,

Few months ago i have posted a Step X Step reference to Install and configure MongoDB on Windows Operation System. now i am doing the same but to Install and Configure MongoDB on Linux Server (am Using UBUNTU 14.04 LT version).

I. Lets Be Root Users

sudo -s

II. Prepare your System with Latest Updates (do this before any installation of any kind)

sudo apt-get update
sudo apt-get upgrade

note that apt-get update (Used to re-synchronize the package index files from their sources) and apt-upgrade (Used to install the newest versions of all packages currently installed on the system from the sources enumerated in/etc/apt/sources.list) [Reference Here for more details]

III. Import the public key used by the package management system.[Reference For more details]

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10

IIII. Create a list file for MongoDB. [Reference For more details]

echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list

V. Re-synchronize the package index files

sudo apt-get update

VI. Install the latest stable version of MongoDB

sudo apt-get install mongodb-org

At this point we done and we have mongo Installed at the server configured to port 27017 and accept only requests from local host.

Now Lets discover the mongod Config file and see how we can change it to enable remote access to MongoDB.

First : Issue the following comand on the Terminal as Root (sudo -s makes you root)

vim /etc/mongod.conf

Note that “vim” is a popular text editor based off of the venerable vi editor, if you don’t have it, and mostly you will have it , install it with the command

sudo apt-get install vim

Second : the vim will open the mongod.conf file inside your terminal, here we have two lines to Focus.

Line 1: #Port = 27017

This is the default port, and by default commented by ‘#’ remove the ‘#’ and change it and you will change the port that mongo listen to.

Line 2: bind_ip = 127.0.0.1

This line means that the mongodb engine just accept requests from localhost, comment the line with ‘#’ and you will make mongo accept requests from any IPs, or write the IP of interests, note that you can add more than one IP with ‘,’ separations.

To make any of the above changes, use the arrows in your keyboard up and down to the line of ineterst and use the ‘x’ to delete character and type what ever you want.

After that Typr [ESC] then [:w] then [:q]

:w  (will save the changes)

:q (will exit vim and get back to the treminal)

Finally : Lets Open the port 27017 to Accept requests, do this by the following.

Note: If you are using AZURE VM or Google Compute engine, the following steps are not necessary as you just need to open the Port in the FireWall Rule or EndPoints Manager.

For Any IPs:

iptables -A OUTPUT -p tcp --dport 27017 -j ACCEPT
iptables -A INPUT -p tcp --dport 27017 -j ACCEPT

For Specific IP:

iptables -A INPUT -s <ip-address> -p tcp --destination-port 27017 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -d <ip-address> -p tcp --source-port 27017 -m state --state ESTABLISHED -j ACCEPT

and the last thing if you have the UFW enabled , you will need to open the port in the firewall

sudo ufw akllow 27017
sudo ufw akllow 27017/tcp

Quick start to MongoDB for windows users

Hi There ..

If you are seeking the simple and direct to the point steps to install and configure MongoDB in your Windows Operating System of interest .. i advice to read this post to the end.
Farther in this post we covering these points.

1. Download the Package of interest from MongoDB Official Website and Install it.
2. Configuring MongoDB.
3. Create Windows Service to Run MongoDB service with startup.
4. Securing MongoDB with Admin User.
5. Enable Remote Connection to MongoDB Server.
6. Listing some MongoDB Management Studios.

mongoversions

1. Go to MongoDB page and download the proper version for you, they have (Windows Server 2008 R2 + and Windows 64, 32-bit) so this should cover all your needs if you are running Server or Client Windows.

Install MongoDB and go through the Wizard, its very straight forward and asking for nothing, so just NEXT to the end.

By finishing to here you can check you “Program mongofoldersfiles” folder and locate the MongoDB folder. open the folder you should find the contents as shown in the image.

2. Now we will start configuring MongoDB;

2.0. Run the Command Prompt as administrator.

2.1. Copy and Paste the following Command to Create DB folder to save your data.

mkdir c:\data\db
//this will create DataBase folder on the path c:\\data, and indeed you can change it

2.2. Create Log Folder

mkdir c:\data\log
//this will create Logfolder on the path c:\\data, and indeed you can change it

2.3. Copy the Created two folders Paths to the configurations file, this will be used farther in the windows service. To do this run the following two commands.

echo logpath=c:\data\log\mongod.log> "C:\Program Files \MongoDB 2.6 Standard\mongod.cfg"
echo dbpath=c:\data\db>> "C:\Program Files\MongoDB 2.6 Standard\mongod.cfg"
//C:\Program Files\MongoDB 2.6 Standard is the installation path, it could be different if you installed 32-bit version as you will find it inside Program Files (x86)

2.4. Create MongoDB windows service

sc.exe create MongoDB binPath= "\"C:\Program Files\MongoDB 2.6 Standard\bin\mongod.exe\" --service --config=\"C:\Program Files\MongoDB 2.6 Standard\mongod.cfg\"" DisplayName= "MongoDB 2.6 Standard" start= "auto"

//don’t forget to change the path(s) to match you installation

2.5. Start the Service

net start mongodb

Now we successfully configured MongoDB and you can test it by the following;

3. Test the configurations

e.g. C:\Program Files\MongoDB 2.6 Standard 

3.1. open bin folder and locate the mongo.exe, run it write “show dbs“, list of DBs should be populated now.

NB. By Default you should find admin and local Databases exist. if you didn’t find any of them , it doesn’t mean any thing. just move on.

4. This step is Optional but necessary if you are about to introduce your database to the production and want to secure it with Admin UserName and Password.

4.1. Run mongo.exe and paste the following commands;

use admin

//this will apply all the following commands to the admin DB

db.createUser({
user: "adminusername",
pwd: "adminpassword",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
})

//as you see, we make the “role” as userAdminAnyDatabase to the DB admin. and the Admin on “admin” DB is admin on any other DB.

Note here that this Command applied on on the Exist DataBases , and any Database you create after that won’t follow the same Command, so you have to run again to be applied on the newly created databases.

4.2. Now try to access the MongoDB from the mongo.exe by the following command;

mongo --host localhost --port 27017 -u adminusername-p adminpassword--authenticationDatabase admin

5. By default mongo installed and configured to Port 27017, if you want to expose your MongoDB to external connection, you can easily do this by enable inbound and outbound rules in the Windows Firewall to to the 27017 Port.

Note here that you have to take care while doing this as you have to enable the port for specific IP, Domain or more farther through the FireWall Options.

and to close this point, you can change the Port Number, the Accepted IPs to connect to mongo and more farther options in the Mongo Configuration file.Read more about this in the Official mongo documentations.

6. amd Finally , this step is optional but nice, you might need to install a MMS or management studio to admin or view you MongoDB artifacts (DataBases, Collections, Data …etc) and also for farther operations like (Delete, Import, Export ..etc), there are many MMSs for MongoDB and these two are example (mongovue , litixsoft).