Thursday, August 28, 2014

Creating A Simple RESTful Web Service using Express Node.js - JSON Data for Different Platforms (Part - 1/2)

As Every Day Device Shrinks and the way how it is connected to the Server to pull data and Append data becomes complex.Here is the solution for that because usually Network related application are data driven applications,where data is the king and we could make up something as we need .JSON data - Javascript Object Notified which is considered to be Light weight data for data sharing between two platforms or systems.where XML is also used,but JSON is preferable for mobile applications to pull data easily via AJAX JQuery with cross origin request.API is common term where in web apps are data driven application,Data is used to build apps which paves a way to create Application Programs with those data.


Creating A Simple RESTful Web Service using Express Node.js - JSON Data for Different Platforms (Part - 1/2)
Creating A Simple RESTful Web Service using Express Node.js - JSON Data for Different Platforms (Part - 1/2)
Download :  Download Demo

The Main Aim of Creating such Rest API Web Service is to share the data between application where we could create apps that can reach a huge peoples!


There are lot of standards in REST API building to prevent attacks,scaling and illegal requests.To prevent that we could add APP ID and Secret token basically (BASIC).Oauth2 standards would have such process



  • The Specific Application is registered with APP id and Secret key and may be where the origin request is arises and handled.
  • Provide appId and Secret Key for Application.where the app developer just pass them via Header
  • [may be sometimes they have permissions if it is a Big Company like Facebook,Google,Twitter
  • And Action to be perform is passed via Body part with data to be processed.
  • Return Success/Error messages with Data to application in JSON/XML format
The above steps are basic simple but there are lot of methods to be followed for full Fledged API platform to run with performance.

Scope:

My Application will pull data from Server which is managed by Node.js as Backend Server Responding the Requests!

Warning:

  • This is just Basic Model Of pulling data from server to display at cross platform application.
  • I haven't enabled any HMAC Security and any other securing features to authenticate.
  • I am using Express Framework 4.x.x version since it is handy for me.
  • I am versioning the API via URL for my easiness.There are lot of controversies in this versioning API via URL/or body part!

Node.js Express Backend:


First of All let me Create a Simple routes that can respond with JSON format data and accepting inputs via body and headers.

package.json

{
"name":"SampleRestAPI",
"description":"Basic Web Service",
"version":"0.0.1",
"private":true,
"dependencies": {
              "express": "~4.x.x",
               "body-parser": "*",
              "mongoose": "~3.8.11"
  }
}

server.js:


Important part is to create routes for your application and which can determine to give away resource! Rest API is meant for that! Asking for resource via HTTP methods. :)
simple examples of creating routes for ur application:


app.get("/",function(req,res)
{
      //get movies list data
});
app.post("/year",function(req,res)
{
        //filter year wise result movie
});
app.post("/create",function(req,res)
{
      //create new movie in Database
});
app.put("/update",function(req,res)
{
     //update certain part of the object(movie)
}
app.delete("/delete",function(req,res)
{
     //delete object(movie)
}



So,from the above Routes created , you may get some idea to build yours,there are lot of techniques in routing in express,if you can manage it apply and make it,others simply you can use and further learn more about creating complex application routes[Express 3.x.x] version
And Finally respond your client with the JSON data appropriately using res.json method

Creating Database for Back End Data Handling With MODULUS.io:


Since we are going to handle a considerable amount of Data lets have simple schema holding recent film,2014 films and love.horror movies in single schema document with sub-document.


Create A account in modulus.io for free Mongoose Database hosting.It is actually free but we wont use it upto such extent! :)



  • Create An account with your email account
  • Create New -> Database service
  • Select preferred Hosting such as Amazon/Joyent
  • and give Database Name , here Database Username/Password is very important.
  • After creating they will provide a URL to connect to your database

mongodb://<username>:<password>@proximus.modulusmongo.net:27017/zzzzzzz


The Above GIven URL is for example ,you may get different Domain ,Port number and Database unique ID


database.js :



Sample DB from modulus.io
This is created for connecting your schema to Hosted DB and transferring of Data from application to Database and reverse to :)


 module.exports = {'url' : 'mongodb://<username>:<password>@proximus.modulusmongo.net:27017/zzzzzz};

server.js Additional to Routes :

Let me explain the logic of Database query here,Btw we connected to mongoose db with url connect() using the url.



  1. GET /  -  This route is used to request whole movie database with native function find() without passing any params and return type to client as JSON Format
  2. POST /create - this route is used to create new movie object and append to database and return user with unique id for the insert
  3. PUT /update - this route is used to update a movie by passing _id and necessary details to update.here findbyIdandupdate function is used to find id and update simultaneously.
  4. DELETE /delete - this route is used to delete a movie by passing a id and remove function is used to delete from our database
  5. POST /year - this route is used to search for particular year movie details using find() function and return as JSON[this can be done using GET method by passing params in url]



model.js:

var mongoose = require('mongoose');
var movie_api = mongoose.Schema({
    movie          : {
        name       : String,
        year         : String,
        director   : String,
        genre       : String,
        thumb      : String ,
        music       : String,
        rating       : Number ,
    }

});

//you can have methods here 
module.exports = mongoose.model('movie', movie_api);


Thus in Above model.js we have defined our database schema and how we are going to organize our data in mongoose database.



My Try over API from REST CLIENT :

Download the REST API Client from here. abd have a try.


  • Download the files and extract
  • execute npm install
  • run server.js file
  • try the API URL from client addons
  • report for errors/bugs [email protected] 

REST ADVANCED CLIENT CHROME ADDON - A try over my API


Note : I haven't validated any data from user and retrieve from DB.This is basic app for RESTful Webservice and not suitable for production mode.

Try the Demo files in your localhost/node.js hosting.if any error/suggestion/bug do comments below or mail me [email protected] or connect with me in FB/Twitter for help and other sorts.Share is care

Thursday, August 21, 2014

Working With File-Encryptor Node.js Module - Encrypt and Decrypt your Files OpenSSL

I love Encryption/Decryption a Lot in Javascript ! And I have Already written article on JavaScript Crypto.JS Library and got many Responses/Doubts.And So recently I have Been working on a Small Node.JS project for File Management System in Cloud , I have Been using this File-Encryptor module for my Use.And i didn't see Any Successful Blog post guiding for this Encryption/Decryption File Module in Node.js.


Working With File-Encryptor Node.js Module - Encrypt and Decrypt your Files OpenSSL
Reference :   Download Demo


Installation:

>npm install file-encryptor 

Requirements: 

Procedure :

Require File encryptor and path for our Application.


 var encryptor = require('file-encryptor');
 var path = require("path");


Encrypting File : 

Encrypting the File is easy,Just invoking the function lets you to Encrypt as DAT file in directory.Using the FileSystem Module we could normalize our directory 






var key = 'My KEY For Encryption';
var input = __dirname+'/../private/file.txt';
var output = __dirname+'/../private/filename.dat';
encryptor.encryptFile(input, output, key,options, function(err) {
                if (err)
                  throw err;
         console.log("Successfully Encrypted!");
                   
});



Decrypting File :

var key = 'My KEY For Encryption';
var input = __dirname+'/../private/filename.dat';
var output = __dirname+'/../private/file.txt';
encryptor.decryptFile(input, output, key,options, function(err) {
                if (err)
                  throw err;
         console.log("Successfully Decrypted!");
                   
});



Options : 

Before trying Just Install OpenSSL in your System to and Make it Available via Commandline [Set Path]
Now Try openssl list it in your command Prompt and verify your Preferred Algorithm is installed.by default this module does aes192 if your not passing option as argument in function.

var options = { algorithm: 'Your Openssl Encryption Algorithm' };

var options = { algorithm : 'aes256' };


Basic Application :

Package.json


{
  "name": "node-encryption",
  "main": "server.js",
  "version" : "0.0.1",
  "dependencies" : {
    "express" : "~3.4.4",
    "file-encyptor" : "*",
}
}


Server.js:
Try out this simple node application by creating private directory in your project folder and create filename.txt and try encryption first and then followed by decryption.



var http = require("http");
var express = require("express");
var app = express();
var encryptor = require('file-encryptor');
var path = require("path");

app.get("/encrypt",function(req,res){

   var key = 'My Secret Key';
   var input = path.resolve(__dirname+'/../private/filename.txt');
   var output = path.resolve(__dirname+'/../private/tmp/file.dat');
    var option = { algorithm : 'aes256' };
   encryptor.encryptFile(input, output, key,options, function(err) {
      
        res.download(output);   });

});
app.get("/decrypt",function(req,res){
       
   var key = 'My Secret Key';
   var output = path.resolve(__dirname+'/../private/filename.txt');
   var input = path.resolve(__dirname+'/../private/tmp/file.dat');
    var option = { algorithm : 'aes256' };
   encryptor.decryptFile(input, output, key,options, function(err) {
      
        res.download(output);  

 });  //end of decryptor function 


});

http.createServer(app).listen(3000);
console.log('Application Started now ');


For dynamic advanced application you can temporarily create filename unique manner and assign to create encrypted file in your directory.you can make use of tmp npm module.
try out with different algorithm for encryption/Decryption.I have used aes128/aes256/aes192 for my project.I am leaving in your hand for filename generations and applying it.

If you can find any errors/bugs/issues/suggections in my Demo/Post just comment below!lets resolve it.
For Errors/Comments and more details lets discuss below or mail me [email protected] or connect with me in Facebook/Twitter.Share is care.

Monday, August 18, 2014

Run Android Apps on PC Desktop with Windroy - i-visionblog by @nancy.joslin

We have many software like BlueStacks ,youwave,genemotion,andy to run android apps on pc. We can also use another emulator - WINDROY. It is a freeware android running with windows. It is the easiest and fasted way to run all android apps and games including 3D games on your pc along with windows.The present version is android 4.0.3 and new versions are being developed.Note that if you have Eclipse installed in your system you can run any type of Android OS with emulator from Google and with custom settings from your preferred companies like samsung,SONY too.


Scope :

This Article Enables you to run Android application on Windows Desktop [PC]

Specifications : 
It provides
  • ·         Android version 4.0.3.
  • ·         Runs on windows vista, 7, and 8.
  • ·         Supports any UI resolution.
  • ·         Supports Ethernet and PPPoE (Point-to-Point Protocol over Ethernet). 
  • ·         Gives the user the original experience of android device.
  • ·         Input devices are mouse and keyboard so easy to work with.

You can download Windroy from this link 
Install it.
Then open, you will one like this on your pc, starting may take several minutes.

Check the android version in settings>About phone.
Then check mark the ‘unknown sources’ in security >device administration.


To open android app, use one of the following methods. 
      
  • Go to the windroy location on your pc then open windroy_root>system>app Copy and paste your apk file then restart windroy from the beginning you will find your apk on that screen.
  • Go to the windroy location ,then open windroy_root>data>app.Then do the same as did before for first method.       

If this both didn’t work download android market such as mobogenie in windroy. Search your favorite app then download it and install. Now your app can be opened without any conflicts. Google play cannot be used.

Now go test all your android apps on your pc itself.Enjoy apps on PC!

Author :
Nancy Joslin , INDIA studies Computer Science engineering and loves to write technical articles on Android, and other amazing emerging technologies in i-visionblog.

Feel free to comment below to point out errors/bugs/experience.Willing to write posts in our blog join with us - contact me - [email protected] and connect with Fb/Twitter

Note that try this on your own risk on your pc,using android emulators on windows with caution.i-visionblog is no way responsible for damages by software.here by we just promote and introduce features that we had run for test purpose in our systems for development.

Wednesday, August 13, 2014

Deploy Node.js Application on Openshift Hybrid Cloud - i-visionblog

Nowadays Developers/End users prefer cloud services for their Usage,Storage and Demanding service in one clicks either using credit cards for paying the usage.Business start ups / Developers prefer to host their applications on cloud public for users access, and to manage a huge data ,analyse by powerful cloud machines provided by cloud service providers.Where Business peoples/Developers and others can forget their Hardware specifications and start involving in the Application designs and management.Cloud plays important part in business side data/analytics handling!


Deploy Node.js Application on Openshift Hybrid Cloud - i-visionblog

Article About Cloud at i-visionblog : 

  1. What is Cloud Computing ?  - A Good Explanation for Easy Understanding with Video.
  2. Deploy PHP application - Heroku Cloud [ free untill you add add-ons]
  3. Deploy PHP application+IBM Bluemix Cloud [free trial Period ]
  4. Deploy Node.js Application+IBM Bluemix Cloud Foundry
  5. Deploy Mobile Application DataStore online - Parse.com [ Free for Personal apps ]

Scope : 

Here You can develop a simple Node.js Application at Localhost and make it as deployable at Openshift(Red Hat) .

Installation : (Windows Machine ) :

  • Download GIT command line and make sure accessible via command Line [ git --version  must output with version number] click here to download.
  • Download Ruby Installer [ Stable version ] from here Must be accessible via command line.
  • once all goes well do  C:\> gem install rhc  Must Install you with RHC Client for windows.
  • Go to Red Hat Openshift Website and create a Account & then  Create a Domain name.  
This is Enough to Deploy your app in minutes from desktop.however Mac,Linux others can follow deploy process which is same since Git is Standard.Installation can differ.

RHC Setup :

 C:\ >  rhc setup 

It may prompt you for Adding server host ! Just Skip it by Pressing Enter key.you can add it later too.
Then It may ask you to login with openshift account online emailID and Password in CMD if you're doing it first time.
And allow to add a Private SSH file for authentication purpose - RSA public key adding it permanently on you command line for 30 days life time.Enter "yes" to accept and proceed.

Creating Application :

 I would Generally appreciate you to Go to Openshift website to have Overview of application present.
There are lot of application present to be installed.
  • Add Node.js Application by clicking add application
  • Name your application [ Note that you must have added Domain Name already after sign up ]
  • And Add a custom Url for your application - [ can be changed if you have DNS records ]
  • Git repo is optional here 
  • If you want to scale application for more users,Do load balancing here- [note if you have database in application make sure it is shared across application on different instance shares it]
  • Create Application and Get the Source url starting with SSH:// on console application page
Adding Source :
adding source to application !
  • C:\ > git clone [copy the SSH:// URL here ]
  • This would initialize your application directory for Deploying.
  • Copy your Application Folders/Files with package.json and server.js [server.js name is mandatory to start your application ]
Changes in server.js:

Your Localhost is not equivalent to Cloud Setup so, you must provide ip and Port variable to run your application on cloud.And make sure port,ip should be same as Below for any type of Node.js 

var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var ip = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";

and At last while making the application to listen to given port,ip

server.listen(port,ip);

A sample of Server.js file :


Thats All just move in to your Directory through Command Prompt .execute three commands succesive manner and deploy your application.For updating application just follow these three commands one by one.

  • C:\ > git add .
  • C:\> git commit -am "initial commit"
  • C:\> git push origin master 
Debug & Logs :

  • just type  C:\> rhc tail <app_name>
will provide you ongoing Requests / Errors in the Node Applications .

Thus we have Successfully Deployed First Node.js Application on Openshift Hybrid Cloud.Openshift is Free to have Three application with Scalable Application , Https Connection access and also more add-ons With Limited three Gears each Application & 1 GB space.Have a try ! be cautious before adding Credit cards because it may cost you for overusage!.

Report for Error/Suggestions as Comments or mail me [email protected] / or connect with me in Facebook/Twitter.Enjoyed the Posts,Share is care and Do comments!

Thursday, August 07, 2014

Handling File Uploads and Downloads In Node.js with Ajax - Express Framework

Uploading the files is important aspect of transferring the data to the server from the client and moving it to the storage to share for downloading and later usage also.However encryption is important aspect of saving the Files safely with pass phrase encryption/and Decryption on Downloading or requesting.These types of Application is done generally in Cloud for user safety for files from Illegal Access.However Node.js doesn't allows you to peep into directories and get download the files where these directories are generally private unless you make it as Public Folder.This is a Main Advantage for us.



Resource : Download Demo files 

Scope:
We are Just going to Upload the Files via Ajax and Retrieve Files from Directory using FS module and make to available for Download.This Application is simple integration of Storing files online and retrieving it from anywhere.


Package.json:

Create package.json and run the installation to create dependencies for our app.
{
  "name": "expressapp",
  "version": "0.0.1",
  "description": "uploading files-Downloading",
  "dependencies": {
    "express": "3.x.x",
    "Jade" : "*"
  }
}

server.js:

Let me Explain about the server.js - i am initializing the app with Express Framework.Then setting the port for the app to listen in my Configuration function by app object of express.For Templating language i have used JADE to parse the variables across the files(view) and set up my View directory.
Then i have initalized with body parser for fetching my posted values via body and setting the limit of upload and keepExtensions of my uploaded file and setting the path for my directory for uploaded files in Server.And i have set up a public static folder for Javascript/CSS files.

So, creating the routes explicitly read here and here to create route url for Node.js Application.I have created four routing URL for index,Upload,Download,listing files.


Replace the Path URL to fetch corresponding files from your directory.For the Convenience I have used JADE  as Templating language ,You must use it carefully since it is space/tab sensitive.Use online Jade input/output for verfiying your syntax.

FileSystem Function :



var fs = require('fs');
fs.readdir('C:\\Users\\S.Shivasurya\\Documents\\node\\expressapp\\tmp\\', function (err, files) {  if (err)
    throw err;
var result=new Array();
 for (var index in files) {
  if(fs.lstatSync("C:\\Users\\S.Shivasurya\\Documents\\node\\expressapp\\tmp\\"+files[index]).isFile())
    result[index]=files[index];
 }
 res.render("files",{ result:result });  //rendering file.jade for viewing
 });

The above functions just read the given directory and fetch all files and save it in an array if it is file and not a directory! refer to node.js docs for more fs functions

Script.js (Ajax file Upload):


A Third Party plugin for AJAX upload with progress bar:



Jade for looping Array :

file.jade to list out the Files in directory while accessing /file route


extends layout
title files
block content
  div.container
    div.content   
        ul
          - each results in result
            li= results
            input(type='submit', value='Download',id=results,class='download')

  div.footer

Index.jade:


extends layout

block content

  div.container
    div.row
      div.span12
        form(method='post', action='/')
          legend express-upload-progress
          input(type='file', name='myFile', id='myFile')
          p
          div.form-actions
            input.btn.btn-primary(type='submit', value='Submit')
    hr
    div.row
      div.span12
        div.progress.progress-striped.active.hide
          div.bar(style='width: 0%')
    div.row
      div.span12
        div.alert.hide
          button.close(type='button', data-dismiss='alert') x
          span
            strong.message

Layout.jade:


doctype html
html
  head
    title express-upload-progress
    link(rel='stylesheet', href='/stylesheets/bootstrap.min.css')
    link(rel='stylesheet', href='/stylesheets/style.css')
  body
    block content
    script(src='/javascripts/jquery-1.9.1.min.js')
    script(src='/javascripts/bootstrap.min.js')
    script(src='/javascripts/scripts.js')

Download script as client javascript :

This is a simple script that can post the filename we request and download the file from Node.js express routes /download.i am not doing any Ajax operation here.just submiting POST request to server for downloading a file.

on clicking the download button,Jquery request for the file and downloads on the browser automatically.


$(document).ready(function(){
  $(".download").click(function(e){
   var filedata=this.id;
  $('<form action="/download" method="POST">' + 
    '<input type="hidden" name="file" value="' + filedata+ '">' +
    '</form>').submit();

    });
});

I Have tested on Localhost node.js server ,Have a try with demo files provided,If any error/Bug in Code/Article post as comment/mail me [email protected].connect with me via Facebook/Twitter for help.Share is care.report for bugs.