Tuesday, 8 July 2014

Working With Google URL Shortener Service API and Create,Track,Maintain Analytics with Google Account - Javascript API


URL shorteners are really useful for stats counting ,providing small sized URL instead of a huge links.Many Business on Internet Social Media needs stats on how many peoples clicked and used the url.However there are lot of service such as +Klout , +Buffer  and so many sites have their own url shorteners and make stats for users and business organiztions based on data clicks,reactions from Popular social networks.So,Creating and maintaining Shortened URL with Performance and scalability is important,Thats why Google gives us API platform where we could Read,Create,Analyse the Shortened URL by them.we are Just using the service provided by Google in rightful way by providing access Tokens , Login.


Working With Google URL Shortener Service API and Create,Track,Maintain Analytics with Google Account - Javascript API
google URL shortner API service
Files   :  Download   |  Live Demo 

Scope : 

I have Written a simple Web application that connect with your Google account and Can fetch Your all Shortened URLs,Analytics and create new URL and shorten them within an instance.

Installation and Requirements : 

First of All Log into your Google Developer Console for registering our API service and to get API KEY and for Oauth Login. Click here






  • Create a Project and move inside [*note :  I haven't enable Billing for using Cloud or API Service-be cautious while using those service]



  • Under APIs And Auth select API -> enable URL SHORTENER API  alone is enough.



  • Then Move to Credentials Tab.Create API public Key with suitable requirements.select Browser key.


  • API KEY set up
    Then Move To Create Client ID : 
    Application type : Web Application with Authorized javascript Domain Origins and Redirect URL.I have given Both as same Since it is Single page web app under index.php in my localhost
    Get your Corresponding API key from Public API and CLIENT ID for our Web application.

    we need two Scripts from google namely client.js and jquery for easy handling.


     <script src="https://apis.google.com/js/client.js"></script>
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>


    Initialize App with Login and Fetching Access Token :
          Juts use Client ID here and Load with gapi.auth.authorize( ) function to authorize our application with an Google account.


      var apiKey = "API _ KEY here";
     var clientId =  "CLIENT _ KEY _ HERE ";
       var scopes ="https://www.googleapis.com/auth/urlshortener";



    Authorize function :

    gapi.auth.authorize   - method just takes client id and scope for authenticating user and provides you access token with gapi.auth.gettoken()


      function auth() {
            var config = {
              'client_id': clientId,
              'scope': scopes
            };
            gapi.auth.authorize(config, function(data) {
              console.log('login complete');
              console.log(gapi.auth.getToken());
             if(data.access_token)
             { $("#login").hide();
                    $("#call").show();
              }
           });
          }


    Create A New Shortened URL : 

    Generally client.load is used initialize with three params namely : scope ,version ,and a call back function to execute.This is the general approach to call API and bring data inside your application for any type of API data pulling,updating service.
    gapi.client.urlshortener.url.insert - is the main function which request the server API for result data and operation.this function just passes the Long url parameter to create shortened URL in return as JSON object.
      
           function load() {
             gapi.client.setApiKey(apiKey);
             gapi.client.load('urlshortener', 'v1', create);
    }
        function create() {
        var url = $("#url").val();
      var request = gapi.client.urlshortener.url.insert({
        'resource': {'longUrl': url }
      });
      request.execute(function(response) {
             // success do something here with responded data
             console.log(response.id);
       });
    }


    Retrieveing Long URL by inputing Short URL : 

    By the same above method gapi.client.urlshortener.url.get is responsible for fetching the relative long URL.
      
           function loadforretrieve() {
             gapi.client.setApiKey(apiKey);
             gapi.client.load('urlshortener', 'v1',read);
    }
        function read() {
         var url = $("#url").val();
      var request = gapi.client.urlshortener.url.get({
        'resource': {'shortUrl': url }
      });
      request.execute(function(response) {
             // success do something here with responded data
             console.log(response);
        });
    }



    Retrieving USER ACCOUNT shortened URL and Analytics :

    Similarly By the two Methods  gapi.client.urlshortener.url.list( ); will list you all URL already shortened by particular logined user.
     gapi.client.urlshortener.url.list({"projection" : "FULL"}); will list you with analytics ,clicks with month,days basis have a look at the response on console after performing the action.
      
           function loadforuser() {
             gapi.client.setApiKey(apiKey);
             gapi.client.load('urlshortener', 'v1',userapi);
    }
        function userapi() {
         var url = $("#url").val();
      var request = gapi.client.urlshortener.url.list( );
      request.execute(function(response) {
             // success do something here with responded data
             console.log(response);
        });
    }


    You can achieve this function calls simply by button inputs onclick events and you should do with logic since you have jquery for hiding login button after authentication and displaying input box to create.

    If you have any doubt just ask in comments/mail me s.shivasurya@gmail.com.if you can find any bugs comment below.Share is care.

    Wednesday, 2 July 2014

    Node.js With Express.js Framework - Routing Techniques With Name-space

    Express.js Framework on Node.js doesn't inherit from Connect router instead it is built with it.Routing is useful to create Friendly URL's and manage your stuffs in site in elegant manner.When your application becomes complex for managing routes.here comes Namespaced routing for managing urls with namespaces However only you must select the routes accordingly for your application.Express.js doesnt force you to use particular routing.As like as An unplanned routing system for CMS will suffer a huge during the production environment.so,choose and manage your routes efficiently.

    This Post is for 3.x.x version of Express.And note that this is an inbuilt feature in 4.x.x version of express.i will update how to work with 4.x.x routing techniques.

    express-js-i-visionblog













    Downloads :   |    

    Namespace Express routes :

    When your application becomes complex you have to manage a big set of uri in your application,however taking it to seperate routes handlers is second part.let us see how could we segregate them as per needs.when you write CMS,Store or anything you need to club the URI for certain functions.Here Namespace comes to recover us.

    Expected Namespace URI structure :
    when i plan for app store as well as books store within my single website that would be tedious for me to manage them.so i may need URI like below.

      
       surya.com/apps  --> index page of apps store
       surya.com/apps/facebook -->facebook app to download and description
       surya.com/apps/googledocs --> googledocs app to download and description

       surya.com/books -->index page of book store
       surya.com/books/headfirstandroid ->headerfirst android book for download.
       surya.com/books/edit --> must load details for admin to edit the items on index page.


    Installation (package.json):


    {
    "name": "routersample",
    "description": "simple routing and namespaced routing",
    "version": "0.0.3",
    "private": true,
    "dependencies":
    {
    "express": "3.x",
    "express-namespace": "*"
    }
    } 

    Run your npm install command in your application directory.Learn more here

    Defining Routes :

    Note Here we are initializing the http and express before namespace and then app is initialized after namespaced.unless your app with namespace wont work for your needs.

    var http = require("http");
    var express = require("express");
    var namespace = require("express-namespace");
    var app = express();


    Defining routes as per our needs goes below :



      app.use(app.router);
       app.namespace('/apps', function() {
           app.get('/', function(req, res) {
             res.send('Respond Client with Apps Index Page here');
            });

            app.get('/facebook', function(req, res) {
               res.send('Show Facebook App with download link and description');
            });

           app.get('/googledocs', function(req, res) {
               res.send('Show Google Docs App for download link and description');
            });
           app.delete('/delete/:apps', function(req, res) {
               res.send('delete application with  requested ' + req.params.apps);
            });
     });

     app.namespace('/books', function() {

        app.get('/', function(req, res) {
           res.send('Respond The Client With Books Index Page');
        });

        app.get('/headfirstandroid', function(req, res) {
           res.send('show Head First Android book To the User with Relevant Information');
        });
       
     app.get('/harrypotter', function(req, res) {
            res.send('show Harry Potter Book To the User with Relevant Information');
        });
     });
    http.createServer(app).listen(3000);


    Namespace can be nested with one another too.and note that app.router must be loaded explicitly before starting namespace routes.And initialize the namespace routes before the app gets initialize.
    Now point your browser url respective to your routes it works beautifully.This is why we call express as bloat free framework


    basic routing (video) :

    basic form submission and routing video.download files are available above. If you can find any bugs/Errors in my Demo or above code just disqus with me in comments or mail me s.shivasurya@gmail.com.share is care.

    Thursday, 26 June 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: "s.shivasurya@gmail.com", 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","suriya1180@gmail.com");
             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 s.shivasurya@gmail.com or let us disqus as comment below.Share is care

    Wednesday, 18 June 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 s.shivasurya@gmail.com.Share is care.

    Thursday, 29 May 2014

    Working with impress.js to create presentations using HTML & CSS3 - impress.js

    Impress.js was awesome plugin to create awesome presentation because it uses HTML and CSS3 to animate and make the presentation still more lively for users.at the sametime the Author of impress.js warns about the usage of the presentation will be nice only if it is interesting and it's not suitable for the official meets presentations.however it is easy to set up the plugin environment and start our presentation slides.I hope it works only on modern browsers.i have already used Fathom.js but it was regular for official purpose but this one is quite interesting to display interesting streams.
    preview img from presentation slide impress.js
      


    Browser compatibility: 

    Currently impress.js works fine in latest Chrome/Chromium browser, Safari 5.1 and Firefox 10. With addition of some HTML5 polyfills (see below for details) it should work in Internet Explorer 10 (currently available as Developers Preview). It doesn't work in Opera, as it doesn't support CSS 3D transforms.As a presentation tool it was not developed with mobile browsers in mind, but some tablets are good enough to run it, so it should work quite well on iPad (iOS 5, or iOS 4 with HTML5 polyfills) and Blackberry Playbook.


    Installation:

    just like other javascript just include both impress.js and demo-impress.js in your html file in between <head></head> tags.get the orginal source from here.



    <link href="/demo-css.css" rel="stylesheet" /> 
    <script src="/impress.js" ></script>


    Usage :

    Lets start with normal Html tags below

    <html lang="en">
        <head>
            <meta charset="utf-8" />
               <!-- your CSS and JS files can be included here. --> 
    </head>

    now lets dive into slides where i have made them in to div tags and mentioned them with classes and ID's.

    check browser issues:

    before that we must check the browser support if it supports then we could proceed normally! or else we must highlight by showing them Error message and try in latest browsers.

    <div id="impress" class="impress-not-supported">

        <div class="fallback-message"> <!-- this fallback message shows when issues exist -->
            <p>Your browser <b>doesn't support the features required</b> by impress.js, so you are presented with a simplified version of this presentation.</p>
            <p>For the best experience please use the latest <b>Chrome</b> or <b>Safari</b> browser. Firefox 10 (to be released soon) will also handle it.</p>
        </div> 

      <!-- your slides div can go here -->


    </div> <!-- end of div class="impress-not-supported" -->


    slides as div tag : 

    before directly creating tags,just imagine a graph sheet in which you reference with X,Y,Z axis in which our div slides are going to be placed.our javascript plugin takes the value from div and moves around accordingly with CSS3.
    it is mandatory to use Class step in each of our div slides.and you can mention other options if you want.

    General Approach of Div slide:

    <div class="step" data-x="Preferred_value" data-y="Preferred_value" data-z="Preferred_value" data-rotate="Preferred_option" data-scale="Preferred_option">

      <!-- here you could use your own style of HTML coding for contents --> 

    </div>


    Example for Div slide:
    options:
    data-x : which moves along x-axis slide
    data-y : which moves along y-axis slide
    data-z : which moves along z-axis slide
    data-rotate : which rotates around and reach your slide normally
    data-scale : which scales above the slide(zoom level)

    <div class="step" data-x="200" data-y="200" data-z="100" data-rotate="45" data-scale="5">

      <!-- here you could use your own style of HTML coding for contents --> 
    <p>welcome to i-visionblog.com</p>
    <p>i love to create and share my ideas through my blog </p>
    <p>i love to create web/mobile apps as a hobby and my interest is to work with Bigdata and analytics</p>

    </div>


    additional to this we could add some extra effects 3D with id="its-in-3d" and giving option to rotate in their axis 
    data-rotate-x & data-rotate-y & data-rotate-z : which rotates when sliding on their axis corresponding, can be a 3D view.however it is simple and easy to code.


    <div class="step" data-rotate-x="200" data-y="200" data-z="100" data-rotate="45" data-scale="-5" id="its-in-3d">

      <!-- here you could use your own style of HTML coding for contents --> 
    <p>it's a 3d view here..</p>

    </div>

    <!-- this is the last slide of the presentation mentioned with id="return" to go back to our first slide -->

    <div id="return" class="step" data-rotate="0" data-y="2000" data-x="2000">
    <p>join us ! code with us or create ideas | visit www.github.com/shivasurya</p>
        </div>

    <!-- this can be hint for users to naviagte with spacebar or arrow keys -->

    <div class="hint">
        <p>Use a spacebar or arrow keys to navigate</p>

    </div>



    contributors have added some audio and other specific functions go through them in Github official impress.js.if you can find more options and bugs in my demo/code comment below!

    This can be more innovative and interesting when you can think logically using graphs.other can simply use the template provided.I have mentioned options which i have used in this presentation,if i had missed out or any bugs,comment and notify me via E-mail.share is care.