Friday, November 22, 2013

Debugging Javascript using Console Object

Some of you might have already used  Console Object in javascript to log values of a variable for debugging purposes.

var arr = ['1','2','3','4','5'];

There are some interesting methods in Console API other than log. The details of Console API can be found  here

Note: The link above is for Console API supported by Chrome.

But some of interesting one I would like to mention here are:

1. console.profile();  which is used along with console.profileEnd();

function processPixels() {
  console.profile("Processing pixels");
  // later, after processing pixels

This is used for profiling of time that a method is taking.

2. console.trace(); 

Prints a stack trace from the point where the method was called, including links to the specific lines in the JavaScript source.

3. console.table();

Prints a javascript array or Object in Tabular Format.

It should be noticed that Console Object is not available in all browsers and though debugging javascript with Console Object is Quite Helpful if you forget to remove your Console statements it will give you errors in unsupported browsers.

It can also be possible that you don't want to remove the console Statements so that you can always debug your application.

For this a small code that will take care of all the console.log Statements can be added..
if (typeof console === 'undefined')) var console = { log: function() {} };
It should be noted that the above function takes care of console.log statements only. If we are using other console functions than it should be entered in the console object similiar to the way log function is added.

Friday, April 26, 2013

Bootstrap the Frontend Framework for Non Designers.

So you are a Web Developer having an exciting idea flourishing in your mind.

And you rush to your machine and start writing that awesome code that was never written before.

And now you are ready to show it to your friends with all excitement.

Your friends think the idea is fine but it doesn't looks good and then you get a number of suggestions.

There should be proper use of Typography.
Your Site should be responsive to work in various devices.
You should use proper colors, fonts, paddings, margins.
You should have proper images.....

And you get an endless list of advises all telling you to go and find a designer.Someone who can wrap this brilliant idea of yours in a nice package and make it look like pretty cool thing.

And believe me you have to be lucky enough to find someone who can design that frontend for you. But if you are not that lucky here is Bootstrap for you.

Bootstrap is a sleek, intuitive and powerful frontend framework from Twitter for faster and easier web development. You just need to concentrate on your Development parts and not much on the looks part.

You just need not to worry about how boxes arrange on top of each other or why one css code works in one browser and doesn't works in another one.

It gives you several features like

A 12 column resoponsive Grid.
Several javascript components like tabs, navigation etc.
Standard Typography.
Reset CSS. etc.

For details on Bootstrap's you can visit it's website

It has some examples which will get you started. All you need to take care is apply proper classes as described in the some of the examples.

Saturday, March 23, 2013

Just One thing "JavaScript"

So i am a Web Developer, and like most of you I know a bit of java, php on the server side. A bit of css, html, javascript, jQuery on the client side. Oracle and MySQL on the Database side. And this technology stack is never ending. Every now and then you will have to learn something new. Some new framework may arrive. Some new Library or another cool language.

Now with this so demanding and challenging Market How does the idea of learning just one thing sounds?

What if all you have to learn and understand more or less is just one thing and become a master of it.

What if that one thing is javascript. ?  Yaa you heard me right.
"Javascript" - The same language you have been validating your forms with from Years.

So if i have to write Server Side Code i will write something in Node.js
If i will have to do make a wonderful frontend i will do jQuery.js
If my Frontend javascript is becoming to messy i will use some Frontend MVC framework like Backbone.js
If i need to go Mobile I will learn jQuery Mobile and PhoneGap.js

Wait Wait all that is fine but what about database? You cannot do your databases in Javascript. That seems to much.

Ah well i agree on that but have you heard of MongoDB. Now that is a NoSQL database and uses something called BSON to store the data. Now BSON is nothing new its just Binary form of JSON the javascript Object Notation. So again your data is saved as a javascript object.

With so much focus of Market leaders like Google, Amazon, Microsoft and Yahoo! on these technologies and with ever growing demand of real time Applications Javascript looks to be the future of Web and is no more a toy language to validate your forms. I have started my journey to learning JS what are you waiting for? 

Saturday, December 22, 2012

Creating Apps by extending LinkedIn API.

Last few days I have worked with two small applications that extend power of LinkedIn platform using LinkedIn API.

LinkedIn has opened its platform through its REST API and Javascript API. The platform allows you to

Get Profiles Details
Get Jobs.
Get Details of Companies.
Get Groups.
Get Connections.
Do a People Search.

Idea of the First Application was to find the Job Openings by distance when a user enter his skills.

So if you enter "Java" in skills. You get the Jobs list. Starting from nearest to farthest.

Idea of Second Application was to display Profile Information of users of a company.

So if you enter FirstName LastName and Company Name then you can get detailed profile of a person. If you already have a company intranet where you have firstname and lastname of most of its users you can directly see the profile details without the need to enter the basic information.

Though the steps to connect to linkedin API and documentation is available on  site but i will write the generic steps that i took for using the API.

The REST API allows you to access protected resources available with linkedin with the help of REST URL's for example if you want to search a User with FirstName = "Sushil" LastName="Bharwani" Company="XYZ" then you will send a REST URL request like...

But before hitting this URL and accessing the resources you have to authorize your App through OAuth (An open protocol to allow secure authorization in a simple and standard method from web, mobile and desktop applications).

There are several OAuth Protocol implementations available in Market. I tried first using the PHP_OAuth.dll file but could not configure it so i decided to move to java implementation and found. Java Scribe Library.

The sample application didnt worked fine in the starting since i had to apply some hacks for people search as suggested in some of the similar questions.

The suggestions were on Extending the LinkedInAPI class to add r_fullprofile and r_network fields in the authorization url.

When i did performed these changes and ran the code. It gave me a authorization URL. The URL was supposed to be pasted in browser to get a token. When the token is typed in the desired location an XML based result is returned with details asked in the REST call.

So with a few small modifications i was able to query the Linkedin platform using the REST API services that it has provided.

In the Job search application similar call was made to LinkedIn Job search API which returned me a list of locations with their lat long information in JSON Format. I utilized this info and combined it to google distance API to find the matching jobs by distance.

Friday, August 17, 2012

Finding your user's location through HTML5 Geolocation.

Geolocation is a HTML5 interface that helps in identifying which part of the world you are
located in and sharing this information with people on your wish. The location is identified based on a number of ways like IP Address, WI-FI networks, Cellular Towers, or Specific GPS hardware in your Device.

Though sharing your location to Web seems like a risky thing, you can share the information on your wish to trusted sites and always opt not to share if you dont trust a site. Their are many Websites that use this API to serve products and services near you.

One most popular and widely used site is FourSquare which is a social Networking Site where people can publish their location by check-in into the places of their interest. Each Check-in awards users some points and some of these points can actually be converted into goodies.

Similiar App's can be created using combination of Geo-location API and some of the Map's API's to offer services like Stores, Hospitals, Restaurants in users nearby location.

Some of the Map's API that can be used to find distances, places, driving directions etc are:
Google Maps API.
Microsoft's Bing API.
OpenStreet Maps.
OVI Maps API by Nokia.

Lets quickly look at how to get Users location with the help of Geo-location.

All we will be writing is simple html and javascript to read the location of a User.

<!doctype html>
<title>My Geolocation App</title>
function getLocation(){
     alert("Geolocation API is not supported by your Browser");

function showPosition(){
// implementation below

function showError(){
// implementation below

In the code above we have called a getLocation function which we have defined in the script.

The getLocation function first checks if navigator (Browser) supports the GeoLocation API
If it does not supports it alerts the same.

If browser supports the GeoLocation then we can call the method getCurrentPosition on the geolocation object. The Method takes two callback functions showPosition and showError.

showPosition is called when the cordinates are available.
And showError is called when there is some error in finding the location.

showPosition gets the position object, with the help of which we can get latitude and longitude of users current position. This latitude and longitude information can be further converted into actual name of the place using what we call as reverse Geocoding.

function showPosition(position)
  lat =  position.coords.latitude;
  lng =  position.coords.longitude;
  alert("You are located at Latitude: " + lat + " and Longitude " + lng  );


showError gets the error object. Based on the error code. Different

function showError(error)
    case error.PERMISSION_DENIED:
      alert("User denied the request for Geolocation.");
      alert("Location information is unavailable.");
    case error.TIMEOUT:
      alert("The request to get user location timed out.");
    case error.UNKNOWN_ERROR:
      alert("An unknown error occurred.");

Lets modify showPosition method to apply Reverse Geocoding to get the exact name of the place.
This can be done with the help of Maps API's. We will use Google Map's API for the same. To use google Map's API will fist need to include the javascript api. Using the script tag in the head section.

<script type="text/javascript" src=""></script>

Then we will modify the showPosition function.

function showPosition(position)
  lat =  position.coords.latitude;
  lng =  position.coords.longitude;
  mylocation = new google.maps.LatLng(lat,lng);
   geocoder = new google.maps.Geocoder();
    geocoder.geocode({'latLng': mylocation}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (results[0]) {

myaddress = results[0].formatted_address;
      } else {
        alert("Geocoder failed due to: " + status);


So using simple API's we can find a user's location and by combining it with Map's API's
extend this idea to create wonderful app's to let user find particular services, products and places around him.

Thursday, June 21, 2012

Notes From Multi-Speaker Session on Joomla Selenium Mobile Apps and Online Marketing at Delhi IT Meetup

This Saturday on 16th of June 2012 I gave an Introductory Session on Joomla 1.5 in Delhi IT Meetup group at YMCA Delhi, It was a Multi-Speaker Meetup. There were 3 more topics other than mine and here are my notes from other three Sessions.

Mobile Apps: First Presentation was on Mobile Apps and was given by   . Here are my notes on that.

  1.  Mobile Apps are of Three Types Native Apps, Web Apps, Hybrid Apps.
  2. Native Apps are custom to a particular Device are less portable but have the best of the ability to interact with the Device Hardware.
  3. Web Apps runs in Browsers, These are a cut down or responsive version of your Website.
  4. Hybrid Apps are like native apps residing on your System with a special icon, but utilize some of the Web technologies like JavaScript html5 and css3 that have created a wrapper over the native language of Mobile and are able to make some of the native calls.
  5. phonegap is a widely used api which gives you a set of javascript Objects and methods to interact with device. There are libraries like Sencha Touch, JQuery Mobile etc which forms the presentation layer in the Hybrid Mobile App.
  6. Sumit Demonstrated a Guess Who Application Developed with the help of Microsoft.Phone.controls and have also created Unit Test Cases for his functions using nunit.
  7. A unit test must first fail then you should run it to see if it passes.
Online Marketing: This was third presentation by    Here are my notes.

  1. First and Foremost things to market and sell your website is - To define your offering you should be very clear about what do you want to sell, until you haven't defined it your all other efforts on SEO or Site Optimization are vague.
  2. Develop sensible Content? If you have poured your heart in writing your content people will also definitively love to read it.
  3. Spread a word about your content emails,blogs,Campaigns, SEO, Social Media.
  4. Research the keywords, Modify your content based on Keywords, Define your keywords in the Meta tags, Keep a Keyword Density of 5-6 keywords per page.

What is Selenium: This was fourth and last presentation of the day by . Here are my notes.

  1. Selenium automates Browsers and is mostly used for functional Testing of Web Applications.
  2. Support Multiple Browsers Platforms and Languages.
  3. Can be deployed in Mac Windows and Linux.
  4. Selenium comes in three Variants Selenium 2.0 (selenium webdriver) Selenium 1 (Remote Control) and Selenium IDE.
  5. QTP is a competitive product to selenium but is a paid software.
  6. Selenium IDE just records steps on Firefox, it does not have programming Constructs and is sequential in Execution.
  7. Selenium Remote Control  or Selenium RC was a improved version in which you could write programs in different languages and injects a javascript into browser to automate the functionality of a Web Page.
  8. It had some limitations, One is javascript that is injected into web page can have limitations like it could not execute due to same origin policy, or javascript is disabled into the browser.
  9. selenium webdriver or selenium 2.0 works on this limitation by directly working with the browser using native support for browser.
  10. SauceLabs is a company owned by creator of Selenium who provides selenium automation at Cloud. The benefit of this is that you do not need to to setup different machines with different OS and Browsers to test functionality of your Web App.
  11. Think Future Technologies is working out to on some of the issues that are present with Selenium Web Driver, One of the main issue is that Testing Resources do need to learn programming Languages in order to write a Functional Test. TFT is creating a layer over Selenium Web Driver where they allow Test Engineers to write Test Cases in Excel Files with a well formed set of instructions that can create Functional Tests.

Friday, May 4, 2012

Loosely Typed v/s Strictly Typed Languages and a Code Bug

If somebody has worked in in a strict type language like java he would definitely know that function in java have to return type.

So lets say we need to define a function for sum of two numbers.

We would say:

public int add(int a,int b){
return a + b;

Here we are very sure that we will be returning a value of type integer. but in cases we may want to return a integer and a boolean or a string.

For example say a very common function in String Manipulation indexOf the function returns the index of matching substring.

int indexOf(String str) 

The return type is integer. So to find "Fox" index in "One Sharp Fox" you will write.

"One Sharp Fox".indexOf("Fox"); and will get 10 index.

But what if the match is not found. In these cases you might want to return "No Match Found" or false. But you cannot because the return type is an integer. And therefore you will have to return a number and in this case it is "-1".

and your no found comparision goes like

if("One Sharp Fox".indexOf("Lion") == -1 )

In Case of loosely typed languages we do not have this restriction and we can have more then one type in return.

I was working through one particular bug in our code where we have used a php function


Now php being a loosely typed language can have more than one return type.

Array_search function returns the Key of the Search String in the array in case the match is found. But in case the match is not found it will return false instead of -1 as we have seen in case of java code example.

So for example if we have an array storing car brands.


and if we do 


It will return 2 as a search index.

But if we search "Hyundai" in this array

array_search(" Hyundai",$cars);

We will get false as a return value.

The interesting bug that i found in our code was we had to find the Role of a user.Roles were available in an array having several values and we had to return true if user had "Business Admin" roleThe function that we have used was like 

function adminType($arr){

if(array_search(" Business Admin",$arr)){
return true;
return false;


At first glance it looked perfect to me and was working fine. Until a user complained that She is a Business Admin and is not able to see a particular functionality.

On debugging the code I found that She just had one role and that was "Business Admin" 

So now if we go through the function.

-> $arr = {"Business Admin"}
array_search(" Business Admin",$arr)

will evaluate to 0 the index of the "Business Admin" and   

if(0) will let enter into else statement and return false. So the code will not work as desired.

On searching further I found that there is another function in_array($arr) which will just return true of false if a match is found or not. And i corrected our function by replacing array_search with in_array. 

Overall I believe working in two different programming languages shows you features and their advantages and disadvantages both. Here in PHP though being loosely typed gives us an advantage of having any return type. But then we have to take care of our comparisons very well.