Saturday, July 26, 2014

Getting Started With Node WebKit Apps- Developing Desktop Native Apps

HTML5 Becomes Day to day More Powerful since it supports many Developer Friendly API such as Audio,File,Geolocations and many too.Html5 was used to build Amazing websites,Phonegap Apps for Android,iOS,Windows and Bada OS too.Now it has been started to be used as Desktop Application with HTML5 API and Javascript API native Windows Tasks with the help of Node.js Modules.Having Experience on Node.js Previously I am Writing this Article - Read More about Node.js Basic Here.Even Intel Appframwork GUI based mobile application developing environment uses nodewebkit as a part!



Reference : Download Demo File

Installation :

Just visit the GitHub Project use their Download option and extract the file and keep it in directory where you frequently access.

Project structure :

|-www
|  |_ index.html
|-node_modules [ if necessary ] 
|-package.json
|-ico.png



package.json :




index.html:

consider Demo file for working purpose.

Creating Zip File : 


1) Create New-> Zip File 

2) Add all www,package.json and ico.png file to Zip files and rename name.nw.zip
3) go to nodewebkit folder where you have extracted and copy this Zip file .
4) open in command prompt[terminal].
5)move to extracted Folder which you have Downloaded and execute the command.

C:\node > nw nameofapp.nw.zip


This opens the nodewebkit app index.html with your specified app details using package.json file such as toolbars,height,width and etc.


Create executable binary for Distribution:


under same directory run the command in the command prompt


copy /b nw.exe+appname.nw.zip application.exe


Note:
For More Desktop API window environment Visit official Github Repo Wiki to learn more.Consider npm repository searches for creating node_modules under nodewebkit app for node.js support. 

If any error/bug in the Demo/Article Just Mail me [email protected] or comment below here.or connect wit me via Facebook/Twitter for interactions.Share is care. 

Saturday, July 19, 2014

Import Contacts and Invite New Contacts By Email From Gmail Contacts API - Inspired By Linkedin,Twitter Mail Importer

Inviting by E-Mail is an excellent way for asking new users to try our sites,Which is actually sent by their friends or contacts in Address Book.As Like as LinkedIn,Twitter Gets your Email address especially Gmail and Access all your contacts and Matches with Their Email Database and shows their existing users to follow(connect) and invite New users to try their respective sites.It means enjoying the site with their friends(Especially Twitter does this).Even i too joined LinkedIn and Twitter because of Invitation mail from my friends in Gmail via Twitter,LinkedIn.


Import Contacts and Invite New Contacts By Email From Gmail Contacts API - Inspired By Linkedin,Twitter Importer











Reference :  
 |  

Script Structure :
  • index.php [ Main Html markup and other scripts ]
  • mail.php   [ Send Mail with Loop for Users ]
  • invite.js    [ javascript file handling JSON data append and processing Gmail Contacts API ] 
  • process.php [ Compare exisiting users and new users responding as JSON format to frontend ]

Scope : 

This is simple add-on Application for websites having Email users database.It is similar to Twitter,Linked Contact Importer where they get API access and fetch email from corresponding service and filter them accordingly as existing users and New users.and giving some options such as Follow or Connect and Inviting by Emails.

Javascript API for Gmail Contacts Import :

Gmail API Contacts let you to Read,Update,Create Contacts in Gmail.Core part of the Contacts API below Here.

Installation and Initialization:

check here how to get those keys 
 var clientId = 'Your Client ID here';
 var apiKey = 'Your api key here';
 var scopes = 'https://www.google.com/m8/feeds';

with this we are going to add Javascript plugin Jquery,Client.js from google



<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script src="https://apis.google.com/js/client.js"></script>


Javascript API to get Contact List as JSON data :

Check my Last post to Authorize a Google User and access their API - Click Here

$.get("https://www.google.com/m8/feeds/contacts/default/full?alt=json&access_token=" + authResult.access_token + "&max-results=700&v=3.0",
      function(response){
if(response.feed.entry.length > 0){
         //Handle Response
       console.log(response);
         var email= [];
console.log(response.feed.entry.length);
        for ( var i= 0 ; i < response.feed.entry.length ; i++)
    {  console.log(i);
          if(response.feed.entry[i].gd$phoneNumber)
           { continue; }
else{
      email[i]= response.feed.entry[i].gd$email[0].address;
      console.log(email[i]); }
 });

Posting the Javascript email array to proccess.php via ajax to filter new users and existing users.


$.post("process.php", { email: email },
    function(Result){
     //use the results to append to show the existing users to new users.
});


process.php


process.php just filter incoming list JSON contact email to existing email database.filter them as new users as object in json ,and existing users with their prof pic we are making another object in JSON.with header JSON/Application we are just encoding output via ajax to index.php

Download the Demo files try in Localhost ,I have added Mailing code via ajax too.If you can Find any error in Javascript (invite.js) just check the console and report error as comments/ or mail me [email protected]

Tuesday, July 08, 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.

Sponsored :





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 [email protected] you can find any bugs comment below.Share is care.

    Thursday, July 03, 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 [email protected] is care.