Friday, February 3, 2017

Express With MongoDB - Quick start

Let's access MongoDB from Nodejs using Express. 

What is Express? 
As per Express site, it's a minimal and flexible Node.js web application framework that provides a robust set of features for the web and mobile applications.

Features
·         Robust routing
·         Focus on high performance
·         Super-high test coverage
·         HTTP helpers (redirection, caching, etc)
·         View system supporting 14+ template engines
·         Content negotiation
·         Executable for generating applications quickly

Great.Lets start. (Assumed you have Nodejs and MongoDB installed, if not ,check Nodejs & MongoDb)

Create a folder and run following command on your terminal-

 > npm init

It will ask you few questions (Like- Name for the project, author, version). For now, you can keep all the default values. This will give you your package.json inside the same folder.

Greate execute this now-

> npm install --save express
mongoose morgan body-parser

So here, we actually installed Express along with mongoose which is a Node.js library that provides MongoDB object mapping similar to ORM with a familiar interface within Node.js and Morgan which is basically used for logging request details. And body-parser parses incoming request bodies in a middleware before your handlers, available under the req.body property.

Now you should see a folder named node_modules inside your current folder. Inside node_modules all your installed node packages reside. We are now ready to go further.

Let's create a file and name it server.js. Put the following code and save it.

var express = require('express'); // load express module in your project

var morgan = require('morgan'); // load morgan module 

var mongoose = require('mongoose'); //load mongoose module 

var bodyParser = require('body-parser'); // load body-parser module 

var app = express(); //init express
var port = process.env.PORT || 6064; //allocate the port for your server
app.use(express.static('./public')); // set folder for public items , such as - image , css, html, client side js
app.use(morgan('dev')); // init morgan for logging request details
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

mongoose.connect('mongodb://localhost/mongodbtest'); // mongodb connection

routesetup(app);// set your route details with path and its handlers 
app.listen(port);// start your server
console.log("App listening on port " + port); 


function routesetup(app) { // function for route setup
   app.use( function (req, res, next) {  // will be executed for all request
        console.log(req.url);
        next();
    });
    app.use( function (err, req, res, next) { // will be executed for all error
        console.log(err);
        next();
    });    
// REST API to access from client side js--> 
    app.get('/api/todos', function (req, res) { // get method route
       todo.find(function (err, todos) { // used mongoose model to get data
            if (err) {
                res.send(err);
            }

            res.json(todos);
        });
    });
app.post('/api/todos', function (req, res) { //post method route
 var td = new todo({
 val: req.body.val
        });

        td.save(function (err, td) { // use mongoose model to dave data
            if (err) {
                return res.status(500).json({
                    message: 'Error when creating todo',
                    error: err
                });
            }
            return res.status(201).json(todo);
        });
});
    app.get('*', function (req, res) { // get method for html
        //throw new Error('err');
        res.sendFile(__dirname + '/public/index.html');
    });
}

var todo = mongoose.model('Todo', { //mongoose model
    val: {
        type: String,
        default: ''
    }
});

Now create a folder public and inside it create a file index.html  and add following -

<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script>
    $(document).ready(function () {
        $("#btn").click(function () {
            $.post("/api/todos",
                {
                    val: $("#txttask").val()
                },
                function (data, status) {
                    console.log("Data: " + data + "\nStatus: " + status);
                });

            $("#txttask").val('');
            getData();
        });
        function getData() {
            $.get("/api/todos", function (data, status) {
                var listVal = "";
                $.each(data, function (index, val) {
                    listVal += val.val + "<br>";
                })
                $("#listtask").html(listVal);
            });
        }
        getData();
    });
</script>
</head>

<body>
    <div>
        <b>Express Running</b></div>
    <div>
        <label> Task:</label><input type="text" id="txttask" /><button id="btn">Save</button>
    </div>
    <div>
        <b>Task List</b>
    </div>
    <div id="listtask"></div>
</body>

</html>

Save both the files.

Note: Please read all the inline comments carefully for better understanding.

Greate . Now we are ready to run our first Express application with MongoDB.

Run you mongoDB, before going further.(go to your mongo installation folder and then ./bin folder using a new terminal window)

> mongod --directoryperdb --dbpath <folder path>


To Run the application, execute following in your terminal-

> node server.js

Now Try to open - http://localhost:6064/

If you have done it properly, you should see your HTML page with heading Express Running. Using the api created in server.js you can save and see the saved list of items in the page.

That's it.

Feel free to ask if you have any queries. 



Nodejs Create Server


We know what nodejs is, and up to now, we are able to run basic node server. If you have not gone through the previous tutorial please check it here.

Cool, let’s go ahead. Now we will create a more sophisticated application. So what we have up to now-

  var http = require('http');
    
    function onRequest(request, response){
        console.log('request '+ request.url);
        response.writeHead(200,{"Context-Type": "text/plain"});
        response.write('Server running');
        response.end()
       
    }
    http.createServer(onRequest).listen(9000);
    console.log('Server Running');

Add and modify few line of code in it-
  var http = require('http');
 function send404(response){
          response.writeHead(404,{"Context-Type": "text/plain"});
          response.write('Error 404');
          response.end();
    }
    function onRequest(request, response){
        console.log('request '+ request.url);
      if(request.method == 'GET' && request.url == '/'){
        response.writeHead(200,{"Context-Type": "text/plain"});
        response.write('Server running');
        response.end();
       }
       else{
         send404(response);
       }
    }
    http.createServer(onRequest).listen(9000);

    console.log('Server Running');

Save the file as server.js and run it (>node server.js). If you can see “Server Running” message, then we are good to go. Open http://localhost:9000 in your browser. You should see “Server Running” in the browser also.
Now change the URL to http://localhost:9000/somethingelse. You will get a message “Error 404”.

Now let me explain what exactly happened. When we request http://localhos:9000, it comes to the server , and as we setup onRequest as a handler function, it starts executing. Now depending on the condition check on request type & properties, it creates a response and sends it back to the browser. For error handling, we used send404 function. Now same way we can create multiple request and error handler.

Example –

    function onRequest(request, response){
      if(request.method == 'GET' && request.url == '/'){
        response.writeHead(200,{"Context-Type": "text/plain"});
        response.write('Server running');
        response.end();
       }
      else if(request.method == 'GET' && request.url == '/somethingelse'){
        response.writeHead(200,{"Context-Type": "text/plain"});
        response.write('Something else from server');
        response.end();
       }
       else{
         send404(response);
       }
    }

Replace your existing onRequest with just above onRequest and again hit http://localhost:9000/somethingelse .  You should see “Something else from server”.

Return physical files –
Now instead of sending string response, let’s send files. To do that we need to add below line at the top of the server.js file–

    var fs = require('fs');

Now just update your onRequest function.

function onRequest(request, response){
        if(request.method == 'GET' && request.url == '/'){
            response.writeHead(200,{"Context-Type": "text/html"});
            fs.createReadStream('./index.html').pipe(response);       
        }
        else if(request.method == 'GET' && request.url == '/script.js'){
            response.writeHead(200,{"Context-Type": "text/plain"});
            fs.createReadStream('./script.js').pipe(response);       
        }
        else{
            send404(response);
        }
    }

[Note : Make sure you have index.html and script.js file in the folder]

Lets see what exactly we did. First we imported fs module (node module) for accessing files. Now in onRequest function we used that fs module to read an existing file and send it back as response.

Example -
index.html- 
<html>
<head><script src="./script.js"/></head>
<body>test</body>
</html>
script.js -
(function(){
console.log('test')
})();

In browser and in console you should see "test".


That’s it for now.

Saturday, January 21, 2017

Nodejs Intro

Nodejs introduction




Nodejs is having lots of inbuilt modules/packages and also custom packages (npm manages packages). 

Fine, Now how to use those packages? 

Simple - just use require('<package name>') (commonjs approch).

Example - var http = require('http');

(Here we can see http module is imported. You can import multiple modules as required.)

Note: Any javascript code is valid under nodejs, as it uses V8.

Start the server-side coding using Javascript-

    var http = require('http');
    
    function onRequest(request, response){
        console.log('request '+ request.url);
        response.writeHead(200,{"Context-Type": "text/plain"});
        response.write('Server running');
        response.end()
       
    }
    http.createServer(onRequest).listen(9000);
    console.log('Server Running');

Now save it, say server.js.

To run this application run following in console - 

> node server.js

Server Running // this line will be printed in console.

Cool, it's running. 

Now if you open localhost:9000, you will see "Server running" text in the page.

Congratulation it's your first nodejs application. 

Friday, January 20, 2017

NOSQL -MongoDB

Introduction





Setup Mongo


Download & Install Mongo from- MongoDB site

Now you need a folder to store the data. So, Create one and Setup mongo.

Run MongoDB command in console-

mongod --directoryperdb --dbpath <folder path> --logpath <file path> --logappend --rest 

Mongo commands


Great, you are ready to do DB functionalities. For this, you have to run following command in the console. 

mongo

That's it. It will open a shell for executing mongo commands.

Show list of DBs-
>show DBS

Create/Use the DB-
>use local

See selected DB-
>db

Create user for db-
>db.createUser({user:"test",pwd:"1234",roles: ["readWrite","dbAdmin"]});

Create a collection in DB-
>db.createCollection('employee');

Show all collections in DB-
>show collections

Insert document in a collection-
>db.employee.insert({first_name:"sudhir", last_name:"ghosh"});

Fetch the documents-
>db.employee.find();

Insert multiple documents-
>db.employee.insert([{first_name:"sakti", last_name:"ghosh"},{first_name:"subha", last_name:"ghosh", gender:"M"}]);

Get Collection-
>db.employee.find().pretty();

Update commands -
>db.employee.update({first_name:"sakti"},{first_name:"sakti", last_name:"ghosh",gender:"M"});

>db.employee.update({first_name:"sudhir",{$set:{age: 40}});

>db.employee.update({first_name:"sudhir",{$inc:{age:5}});

>db.employee.update({first_name:"sudhir",{$unset:{age}});

>db.employee.update({first_name:"rnga"},{first_name:"ranga", last_name:"ghosh"},{upsert:true});

>db.employee.update({first_name:"rnga"},{$rename:{"gender":"m"}});

Remove commands -
>db.employee.remove({first_name:"rnga"});

>db.employee.remove({first_name:"rnga"}, {justOne:true});

Find Commands -
>db.employee.find({first_name:"sudhir"});

>db.employee.find({$or:[{first_name:"sakti"},{first_name:"sudhir"}]});

>db.employee.find({age:{$lt:40}}); //$gt/$gte/$lte

>db.employee.find({"address.city":"kol"});//json path

>db.employee.find().sort({last_name:1});//asc/desc (-1)

>db.employee.find().count();

>db.employee.find().limit(4);

>db.employee.find({deot:{$in:['software','testing']}});

>db.employee.find().forEach(function(doc){
print('name:'+ oc.first_name)});



Further study - https://docs.mongodb.com/manual/

Friday, March 4, 2016

ES6 and Babeljs

Introduction

In the implementation of control tool kit we will be using ES6 or ECMAScript6. As the code developed using ES6 is not compilable in browser, we need babeljs to compile it and run it in browser. The development stack discussed below.

What is ES6?

ES6 is ECMAScript 6. It is a scripting language specification created by a committee called TC39. Currently the JavaScript we use for development is basically following ES5. All the modern browsers has support for it with different JavaScript engines, like - V8 (in google chrome). For ES6, the browsers dose not has full support. So if we do code in ES6, browser compilers will through compile time (Syntax) error, as this version of ECMAScript has many new syntactical and implementation level changes, which we will discuss shortly. So, to overcome this and to use new features of ES6, we need some compiler which will take ES6 code as input and give us something browser compliable.

What is Transcompiler or Transpiler?

Transpiler is a tool or engine to compile one source code to another source code. To use ES6 now , we need to use some kind of transpiler to convert ES6 to something browser compliable(e.g ES5). There are several transpiler is market now, which facilitates us to use ES6 now . Babeljs is one such transpiler, which we will be focusing now.

What is Babel?

Babeljs is a transpiler to convert ES6 code to ES5. Babel supports pre and run time compilation. Pre compilation is for compiling our ES6 code to ES5 in the time of project build. For production environment pre compilation is preferable. Runtime compilation is straight forward process to compile your ES6 code to ES5 in the browser itself, which is time consuming for sure and not preferable for practical implementations.

How to convert ES6 to ES5-

As discussed above there are two ways to do it. Lets discuss preferable way first-

Per- compilation of ES6 code using Babeljs.

There is a npm module called babel, which we need to install in our app.

npm install babel

Then it's pretty straight forward to compile the ES6 code to current javasctipt code.

babel script.js

Babeljs also has gulp support. We can use gulp-babel to do the same using gulp build process.

First install it-

npm install --save-dev gulp-babel

In gulp file-

var gulp = require('gulp'); var babel = require('gulp-babel'); gulp.task('default', function () { return gulp.src('src/app.js') .pipe(babel()) .pipe(gulp.dest('dist')); });

It will compile app.js ES6 code files to vanilla JavaScript and put it in dist folder.

Now let's see, how the runtime compilation works. We need to add reference of browser.js in our web page from babel-code folder after npm installation of babel. This will basically convert all the scripts with type text/babel from ES6 to JavaScript (ES5).

<script src="node_modules/babel-core/browser.js"></script> <script type="text/babel"> class Test { test() { return "test"; } } var test = new Test; test.test(); </script>

But as discussed previously, it will make the application perform slowly.
That's all we need to know about babeljs for now.

ES6 Feature

ES6 gives us a true programming language flavor in javascript just like Java, C# and so on. We can utilize all the features like - class, inheritance, anonymous function, scoped variable, string template, destructuring, itaitarator, etc.

Class

More oop type approach than using prototype.

class Rectangle extends Shape {
constructor (id, x, y, width, height) {
super(id, x, y)
this.width = width
this.height = height
}
}
class Circle extends Shape {
constructor (id, x, y, radius) {
super(id, x, y)
this.radius = radius
}
}

Constant

Const variable declaration support

const PI = 3.141593

Arrows

Simplified anonymous function declaration

nums.forEach(v => {
if (v % 5 === 0)
fives.push(v)
})

Get-Set

Like modern language seter and geter method for properties.

class Rectangle {
constructor (width, height) {
this.width = width
this.height = height
}
set width (width) { this._width = width }
get width () { return this._width }
set height (height) { this._height = height }
get height () { return this._height }
get area () { return this.width * this.height }
}
var r = new Rectangle(50, 20)

Block-scoped variables

Variables are now scoped within a code block using let key word.

for (let i = 0; i < a.length; i++) {
let x = a[i]
�
}
for (let i = 0; i < b.length; i++) {
let y = b[i]
�
}

Default Parameter

function f (x, y = 7, z = 42) {
return x + y + z
}

Rest Parameter

'a' can take n number of params and keep it in array of params ,can be accessed by index.

function f (x, y, ...a) {
return (x + y) * a.length
}

New Built-In Methods

Helper methods to do searching , validation , verification with lesser code.

Object.assign(dst, src1, src2)
[ 1, 3, 4, 2 ].find(x => x > 3)
"hello".startsWith("ello", 1) // true
"hello".endsWith("hell", 4) // true
"hello".includes("ell") // true
"hello".includes("ell", 1) // true
"hello".includes("ell", 2) // false
Number.isNaN(42) === false
Number.isNaN(NaN) === true
Number.isFinite(Infinity) === false
Number.isFinite(-Infinity) === false
Number.isFinite(NaN) === false
Number.isFinite(123) === true
Number.isSafeInteger(42) === true
Number.isSafeInteger(9007199254740992) === false

String Interpolation

In build String tinplating. No more - str + val

var customer = { name: "Foo" }
message = `Hello ${customer.name}`

Property Shorthand

Smart way to declare {x:'x',y:'y'}

obj = { x, y }

Method notation

Smart way to declare {x:function(){}} as shown below

obj = {
foo (a, b) {
...
},
bar (x, y) {
...
},
*quux (x, y) {
...
}
}

Modules

Import and export modules just as importing name space.

// lib/math.js
export function sum (x, y) { return x + y }
export var pi = 3.141593

// someApp.js
import * as math from "lib/math"
console.log("2p = " + math.sum(math.pi, math.pi))

Map & Set

let m = new Map()
m.set("hello", 42)
m.set(s, 34)
m.get(s) === 34
m.size === 2
for (let [ key, val ] of m.entries())
console.log(key + " = " + val)

let s = new Set()
s.add("hello").add("goodbye").add("hello")
s.size === 2
s.has("hello") === true
for (let key of s.values()) // insertion order
console.log(key)

Promise

function msgAfterTimeout (msg, who, timeout) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(`${msg} Hello ${who}!`), timeout)
})
}
msgAfterTimeout("", "Foo", 100).then((msg) =>
msgAfterTimeout(msg, "Bar", 200)
).then((msg) => {
console.log(`done after 300ms:${msg}`)
})

Tuesday, August 26, 2014

How to stop double tap or multi tap problem in android Xamarin

It is a common problem for android or any mobile developer, to stop unwanted multi tap in a button or view. This may cause blockers and crashes also. So, it’s a kind of serious and common issue. To fix this there are multiple solutions you can approach to. You can use timer or you can track down view event or even you can use a flag also. But again you have to change the flag after the button click occurrence. You can assign a different handler after first click. But also again you have to assign the real handler after the click occurs. All these may not give you 100% solution; as well it can be another piece of code for a new error.
Here I found a solution which may solve this issue in much secure and smart way.

Note: Same idea will work for Android Java developers.

Let get in to it-

Step 1: Create SingleClickListener class, with following code.

public  class SingleClickListener
    {
        public SingleClickListener(Action<object, EventArgs> setOnClick)
        {
            _setOnClick = setOnClick;
        }
        private bool hasClicked;

        private Action<object, EventArgs> _setOnClick;

        public void OnClick(object v, EventArgs e)
        {
            if (!hasClicked)
            {
                _setOnClick(v, e);
                hasClicked = true;
            }
            reset();
        }
      
        private void reset()
        {
            Android.OS.Handler mHandler = new Android.OS.Handler();
            mHandler.PostDelayed(new Action(() => { hasClicked = false; }), 500);
        }
    }

Step2: Use it everywhere you need it, in following way-

Button myButton= FindViewById<Button> (Resource.Id.myButton);
myButton.Click += new SingleClickListener( myButtonClickEvent).OnClick;
void myButtonClickEvent (object sender, EventArgs e)
{
//your button click code goes here.
}


That’s it. :)