Thursday, June 26, 2014

Working With Parse.com For Mobile Application Data Storage - Javascript API Connecting NoSql Datastore

Nowadays we are always tempt to use mobile applications on Android/iOS/ BBos and Windows 8 and etc...where these apps have to store the data for future reference.Particularly concentrating HTML5 apps powered by javascripts are more powerful and easy to build across different platforms.The User data is better to store in cloud and could be searched with the help of API provided.although Parse stands Easy for me for saving data,Where Bluemix Also supports that ,I have tried Parse since it gives Class-Object approach to save data with few lines of Javascript code.And Application can be easily scalable and Searched efficiently.Not Only mobile applications,Apps that is data-driven can also use this feature for easy storage and tension free and forget about Database design,Support and code for connecting database.Where parse provides simply efficient datastore with Access Tokens and Application ID and save your data.And it is also part of Facebook :)

Working With Parse.com For Mobile Application Data Storage - Javascript API Connecting NoSql Datastore
parse.com - i-visionblog - Mobile apps Storage

Scope:

This Post can Give you a Experience to store data as Objects via Class using Javascript API provided by Parse.com.Not only Data, You could upload files and others too save in the Datastore,with few lines of Javascript Code and Application ID and Secret Code.

Installation :

As Like Normal Javascript include it in normal part and You can Download from Official Parse Site.click to Download

                  <script src="./parse-1.2.18.js"></script>

Understanding the Concept Of Saving Data : 

Storing data on Parse is built around Parse.Object. Each Parse.Object contains key-value pairs of JSON-compatible data. This data is schemaless, which means that you don't need to specify ahead of time what keys exist on each Parse.Object. You simply set whatever key-value pairs you want, and our backend will store it.
Create a Object by extending the Parse.Object.extend and this could create new class and then we could save as Keys must be alphanumeric strings. Values can be strings, numbers, booleans, or even arrays.

example for raw data :

                    email: "[email protected]", phone: 9788012345

JavaScript API to Handle Data :

I have Chosen JQuery to Handle my data and operation to perform with Parse javascript functions with callbacks,since it is basically network operation.

1) Create Application in Parse.com  and You may receive Application ID and Secret Keys for various platforms for your application.

Initialize Your Application to Connect Parse :
First Initiative step is to save the Data as objects with particular class in Parse.com.So,Create a Class in parse dashboard.

2) just use Parse.initialize method to configure your application and get connected to the Parse Datastore.

Parse.initialize("Your App ID", "Your Javascript Key");

CRUD functionality:

3) First let us see how to create a Row(Record) with unique object ID that contains User Data, and by default it has Created Time ,Updated Time with ACL(Access Control List).

To Create a record just extend the parse object with suitable created class and create object with that and invoke the function save to save our data in Datastore.Well see the example below.

   var createobject = Parse.Object.extend("users");
   var objectwithdata = new createobject();
   objectwithdata.save({email: email,phone: phonenumber},{
         success: function(object) {
         console.log("success");
         $("#load").hide();
         },
        error: function(model, error) {
         console.log("error");
           }
    });

In above code we have just extended to class user and created object of User class.and we have added few data by invoking a function save() with a callback function with success and Error handlers.since it is time consuming operation to save data in parse.so whenever the return is success a row is added automatically with Object ID ,it is better to retrieve and keep it in HTML5 storage for later queries and other operations.

Retrieve Data : 


   var retreiveobject = Parse.Object.extend("users");
   var retrievedata = new retreiveobject();
   retrievedata.get("Your Object ID for Particular Client",{
         success: function(object) {
         console.log("success");
         console.log(object);
         },
        error: function(model, error) {
         console.log("error");
           }
    });

In above code we have just extended to class user and created object of User class.and we have read few data by invoking a function get() with a callback function with success and Error handlers.

Update Data :


   var retreiveobject = Parse.Object.extend("users");
   var retrievedata = new retreiveobject();
   retrievedata.get("Your Object ID for Particular Client",{
         success: function(object) {
         console.log("success");
         console.log(object);
         retrievedata.set("email","[email protected]");
         retrievedata.set("phonenumber",9876543210);
         retrievedata.save();
         },
        error: function(model, error) {
         console.log("error");
           }
    });

In the above method we had retrieved the data and we just used set() function to update values and finally call save() function to update the data in database.

Delete Object :

   var destroyclass = Parse.Object.extend("users");
   var destroyobject = new destroyclass();
   destroyobject.destroy("Your Object ID for Particular Client",{
         success: function(object) {
         console.log("successfully deleted");
         },
        error: function(model,error) {
         console.log("error");
           }
    });

In the above method we have just called the destroy() function to destroy the row of particular Object ID from Datastore.
There are still Lot arrays,Datatypes,queries,compound query,relating data and so on.visit here to Learn more

My sample :

I have created a class named users with phone numbers and email storing data in parse and when success function runs it is redirected to List.html file in my mobile application.

       //consider jquery.js included
     <script src="js/parse-1.2.18.js"></script>
     <script>
   
        $(document).ready(function(){
   
        $("#login").click(function()
            {
                var email=$("#email").val();
                var phonenumber=$("#phonenumber").val();
                console.log(email);
                console.log(phonenumber);
                $("#search").hide();
                $("#load").show();
                Parse.initialize("My APP ID", "My javascript Secret Key");
                var TestObject = Parse.Object.extend("users");
                var testObject = new TestObject();
                testObject.save({email: email,phone:phonenumber},{
                  success: function(object) {
                   console.log("success");
                  $("#load").hide();
                   window.location="./list.html";
                },
                error: function(model, error) {
                console.log("error");
      }
});        
 }
        );
            });
    </script>


My simulated application results:

I had made a simple form to trigger with sign up button and call parse.save function to save data in Datastore.

Cautions:

1)Always concentrate Errors on Console Log of chrome to minimize the Errors

2)However it is javascript client code it is showing both keys public manner.so just use ACL and permissions,Sessions to prevent Illegal data transactions in Parse Dashboard.

3)Handle the Errors and print the errors to guide the project to success.




My result:

my Class with Data populated on Parse.

Beware of Securing the Data.Just Try out Parse for Mobile apps and make use of Cloud code for efficient scaling.For further doubts/Bugs/reports Mail me [email protected] or let us disqus as comment below.Share is care

Thursday, June 19, 2014

Node.js With Express Framework Basic App on IBM Bluemix - Deploying Cloud Foundry

As i got request from +Yogesh Asthana brother by Google+ on Node.js app basics and other frameworks to build Highly scalable application that can be real time usage.Node approaches different manner in responding requests and while other scripting language make threads and use the RAM and core with full fledge usage and blocking approach.But Nodejs take care since it is written as Asynchronous functions with non blocking I/O behavior ,where when u Do some task in Nodejs like Database operations or file upload ,which is cost effective, network based and time consuming operations are made asynchronous where it will return the results later.here the next line code executes without any blocking.Thats why it is faster and may be due to other reasons to.This is built based on Google Chrome Run Time Javascript V8 compiler,by Google Engineers.
Node.js With Express Framework Basic App on IBM Bluemix - Deploying Cloud Foundry
nodejs with express i-visionblog

Demo | Download | Contact 

Scope : 

By this Post You could successfully Run a simple app Nodejs with Express in Blumix Cloud,IBM.
I have explained to build a simple app in my Youtube Video Channel.Any way i will Provide Explanation also by words below.

Downloads :

Visit Nodejs website and based on the operating system install the Nodejs in Your local machine for Locally testing your app before deploying cloud.

As my Last post gave You idea of IBM Bluemix,Just Create account in Bluemix and install Cloud Foundry Tool. - refer Here to install

Let Us Code : 

Basic Nodejs App contains Package.json file through which you can download all the dependencies and maintain your app efficiently even if you migrate from System.simply by using npm command you can fetch and install the dependency modules.You can simply initialize your package.json By command line

npm init  // will ask you one by one and you can provide details corresponding.

here i am explaining a simple app named sample and with description and others too.
package.json 

{
"name":"sample",
"description":"second app with node js",
"version":"0.0.1",
"private":true,
"dependencies":
{
"express":"3.x"
}
}

For Further Create a directory and do all the above operations.
now create app.js file to regulate and control our app.here app.js name is optional you can name it as per your needs.[main.js is mostly recommended]

app.js : 



var http = require("http");
var express= require("express");
var app= express(); // here we are defining our app and initializing with express 

//i am going to make basic routes for app

app.get("/",function(req,res){
res.send("<h1>this page is from Node js Express APP - Shivasurya - </h1>");
});

app.get("/welcome",function(req,res)
{
res.send("This welcome page ");
});


app.get("/about",function(req,res)
{
res.send("This is from About page ");
});

app.get("/example",function(req,res)
{
res.sendfile('example.html');
//the above fun send html file to browser so that browsers can intrepret
});


//similarly you could add routes and send the text as html or even html files to the browser using res.sendfile();


http.createServer(app).listen(3000); //here 3000 is port number for app



//thus we have created a simple web app using Express framework

In the Above Code we created Express object of response and request and we accessed send() and sendfile() functions.there are still more functions can be invoked,by next post i will brief it about the Routing techniques and best practices.Open Your browser point to localhost:3000 and check the routes we defined already in app.js

Time To Deploy On Cloud :


Check that You have Installed by Using the Command in Your Command prompt.

C:\>cf -v  

must output the version number of your CF Tool installed currently.Move to Your Current Directory where your project lies.We need Small Changes in Our code since it is Production Environment however your going to test in on Cloud as Sand Box mode.

Code Changes For deploying at Cloud :

thus we had Simply added VCAP service Port Number and Host to work perfectly on cloud environment.

var port = (process.env.VCAP_APP_PORT || 8192);
var host = (process.env.VCAP_APP_HOST || 'localhost');
var http = require("http");
var express= require("express");
var app= express(); 


app.get("/",function(req,res){
res.send("<h1>this page is from Node js Express APP - Shivasurya - </h1>");
});

app.get("/welcome",function(req,res)
{
res.send("This welcome page ");
});


app.get("/about",function(req,res)
{
res.send("This is from About page ");
});

app.get("/example",function(req,res)
{
res.sendfile('example.html');

});


http.createServer(app).listen(port,host); 



now create a Manifest.yml file to instruct Bluemix to allocate Nodejs Applications,space Instance and others.i have explained in my Last Post on Creation and Usage of Manifest.yml.

Manifest.yml


---
applications:
- name: sampleapp1995
  memory: 256M
  instances: 1 
  host: sampleapp1995shiva
  command:node app.js

Just Push the App using the command below in Command prompt

$ cf push
Progress :


finally after deploying
during installation depedencies automatically screenshot


note: Work with caution because cloud may costs you money for over usages and scalling instance.And you can use HTTPS connections too.

I have deployed my application on Bluemix.just have a try since it is free till june month 2014.just share your experience with comments and post errors.Contact with me in [email protected].Share is care.