Tag Archives: Programming

Integrating InMobi Ads into jQueryMobile and MoSync based app

Recently I was developing a HTML5 app for a client using jQueryMobile and MoSync Reload with Wormhole Library (an amazing client which let you develop about 70% times faster compared to using native procedures) when I struck with a problem of placing InMobi ads into jQueryMobile sub-pages. If you are familiar with jQueryMobile you would know that it normally fetch pages on ID bases through AJAX and this trick allows it make smooth transitions. While on non-AJAX pages you can simply integrate InMobi’s JavaScript SDK which would be simple JavaScript snippet which you include in your pages and mobile ads will start rolling, however, in case of  AJAX based pages, ad providers normally detect AJAX requests and then refuse to serve ads because of the threat of misuse. I went as far as signing up for an AdMob account but found similar problem there.

I googled through, despite of some questions on stackoverflow, none had the solution (except the solution of turning to non-AJAX based pages which I couldn’t do in any case), I fired up an email to InMobi support and surprisingly got reply with-in an hour linking me to InMobi Mobile Web API.

InMobile Web API require POST request with a certain set of parameters and then return ads in XML format which you then need to parse and display ads wherever you want (including your jQueryMobile sub-pages).

Following is the dissection of request to API:

Basically InMobi Mobile Web API require you to make a POST request along with following parameters:

mk-siteid=xxxxxxXXXXXxxxxxXXXXXX&
mk-version=pr-SPEC-ATATA-20090521&
h-user-agent=Nokia6233%2F2.0&
mk-carrier=117.97.87.6&
format=xml
  • mk-siteid is the ID which you get after registering your app with InMobi through their website, for the purpose of development you can use their test ID which is: 4028cba631d63df10131e1d3191d00cb
  • mk-version is unknow to me but it remains static as it is.
  • h-user-agent is your browser agent which you can easily get through navigator.userAgent
  • mk-carrier is the user IP which you can get through following simple JSON call:
$.getJSON("http://jsonip.appspot.com?callback=?",
function(data){
      userIP = data.ip;
});

and format can always be XML as response will always be.

Moving forward we all know how to make POST request using jQuery along with above parameters:

$.post("http://w.sandbox.inmobi.com/showad.asm", { "mk-siteid": "4028cba631d63df10131e1d3191d00cb", "mk-version": "pr-SPEC-ATATA-20090521", "h-user-agent": navigator.userAgent,
"mk-carrier": localStorage.getItem("userIP"), format: "xml", "mk-ad-slot": 10 },
function(data) {
         console.log(data);
}

URL in above post request is of Sandbox which you should use while developing and when you are ready to go Live, you should make your calls to:

http://w.inmobi.com/showad.asm

At this point if you check your Firebug or Chrome JavaScript developer tools you should see a XML object with AdURL, ImageURL or LinkText in it. The next step would be how we extract this data and display in our page.

First you need to create an ad ‘holding’ area in HTML, in my case I created it just above the closing content div:

<div>
<a id="bannerURL" href=""><img id="playerBanner" src=""></img></a>
</div>

Next you need to expand your data callback function and include XML parsing capability which should extract the ad data out and show it in ad holding HTML.

function(data) {
        $(data).find("Ad").each(function(){ //find Ad tag and loop through each
        $("#bannerURL").attr("href", $(this).find("AdURL").text()) ;  //get AdURL tag and update 
        if($(this).attr("type") != "text"){ //if ad is not text based
           $("#playerBanner").attr("src", $(this).find("ImageURL").text()) ; //update image src 
        }else{ //in case of text based ad
           if($(this).find("LinkText").text() != "invalid ip-address"){ //ip not found
              $("#bannerURL").text($(this).find("LinkText").text()) ; //just update text
           }
        }
        });
}

Above code should be self explanatory as I have added comments against each line, basically you need to loop through all of the XML, finding “Ad” nodes, then going through each node and finding AdURL (where user will go after clicking on Ad) and updating href attribute of our hyperlink tag in holding HTML then InMobi serve ads in two formats, one is text and other is image based banner ads. If it’s not text ad, we will get ImageURL and update the img src in our holding HTML, if it’s text ad then we will simply update text enclosed in “a” tags.

This should complete your ad integration and you should see a sandbox banner or text in your sub-pages. In my case it did:

Complete code is below:

<script>
var userIP;
$.getJSON("http://jsonip.appspot.com?callback=?",
function(data){
        userIP = data.ip;
        localStorage.setItem("userIP", userIP);
});

$.post("http://w.sandbox.inmobi.com/showad.asm", { "mk-siteid": "4028cba631d63df10131e1d3191d00cb", "mk-version": "pr-SPEC-ATATA-20090521", "h-user-agent": navigator.userAgent,
"mk-carrier": localStorage.getItem("userIP"), format: "xml", "mk-ad-slot": 10 },
function(data) {
        $(data).find("Ad").each(function(){ //find Ad tag and loop through each
        $("#bannerURL").attr("href", $(this).find("AdURL").text()) ;  //get AdURL tag and update 
        if($(this).attr("type") != "text"){ //if ad is not text based
           $("#playerBanner").attr("src", $(this).find("ImageURL").text()) ; //update image src 
        }else{ //in case of text based ad
           if($(this).find("LinkText").text() != "invalid ip-address"){ //ip not found
              $("#bannerURL").text($(this).find("LinkText").text()) ; //just update text
           }
        }
        });
});
</script>
<div>
<a id="bannerURL" href=""><img id="playerBanner" src=""></img></a>
</div>

This provides basic integration of ad API and you can build your ad serving structure on top of it. One improvement would be of adding your in-house ads which would show banners linking to your other apps probably as often InMobi simply do not return any ad when you go live, instead it would show:

<!-- mKhoj: No advt for this position -->

So, it would be wise to handle this exception and in this case show your own ad.

Happy coding!

 

 

Get String Length Tool

Just a bit of background, I was working on live data coming through from Java applets into Javascript, there were strings which I had to match, the conditions were like if (thisID === “blahblahblah”) and there were a lot of them, I had to match strings and then do my stuff, the strings were all different, I had to cut each string into sub-strings because there was a variable portion of every string which I didn’t wanted to match. The result you can imagine is that I was sitting there, counting each string character by character and then putting a condition on it. Got the idea of this tool then (obviously I am lazy when it comes to code), just input your string, get the length, put it as a parameter for the Javascript equivalent of PHP substr or maybe use slice() method of JS and move on! Here is tool:

When I actually searched for such a simple tool online to find a string length straight away (like I have seen a simple tool the other day to convert px values in em for CSS), couldn’t find any (maybe there are but I couldn’t find them). However, when you will search you will get lots of functions in every language (C, C++, Java, Javascript etc.) to do that but what if I only want string length and don’t want to write a line, execute it, know the length, erase it and then continue? Well, here is one, it helped me, it may help someone else too!

Happy Coding!

Tutorial: Using IE Developer Tools as Firebug in Mozilla Firefox

There was a time when development for Javascript and CSS was restricted mainly because IE was the only main browser around (basically because it was shipped with your copy of MS Windows) and even the other browsers like Opera and Netscape were not able to listen to the web developer needs. Then came around, Youtube, GMail, Facebook, all of them giving rise to the concept of RIA (Rich Internet Applications) and at the same time Firefox was launched (2004). Firefox was an open source project which in turn allowed thousands of developers around to write what they want as plugins and someone came up with the idea of Firebug, that bug caught the web development community like fire and this plugin has more than 117,085 weekly downloads at the time of this writing. If  you ask any web developer that which plugin is his/her favourite, firebug will always get mentioned at the top and due to all good reasons. I remember coding Javascript before the firebug, when to check and debug a javascript array, I would have to write alert(array.length) and that will pop-up an alert box with array length and then imagine my page is getting updated after 1 second or that array is in a function who is running in loop.. bang! … just to inspect an instruction in that loop, that alert box will appear after every 1 second and ultimately I would have to kill my browser to get rid of it. Not the case any more. Then came around Ajax, I remember JS frameworks such as YUI and jQuery weren’t around in those days and I wrote my first function to make an Ajax request using XMLHttpRequest and after that telling my colleagues that the problem in writing Ajax code is that, you don’t get to see what is happening behind the request. A real nightmare? well we are lucky now, that dark period for client-side web scripting is over.

I don’t think if you are a web developer and you are not aware of firebug but this can be the case that you are a web developer and you are still sticking with the Firefox just because you love firebug and web developer toolbar. Most non-techie people around the globe still love IE (some of them are still on IE6 because that came with their MS Windows XP installation) and they constitute more than 70% of  the total, so if you are going to develop for general public or for a client who just couldn’t understand that why I don’t use IE and why Firefox is my favorite browser, you need to have a look at your web application in IE before shipping it and I am telling you it could always go wrong as you may be calling a function whose one parameter Firefox is ignoring and still executing the code while IE wouldn’t ignore and will stall altogether. Luckily, IE8 comes bundled with IE developer tools (developer tools were around from some time but installing them on and off was a real nightmare, at-least for me). But yes I can hear what you are saying, most of the times, IE will throw an error and it will have very “helpful” error description such as “Unspecified Error” and it will point at totally wrong line in the source code and you will have to do your guess work to eliminate the problem, anyway, with developer tools you could see something in place of nothing.

Enough discussion, here is your 3-minutes crack-on graphical tutorial to use IE developer tools just like your native firebug console and web developer toolbar on Firefox.

First load your desired web page in IE8 which you want to inspect by pressing F12 or by selecting Tools > Developer Tools in IE8.

Second always remember that to inspect a script you need to select it first and start debugging.  In IE Developer Tools > Script tab > Select script > Start Debugging

Selecting Debugging Source

Inspecting Javascript Variables

The most convenient use of firebug for me is of seeing the JS variable values as I develop a complex client-side application. As I discussed above, you don’t want to see alert boxes again and again, IE developer tools, do that for you in two ways.

You can use console to see any output messages. To differentiate between these messages, different console.log APIs are available:

  • console.log
  • console.error
  • console.warn
  • console.info
  • console.assert

My favorite in firebug was console.debug but I left using that long ago because IE Developer Tools do not support console.debug and this will break your code. Secondly firebug allows you to format those error message, IE  Developer Tools do not support that (or at-least something I am not aware of). The output of these console messages will be exactly like something you see in firebug. For the record, you write code like this:

var myvar = 0;
console.log(myvar);
console.error(myvar);
console.warn(myvar);
console.info(myvar);

IE Developer Tools Log Messages

The other way is slightly different, can be used for the same purpose but is related to only variables, you are able to see variable values at your breakpoints, so you have the time to analyze them.

To create a break point, hover your mouse on the line number you want to mark as break point and click, a red dot will appear on the left beside the line number, now when you will start debugging, browser will stop executing it just before the line you marked as break point.

Then go to the right hand pane of IE developer tools and select Watch > Click to add the variables you want to see and developer tools will let you know the variable name, value and type at the break point.

Watch variables at break point

You are able to change variable values at this moment as well, just when you are watching a variable in Watch tab, open Console tab and assign new value to the variable to see how it will behave after you hit Play again. In the same manner you are able run any instructions which are not in source code but you want to run them at break point to analyze the effect.

Part 1: Running script at break point

Part 2: IE Developer Tools console with new variable value

Now go back to the Watch tab and see the updated value.

Part 3: Watch updated variable value

Profiling Javascript

Another important need for a web developer who do not think that JS is just a scripting language and it just has bits like getting an element and changing it’s value at run time etc. but it is so important that the developer actually needs to optimize the run times and to see how many times a function is getting called, JS profiler is just what saved our lives in firebug, it is here too in IE Developer Tools.

You need to select Profiler tab in Developer Tools > Start Profiling, do something on your page like refresh or wait for sometime if that is something you want to check and then Stop Profiling, Developer Tools will give you a complete report of JS activity done in that time span, listing Functions, count of the calls made and inclusive, exclusive time etc. Same information can be seen in Call Tree view if you select call tree from Current View.

Javascript Profiler

View Generated Source

If you ever worked with Ajax, you would probably know the importance of seeing the DOM once your Ajax call has been made and your DOM has got updated. In Firefox I use Web Developer Toolbar to see Generated Source, in IE Developer Tools, you can view the same by going into View > Source > DOM, you can view the Original source code and the selected element’s DOM as well.

View Generated Source

Outlining Elements on the Page

Another important tool of firebug is when you can outline the elements on your page to see where they are residing, like the divs or tables etc. I specifically use Web Developer Toolbar instead to outline and see the cause of cosmetic issues. IE Developer Tools comes with this solution as well. You can go to Outline in menu and select the type of elements you want to outline or to select an individual element you can go to Any Element and add the name of the element to view outline.

Outlining Elements

There are plenty of other functions which Developer Tools support like you can also see the CSS of an individual element by going to Find > Select Element by Click and then clicking on the element, just like you do for inspect element tool in firebug. You can view Images information or disable scripts, CSS, change the browser modes to render the page in IE7, validate your HTML (this will take you straight to W3C website and if you are working on localhost on your system, chances are W3C will refuse to check your code), CSS etc and you can even re size your browser to see your pages in different resolutions.

There is no doubt, Microsoft was under pressure from the developer community to bundle the developer tools with IE because after the arrival of Firefox, the whole development scenario got changed and developers want to develop more rich applications for the web. I personally havn’t adopted IE for my core development but it is handy to check my code every now and then in IE to see if everything is fine there and if not, using Developer Tools makes the life easier by allowing you to debug the code.

Feel free to comment if you have anything to say!

Javascript: Power tools of Firebug for developers and designers

Every developer now adays use Firebug to tackle the Javascript, which is obviously one of the most powerful innovation in the domain of Web. However, most people don’t know the correct use of this amazing addon of Firefox.

Let’s quickly get to the business, I will let  you know the most useful power tools of Firebug.

console.debug(obj)
Ever you get caught using too many alert messages, eventually I was using this to see the outputs, inserting an

alert("yes")

on nearly everyline while debugging to see if my variables are passing fine. In that case, if I have a loop of 100 times and some values is going wrong in it, I would have to hit my enter button for 100 times to get rid of that alert box while trying to debug the code. Don’t do it, if you have Firebug installed, use

console.debug("yes")

and it will nicely print the debug output in Firebug console. No more buggy alert boxes.

console.count()
Ever wondered how many times your javascript function is getting called, feeling the need to go and declare a global scope variable and then increment it and then print its value to see? Don’t do this if you have Firebug, instead use

console.count("name")

at the line of code you want to see the execution count and your Firebug console will let you know how many times this line of code was executed. Handy, eh?

Command Line functions
Those of you who are not familiar with command line of Firebug would say, what? well same was my reaction, however, I found it and it is really very useful. You can inspect a visual object on your page through the use of that little inspect arrow on the top left corner of your Firebug console, however, for example you cant see that element visually and still you want to see it, check bottom right side of your Firebug console, you will see a red square over there, open that and that is your Firebug command line console, type

$('id')

replace id with the id of the element you want to inspect and it will show you that element in your console. In my case, I wrote this command

$('bew')

and output in the console was

>>>$('bew')
<input id="bew" type="hidden" value="BEEPJScript>
Happy debugging!

Top 6 must-have Firefox addons for Web developers and designers

There are lots of blog posts about the must have addons for Firefox if you are a web developer. In fact mozilla’s addon library has lots of lots of them but only some are very useful and now a days when speed of the application along with its cross browser compatibility is a critical issue, some addons are far most critical and every web developer or designer should have them in his/her arsenal.

Firefox addons for Web Developers and Designers

Firefox addons for Web Developers and Designers

6-Measure it

Measure it has a simple philosophy, it lets you measure any thing on your browser screen, amazing when you are working with graphics of the site, you can measure area, it will let you know the width and height in pixels and then you put that information in your Adobe photoshop and make images of exact size.

5- Color Zilla

Color Zilla is your color adviser, very often I feel the need of picking a color on the webpage to export that in my Adobe photoshop, this addon has a fantastic eye dropper tool which let you pick exact color of any image on your web page and then you use that. It comes with some other goodies like page zoomer as well.

4- IE Tab

If you are a web developer, the chances are you already hate Internet Explorer but this web browser is still the most widely used web browser around the world and the reason behind is Microsoft Windows. Anyway if you are developing in Firefox you always need to see your web pages in IE that if they rendering alright in that browser, this addon saves you opening an IE. It adds a tab to your web browser and if you click that tab, it opens the same page with IE render engine. Bingo! You have got IE in your Firefox.

3- YSlow

A friend of mine introduced me to this addon very recently and after I discovered it, I went on thinking how I made my websites without this tool. Yes, it is “why slow”, install it, it will require Fire bug to be installed and then see your website loading, how much is the size of your web page, what is the rating of your website in terms of speed of loading and not just that, it actually advise you what you lack in your web page like you need to include CSS at the top, refer Javascript as include files etc. and it has got wonderful tools of itself, one of my favourite is Smush it, it actually takes all the images on your web page, turn them into PNGs and let you download them, once you have them, you can just go back to your images directory and replace your images, in my case, the difference was in kbs which is obviously huge when we speak of web pages.

2- Web Developer Toolbar

Is that ever happened that you are working in Ajax and your primary tool is IE or Firefox and then you want to see the source code which Ajax has generated? A real bugger eh? Well there are lots of lots of features in web developer toolbar like you can actually see the DIV  (borderless creatures, you can never see them without any external tool) formation on the page, look at the table information etc. but my favorite is View Generated Source option, which let you see whatever is current HTML of your web page.

1 – Firebug

This is the most important piece of code primary developed to serve web developer’s community. Javascript is a real pain to debug in IE (until IE8, it has got its fire bug too now, bundled with IE8 as Developer Tools) but in Firefox you have got fire bug to fire Javascript bugs. It not only let you debug your Javascript or HTML, it becomes very handy when you work on Ajax, it’s XHR panel in Net panel is designed to let you know, how many calls you have made to the server through XHTTPRequest object. Many other important modules like yslow require Firebug to run in. A true life saver!

If I have missed any addon which you think is crucial to be on every web developer/designer Firefox, please comment with its name, chances are that I don’t know about that addon as yet. Thanks!

Microsoft releases new OS project called Barrelfish for next generation

As all we know next generation systems are not single core as the case at the moment as well. Probably the system on which you are viewing this blog is already a multi-core system. The software we are running today are becoming more resource hungry as with the each passing day. Current operating systems are already capable of talking to each other on the level of boxes and they tend to share some resources as well, such as memory and processing power. But as the multi-core systems are around from more over than a couple of years now, there wasn’t an OS which talks at core level with the parallel system. Well, now we have!

Team at Microsoft, Cambridge has announced on 15th September, 2009 that they are working on project code-named Barrelfish in collaboration with ETH Zurich and this new OS is supposed to talk and share resources at core levels with the other systems. It is also a rumour that this new OS will be free as it uses several software libraries which are available under BSD license. However, we need to wait for the more details to come out and yes you can view a snap shot of this project in here.

Get Adobe Flash player